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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cenfoiOS/ImpesaiOSCourse
|
NewsWithRealm/News/NewsViewController.swift
|
1
|
2003
|
//
// NewsViewController.swift
// News
//
// Created by Cesar Brenes on 5/18/17.
// Copyright © 2017 César Brenes Solano. All rights reserved.
//
import UIKit
import RealmSwift
class NewsViewController: UIViewController {
var news: List<News>?
var categoryType = 0
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerCustomCell(identifier: NewsTableViewCell.getTableViewCellIdentifier())
createAddButton()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
news = RealmManager.getAllNews(categoryType: categoryType)
tableView.reloadData()
}
func createAddButton(){
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction))
navigationItem.rightBarButtonItem = addButton
}
func addAction(){
let viewController = storyboard!.instantiateViewController(withIdentifier: NewsDetailTableViewController.getViewControllerIdentifier()) as! NewsDetailTableViewController
viewController.categoryType = categoryType
navigationController?.pushViewController(viewController, animated: true)
}
}
extension NewsViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let news = news else {
return 0
}
return news.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NewsTableViewCell.getTableViewCellIdentifier()) as! NewsTableViewCell
cell.setupCell(news: news![indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
|
mit
|
150c9721a7620333465bca5d9e740036
| 29.784615 | 177 | 0.69965 | 5.717143 | false | false | false | false |
chengxianghe/MissGe
|
MissGe/Pods/ObjectMapper/Sources/CodableTransform.swift
|
2
|
2323
|
//
// CodableTransform.swift
// ObjectMapper
//
// Created by Jari Kalinainen on 10/10/2018.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Tristan Himmelman
//
// 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
/// Transforms JSON dictionary to Codable type T and back
open class CodableTransform<T: Codable>: TransformType {
public typealias Object = T
public typealias JSON = Any
public init() {}
open func transformFromJSON(_ value: Any?) -> Object? {
guard let dict = value as? [String: Any], let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
return nil
}
do {
let decoder = JSONDecoder()
let item = try decoder.decode(T.self, from: data)
return item
} catch {
return nil
}
}
open func transformToJSON(_ value: T?) -> JSON? {
guard let item = value else {
return nil
}
do {
let encoder = JSONEncoder()
let data = try encoder.encode(item)
let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return dictionary
} catch {
return nil
}
}
}
|
mit
|
9f2eafbcabf20a898185519a80911164
| 34.738462 | 130 | 0.661644 | 4.51068 | false | false | false | false |
davidbjames/Unilib
|
Unilib/Sources/Math.swift
|
1
|
23303
|
//
// Math.swift
// Unilib
//
// Created by David James on 12/15/16.
// Copyright © 2016-2021 David B James. All rights reserved.
//
import Foundation
import CoreGraphics
// MARK: - Clamp
/// Clamp a float value to ensure it is between
/// a minimum and maximum bounds (inclusive).
public func clamp(_ value:CGFloat, min:CGFloat?, max:CGFloat?) -> CGFloat {
switch (min, max) {
case let (min?, max?) :
return clampMin(clampMax(value, max:max), min:min)
case (let min?, nil) :
return clampMin(value, min:min)
case (nil, let max?) :
return clampMax(value, max:max)
case (nil, nil) :
return value
}
}
/// Clamp a float value to ensure it is greater than
/// or equal to a minimum value.
public func clampMin(_ value:CGFloat, min:CGFloat) -> CGFloat {
return value >= min ? value : min
}
/// Clamp a float value to ensure it is less than
/// or equal to a maximum value.
public func clampMax(_ value:CGFloat, max:CGFloat) -> CGFloat {
return value <= max ? value : max
}
/// Clamp a float value to ensure it is within a range (inclusive).
public func clamp(_ value:CGFloat, to range:ClosedRange<CGFloat>) -> CGFloat {
return clamp(value, min:range.lowerBound, max:range.upperBound)
}
/// Clamp a potentially inconsistent float value to a nearby multiple
/// rounding the multiple up or down per standard rounding.
public func clamp(_ input:CGFloat, toMultipleOf multiple:CGFloat) -> CGFloat {
let fudged = input + (multiple / 2)
let times = floor(fudged / multiple)
return times * multiple
// Tests:
// Input:
// [-132.5, -90.0, -60.0, -0.0, 0.5, -0.6, 64.9, 65.0, 90.0, 129.2, 130.4, 130.6, 259.4, 262.7, 263.0]
// .. with multiple of 130 ..
// Output:
// [-130.0, -130.0, 0.0, 0.0, 0.0, 0.0, 0.0, 130.0, 130.0, 130.0, 130.0, 130.0, 260.0, 260.0, 260.0]
}
public extension CGFloat {
/// Clamp a float value to ensure it is between
/// a minimum and maximum bounds (inclusive).
func clamped(min:CGFloat, max:CGFloat) -> CGFloat {
return clamp(self, min:min, max:max)
}
/// Clamp a float value to ensure it is within a range (inclusive).
func clamped(to range:ClosedRange<CGFloat>) -> CGFloat {
return clamp(self, to:range)
}
/// Clamp a potentially inconsistent float value to a nearby multiple
/// rounding the multiple up or down per standard rounding.
func clamped(toMultipleOf multiple:CGFloat) -> CGFloat {
return clamp(self, toMultipleOf:multiple)
}
}
/// Given a constant value that lies within an input range
/// produce a new value mapped to it's relative position
/// in an output range.
/// Optionally, invert the output mapping (i.e. so that
/// low input values map to high output values and vice versa).
public func map<F:BinaryFloatingPoint>(_ constant:F, from inputRange:ClosedRange<F>, to outputRange:ClosedRange<F>, inverted:Bool = false) -> F {
// Linear transform (mapping):
// MappedActual = (Actual-Min)/(Max-Min) * (MappedMax-MappedMin) + MappedMin
// Example: compute offset based on device height
// let offset = (height-minHeight)/(maxHeight-minHeight) * (maxOffset-minOffset) + minOffset.
// or, map(1024, from:768...1024, to:30...50)
// Given a larger device (1024 iPad 12.5):
// 50 = (1024-768)/(1024-768) * (50-30) + 30
// or medium size device (834 - iPad 10.5)
// 35.2 = ( 834-768)/(1024-768) * (50-30) + 30
// or smaller device (768 iPad 9.7):
// 30 = ( 768-768)/(1024-768) * (50-30) + 30
// inverted output range (iPad 12.5 to 9.7 respectively):
// 30 = (1024-768)/(1024-768) * (30-50) + 50
// 44.8 = ( 834-768)/(1024-768) * (30-50) + 50
// 50 = ( 834-768)/(1024-768) * (30-50) + 50
let inputMapping = (constant - inputRange.lowerBound) / (inputRange.upperBound - inputRange.lowerBound)
if inverted {
return inputMapping * (outputRange.lowerBound - outputRange.upperBound) + outputRange.upperBound
} else {
return inputMapping * (outputRange.upperBound - outputRange.lowerBound) + outputRange.lowerBound
}
}
// Versions of map() for closed ranges (...) ^^, and half-open ranges (..<) vv
/// Given a constant value that lies within an input range
/// produce a new value mapped to it's relative position
/// in an output range.
/// Optionally, invert the output mapping (i.e. so that
/// low input values map to high output values and vice versa).
public func map<F:BinaryFloatingPoint>(_ constant:F, from inputRange:Range<F>, to outputRange:Range<F>, inverted:Bool = false) -> F {
let inputMapping = (constant - inputRange.lowerBound) / (inputRange.upperBound - inputRange.lowerBound)
if inverted {
return inputMapping * (outputRange.lowerBound - outputRange.upperBound) + outputRange.upperBound
} else {
return inputMapping * (outputRange.upperBound - outputRange.lowerBound) + outputRange.lowerBound
}
}
/// Get the distance between two points, squared.
///
/// Use this method if all you need is to make a
/// comparison, but for actual distance use
/// `distance()` which may be less performant.
public func distanceSquared<F:BinaryFloatingPoint>(from point1:CGPoint, to point2:CGPoint) -> F {
let x = point2.x - point1.x
let y = point2.y - point1.y
return (F(x*x) + F(y*y))
}
/// Get the absolute distance between two points.
///
/// This uses square root which may cause performance
/// issues. See also `distanceSquared()` if all you
/// need is to compare distances.
public func distance<F:BinaryFloatingPoint>(from point1:CGPoint, to point2:CGPoint) -> F {
let x = point2.x - point1.x
let y = point2.y - point1.y
return (F(x*x) + F(y*y)).squareRoot()
// (this could be replaced with hypotf(xDistance, yDistance)
// if tests reveal any performance difference)
// See C3.PointConvertible.delta() which uses hypotf()
}
/// Get the absolute distance between two corners of
/// a rectangle, given the rectangle's width and height.
///
/// Be wary of using this in critical/iterative code
/// because it must determine square root which is
/// apparently not-so-performant.
public func diagonalDistance<F:BinaryFloatingPoint>(width:F, height:F) -> F {
return F(pow(CGFloat(width), 2) + pow(CGFloat(height), 2)).squareRoot()
}
public extension Array where Element:BinaryFloatingPoint {
/// Increment this array of floats by one or specified value,
/// optionally specifying which indices to increment.
func increment(_ value:Element? = nil, indices:Set<Int>? = nil) -> Self {
_incrementer(operator:.add, incrementValue:value, customIndices:indices)
}
/// Decrement this array of floats by one or specified value,
/// optionally specifying which indices to change.
func decrement(_ value:Element? = nil, indices:Set<Int>? = nil) -> Self {
_incrementer(operator:.subtract, incrementValue:value, customIndices:indices)
}
/// Multiple this array of floats by two or specified value,
/// optionally specifying which indices to change.
func multiply(_ value:Element? = nil, indices:Set<Int>? = nil) -> Self {
_incrementer(operator:.multiply, incrementValue:value, customIndices:indices)
}
/// Divide this array of floats by two or specified value,
/// optionally specifying which indices to change.
func divide(_ value:Element? = nil, indices:Set<Int>? = nil) -> Self {
_incrementer(operator:.divide, incrementValue:value, customIndices:indices)
}
private enum IncrementerOperator {
case add, subtract, multiply, divide
}
private func _incrementer(operator:IncrementerOperator, incrementValue:Element?, customIndices:Set<Int>?) -> Self {
indices.map { index -> Element in
let current = self[index]
if let indices = customIndices, !indices.contains(index) {
return current
}
switch `operator` {
case .add : return current + (incrementValue ?? 1.0)
case .subtract : return current - (incrementValue ?? 1.0)
case .multiply : return current * (incrementValue ?? 2.0)
case .divide : return current / (incrementValue ?? 2.0)
}
}
}
}
// MARK: - Angle
/// Simple struct representing an angle between 0º and 360º +/-
/// As this is ExpressibleByFloatLiteral, anywhere that takes
/// an Angle may also take a Double in it's place.
public/**/ struct Angle : ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public/**/ typealias FloatLiteralType = Double
public/**/ typealias IntegerLiteralType = Int
public private(set) var degrees:Double
/// Angle in radians
/// Useful for core graphics/animations rotations
public var radians:Double {
return degrees.radians
}
/// Half the current rotation angle
public var half:Angle {
return self * 0.5
}
/// Double the current rotation angle
public var double:Angle {
return self * 2
}
/// Quadruple the current rotation angle
public var quadruple:Angle {
return self * 4
}
public/**/ init(floatLiteral value: Angle.FloatLiteralType) {
self.degrees = value
}
public/**/ init(integerLiteral value: Int) {
self.degrees = Double(value)
}
public/**/ init?(_ degrees:Double?) {
guard let _degrees = degrees else { return nil }
self.degrees = _degrees
}
public/**/ init?(_ degrees:CGFloat?) {
self.init(degrees.flatMap { Double($0) })
}
// Creating new angles from simple arithmetic operators
public static func + (lhs:Angle, rhs:Double) -> Angle {
return Angle(floatLiteral:lhs.degrees + rhs)
}
public static func - (lhs:Angle, rhs:Double) -> Angle {
return Angle(floatLiteral:lhs.degrees - rhs)
}
public static func / (lhs:Angle, rhs:Double) -> Angle {
return Angle(floatLiteral:lhs.degrees / rhs)
}
public static func * (lhs:Angle, rhs:Double) -> Angle {
return Angle(floatLiteral:lhs.degrees * rhs)
}
}
// TODO: ✅ Genericize this, e.g. <T:BinaryFloatingPoint>
/// Container for functions that can be reused between
/// extensions of floating point types like Double or CGFloat.
/// Since iOS/Swift forces us to go back and forth between
/// Double and CGFloat, this prevents some code duplication,
/// though you still need to implement the method name
/// in each extension.
fileprivate struct FloatingPointHelper {
/// Obtain a random positive/negative floating point number with an
/// outer bound number (upper bound for positive numbers, negative bound
/// for negative numbers). Negative numbers will return a random value
/// between upper and 0, e.g. -10 returns a number between -10 and -0.
static func randomDecimal(withBounds bounds:Double = 0.0) -> Double {
// Median Deviation
// 0.0 = 0.0 to 0.0 // no deviation (bounds 0.0)
// 0.1 = 0.0 to 0.1 // small deviation
// 0.5 = 0.0 to 0.5 // deviation up to 0.5 (half factor)
// 1.0 = 0.0 to 1.0 // deviation up to 1 (1x factor)
// 1.1 = 0.0 to 1.1 // etc
// 10.0 = 0.0 to 10.0 //
// -0.1 = -0.1 to -0.0 // negative deviation
// -0.5 = -0.5 to -0.0 // small negative deviation
// -1.0 = -1.0 to -0.0 // etc
// -1.1 = -1.1 to -0.0 //
// -10.0 = -10.0 to -0.0 //
var start:Double = 0.0
var end:Double = 0.0
if bounds != 0.0 {
if bounds > 0.0 {
end = abs(bounds)
} else {
start = bounds
}
}
let range = Int(start * 100)...Int(end * 100)
return Double(Int.random(in:range)) / 100
}
/// Obtain a random positive/negative factor number between a fraction and
/// a whole number (e.g. 0.5 and 1.5) by providing a positive/negative
/// "deviation" value. The deviation determines the range difference from 1.0
/// so that a deviation of 0 equals a range of 1.0...1.0, which will only
/// return 1.0. A deviation of 0.1 means a range of possible values in
/// 0.9...1.1, etc. Deviations greater than 1.0 pin their bottom bound to
/// 0.0, for example a deviation of 1.1 results in a random value in
/// 0.0...2.1 (and not -0.1...2.1). Negative values act as expected and
/// return random negative numbers, e.g. deviation of -2.0 returns a
/// random value in -3.0...-0.0
static func randomFactor(from deviation:Double = 0.0) -> Double {
// Deviation outside of -1...+1 is pinned to 0 (start or end)
// Deviation Factors
// 0.0 = 1.0 to 1.0 // factor of 1x only
// 0.1 = 0.9 to 1.1 // near 1x factor +/-
// 0.5 = 0.5 to 1.5 // half to 1.5 times
// 1.0 = 0.0 to 2.0 // up to 2x
// 1.1 = 0.0 to 2.1 // etc (from 0 to n+1x)
// 10.0 = 0.0 to 11.0 // etc
// -0.1 = -1.1 to -0.9 // near 1x negative factor
// -0.5 = -1.5 to -0.5 // half to 1.5x negative factor
// -1.0 = -2.0 to 0.0 // up to 2x negative factor
// -1.1 = -2.1 to 0.0 // etc
// -10.0 = -11.0 to 0.0 // etc
var start:Double = 1.0
var end:Double = 1.0
if deviation != 0.0 {
if deviation > 0.0 {
start = max(1.0 - deviation, 0.0)
end = 1.0 + deviation
} else {
start = -(1.0 + abs(deviation))
end = min(-(1.0 - abs(deviation)), -0.0)
}
}
let range = Int(start * 100)...Int(end * 100)
return Double(Int.random(in:range)) / 100
}
/// Obtain a random positive factor number between a fraction
/// a whole number (e.g. 0.5 and 1.5) by providing a positive
/// initial factor value (e.g. 1.5). The initial value provided
/// is the "target" factor which is above or below 1.0. The
/// return value will be within the range between that target
/// value and it's "mirror value on the opposite side of 1.0".
/// E.g. providing 1.5 will return a random value between 0.5 and 1.5.
static func randomOneFactor(from value:Double = 0.0) -> Double {
let deviation = abs(1 - value)
return randomFactor(from:deviation)
}
/// Obtain a random positive/negative deviation number from a median
/// number with the range being 0.0...(median*2).
static func randomMedianDeviation(from median:Double = 0.0) -> Double {
// Median Deviation
// 0.0 = 0.0 to 0.0 // no deviation
// 0.1 = 0.0 to 0.2 // small deviation
// 0.5 = 0.0 to 1.0 // deviation up to 1 (factor of 1?)
// 1.0 = 0.0 to 2.0 // deviation up to 2 (2x factor?)
// 1.1 = 0.0 to 2.2 // etc
// 10.0 = 0.0 to 20.0 //
// -0.1 = -0.2 to -0.0 // negative deviation
// -0.5 = -1.0 to -0.0 // small negative deviation
// -1.0 = -2.0 to -0.0 // etc
// -1.1 = -2.2 to -0.0 //
// -10.0 = -20.0 to -0.0 //
var start:Double = 0.0
var end:Double = 0.0
if median != 0.0 {
if median > 0.0 {
end = median * 2
} else {
start = -(abs(median) * 2)
end = -0.0
}
}
let range = Int(start * 100)...Int(end * 100)
return Double(Int.random(in:range)) / 100
}
/// Obtain a random positive/negative deviation number from an upper
/// bound number using 0 as the median. e.g. 0.1 would return a random
/// number between -0.1 and 0.1, 10 would return between -10 and 10.
static func randomZeroDeviation(from upper:Double = 0.0) -> Double {
let unsigned = abs(upper)
// Median Deviation
// 0.0 = 0.0 to 0.0 // no deviation
// 0.1 = -0.1 to 0.1 // small deviation
// 0.5 = -0.5 to 0.5 // deviation up to 0.5 (half factor)
// 1.0 = -1.0 to 1.0 // deviation up to 1 (1x factor)
// 1.1 = -1.1 to 1.1 // etc
let start:Double = -(unsigned)
let end:Double = unsigned
let range = Int(start * 100)...Int(end * 100)
return Double(Int.random(in:range)) / 100
// print("---------------------------")
// print("upper :", upper)
// print("start :", start)
// print("end :", end)
// print("range :", range)
// print("deviation:", deviation)
}
}
public extension Double {
/// Convert this float (assumed to be "degrees") to radians.
var radians:Double {
return self * (Double.pi / 180.0)
}
/// Convert this float (assumed to be "radians") to degrees.
var degrees:Double {
return self * (180.0 / Double.pi)
}
/// Based on a floating point number, get a random value up
/// to that number. The number provided represents the outer
/// bounds, positive or negative.
/// Example:
/// -1.0.randomDecimal provides a random number betwen -1.0 and 0.0
/// See private static method for more info.
var randomDecimal:Double {
return FloatingPointHelper.randomDecimal(withBounds: self)
}
/// Based on a floating point number, get a random factor between
/// (1 - number) and (1 + number), with the resulting value being useful
/// to decrease/increase some other value "by a factor of".
/// Supports negative numbers.
/// Example:
/// 0.1.randomFactor provides a random number between 0.9 and 1.1
/// let size = 100.0
/// let scaled = size * 0.1.randomFactor
/// scaled // between 90 and 110
/// See private static method for more info.
var randomFactor:Double {
return FloatingPointHelper.randomFactor(from:self)
}
/// Based on a floating point number, get a random factor between
/// that number and it's converse on the opposite side of 1.0
/// with the resulting value being useful to decrease/increase
/// some other value "by a factor of".
/// Example:
/// 1.5.randomOneFactor provides a random number between 0.5 and 1.5
var randomOneFactor:Double {
return FloatingPointHelper.randomOneFactor(from:self)
}
/// Based on a floating point number, get a random value between
/// 0.0 and (number x 2). The number provided represents the
/// "median deviation", with the lower bounds being 0.0 and
/// the upper bounds being the number doubled (thus making the
/// number the middle value). e.g. for 1: 0 lower -- 1 median -- 2 upper.
/// Supports negative numbers.
/// Example:
/// 1.0.randomMedianDeviation provides a random number between 0.0 and 2.0
/// let increment = 2.0
/// let randomIncrement = increment + 1.0.randomMedianDeviation
/// randomIncrement // between 2.0 and 4.0
/// See private static method for more info.
var randomMedianDeviation:Double {
return FloatingPointHelper.randomMedianDeviation(from: self)
}
/// Based on a floating point number, get a random value between
/// -number and +number. The number provided represents the
/// lower (negative) and upper (positive) bounds of the range.
/// Example:
/// 0.1.randomZeroDeviation provides a random number between -0.1 and 0.1
/// let position = 150.0
/// let randomPosition = position + 10.randomZeroDeviation
/// randomPosition // between 140 and 160
/// See private static method for more info.
var randomZeroDeviation:Double {
return FloatingPointHelper.randomZeroDeviation(from: self)
}
}
public extension CGFloat {
/// Convert this float (assumed to be "degrees") to radians.
var radians:CGFloat {
return self * (Double.pi / 180.0)
}
/// Convert this float (assumed to be "radians") to degrees.
var degrees:CGFloat {
return self * (180.0 / Double.pi)
}
/// Based on a floating point number, get a random value up
/// to that number. The number provided represents the outer
/// bounds, positive or negative.
/// Example:
/// -1.0.randomDecimal provides a random number betwen -1.0 and 0.0
/// See private static method for more info.
var randomDecimal:CGFloat {
return FloatingPointHelper.randomDecimal(withBounds: self)
}
/// Based on a floating point number, get a random factor between
/// (1 - number) and (1 + number), with the resulting value being useful
/// to decrease/increase some other value "by a factor of".
/// Supports negative numbers.
/// Example:
/// 0.1.randomFactor provides a random number between 0.9 and 1.1
/// let size = 100.0
/// let scaled = size * 0.1.randomFactor
/// scaled // between 90 and 110
/// See private static method for more info.
var randomFactor:CGFloat {
return FloatingPointHelper.randomFactor(from:self)
}
/// Based on a floating point number, get a random factor between
/// that number and it's converse on the opposite side of 1.0
/// with the resulting value being useful to decrease/increase
/// some other value "by a factor of".
/// Example:
/// 1.5.randomOneFactor provides a random number between 0.5 and 1.5
var randomOneFactor:CGFloat {
return FloatingPointHelper.randomOneFactor(from:self)
}
/// Based on a floating point number, get a random value between
/// 0.0 and (number x 2). The number provided represents the
/// "median deviation", with the lower bounds being 0.0 and
/// the upper bounds being the number doubled (thus making the
/// number the middle value). e.g. for 1: 0 lower -- 1 median -- 2 upper.
/// Supports negative numbers.
/// Example:
/// 1.0.randomMedianDeviation provides a random number between 0.0 and 2.0
/// let increment = 2.0
/// let randomIncrement = increment + 1.0.randomMedianDeviation
/// randomIncrement // between 2.0 and 4.0
/// See private static method for more info.
var randomMedianDeviation:CGFloat {
return FloatingPointHelper.randomMedianDeviation(from: self)
}
/// Based on a floating point number, get a random value between
/// -number and +number. The number provided represents the
/// lower (negative) and upper (positive) bounds of the range.
/// Example:
/// 0.1.randomZeroDeviation provides a random number between -0.1 and 0.1
/// let position = 150.0
/// let randomPosition = position + 10.randomZeroDeviation
/// randomPosition // between 140 and 160
/// See private static method for more info.
var randomZeroDeviation:CGFloat {
return FloatingPointHelper.randomZeroDeviation(from: self)
}
}
|
mit
|
61d9d423026beea31d567ef4b5db2d31
| 38.893836 | 145 | 0.610997 | 3.816841 | false | false | false | false |
ActionKit/ActionKit
|
ActionKit/UIGestureRecognizer+ActionKit.swift
|
1
|
3609
|
//
// UIGestureRecognizer+ActionKit.swift
// ActionKit
//
// Created by Kevin Choi, Benjamin Hendricks on 7/17/14.
// Licensed under the terms of the MIT license
//
import Foundation
import UIKit
// MARK:- UIGestureRecognizer actions
extension ActionKitSingleton {
func addGestureClosure(_ gesture: UIGestureRecognizer, name: String, closure: ActionKitClosure) {
let set: Set<String>? = gestureRecognizerToName[gesture]
var newSet: Set<String>
if let nonOptSet = set {
newSet = nonOptSet
} else {
newSet = Set<String>()
}
newSet.insert(name)
gestureRecognizerToName[gesture] = newSet
controlToClosureDictionary[.gestureRecognizer(gesture, name)] = closure
}
func canRemoveGesture(_ gesture: UIGestureRecognizer, _ name: String) -> Bool {
if let _ = controlToClosureDictionary[.gestureRecognizer(gesture, name)] {
return true
} else {
return false
}
}
func removeGesture(_ gesture: UIGestureRecognizer, name: String) {
if canRemoveGesture(gesture, name) {
controlToClosureDictionary[.gestureRecognizer(gesture, name)] = nil
}
}
@objc(runGesture:)
func runGesture(_ gesture: UIGestureRecognizer) {
for gestureName in gestureRecognizerToName[gesture] ?? Set<String>() {
if let closure = controlToClosureDictionary[.gestureRecognizer(gesture, gestureName)] {
switch closure {
case .noParameters(let voidClosure):
voidClosure()
case .withGestureParameter(let gestureClosure):
gestureClosure(gesture)
default:
assertionFailure("Gesture closure not found, nor void closure")
break
}
}
}
}
}
public extension UIGestureRecognizer {
var actionKitNames: Set<String>? {
get { return ActionKitSingleton.shared.gestureRecognizerToName[self] } set { }
}
}
extension UIGestureRecognizer {
public func clearActionKit() {
let gestureRecognizerNames = ActionKitSingleton.shared.gestureRecognizerToName[self]
ActionKitSingleton.shared.gestureRecognizerToName[self] = nil
for gestureRecognizerName in gestureRecognizerNames ?? Set<String>() {
ActionKitSingleton.shared.removeGesture(self, name: gestureRecognizerName)
}
}
@objc public convenience init(_ name: String = "", _ gestureClosure: @escaping ActionKitGestureClosure) {
self.init(target: ActionKitSingleton.shared, action: #selector(ActionKitSingleton.runGesture(_:)))
self.addClosure(name, gestureClosure: gestureClosure)
}
@nonobjc
public convenience init(_ name: String = "", _ closure: @escaping ActionKitVoidClosure) {
self.init(target: ActionKitSingleton.shared, action: #selector(ActionKitSingleton.runGesture(_:)))
self.addClosure(name, closure: closure)
}
public func addClosure(_ name: String, gestureClosure: @escaping ActionKitGestureClosure) {
ActionKitSingleton.shared.addGestureClosure(self, name: name, closure: .withGestureParameter(gestureClosure))
}
public func addClosure(_ name: String, closure: @escaping ActionKitVoidClosure) {
ActionKitSingleton.shared.addGestureClosure(self, name: name, closure: .noParameters(closure))
}
public func removeClosure(_ name: String) {
ActionKitSingleton.shared.removeGesture(self, name: name)
}
}
|
mit
|
362fa0deeb69c4a917e5473f352943d0
| 36.206186 | 117 | 0.656692 | 4.910204 | false | false | false | false |
frootloops/swift
|
test/Inputs/conditional_conformance_subclass.swift
|
1
|
13819
|
public func takes_p1<T: P1>(_: T.Type) {}
public protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
public protocol P2 {}
public protocol P3 {}
public struct IsP2: P2 {}
public class Base<A> {}
extension Base: P1 where A: P2 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Base.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW(%T32conditional_conformance_subclass4BaseC.0** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
// CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.0*, %T32conditional_conformance_subclass4BaseC.0** %0
// CHECK-NEXT: call swiftcc void @_T032conditional_conformance_subclass4BaseCA2A2P2RzlE6normalyyF(i8** %"\CF\84_0_0.P2", %T32conditional_conformance_subclass4BaseC.0* swiftself [[SELF]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Base.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyqd__AA2P3Rd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
// CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8
// CHECK-NEXT: call swiftcc void @_T032conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyqd__AA2P3Rd__lF(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public class SubclassGeneric<T>: Base<T> {}
public class SubclassConcrete: Base<IsP2> {}
public class SubclassGenericConcrete: SubclassGeneric<IsP2> {}
public func subclassgeneric_generic<T: P2>(_: T.Type) {
takes_p1(SubclassGeneric<T>.self)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T032conditional_conformance_subclass23subclassgeneric_genericyxmAA2P2RzlF(%swift.type*, %swift.type* %T, i8** %T.P2) #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass15SubclassGenericCMa(%swift.type* %T)
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 1)
// CHECK-NEXT: call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness table accessor for Base : P1
// CHECK-LABEL: define{{( protected)?}} i8** @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa(%swift.type*, i8***, i64) #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.tables = alloca %swift.witness_table_slice, align 8
// CHECK-NEXT: [[TABLES_PTR:%.*]] = getelementptr inbounds %swift.witness_table_slice, %swift.witness_table_slice* %conditional.tables, i32 0, i32 0
// CHECK-NEXT: store i8*** %1, i8**** [[TABLES_PTR]], align 8
// CHECK-NEXT: [[COUNT_PTR:%.*]] = getelementptr inbounds %swift.witness_table_slice, %swift.witness_table_slice* %conditional.tables, i32 0, i32 1
// CHECK-NEXT: store i64 %2, i64* [[COUNT_PTR]], align 8
// CHECK-NEXT: [[CAST_CONDITIONAL_TABLES:%.*]] = bitcast %swift.witness_table_slice* %conditional.tables to i8**
// CHECK-NEXT: [[TABLE:%.*]] = call i8** @swift_rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWG, %swift.type* %0, i8** [[CAST_CONDITIONAL_TABLES]])
// CHECK-NEXT: ret i8** [[TABLE]]
// CHECK-NEXT: }
public func subclassgeneric_concrete() {
takes_p1(SubclassGeneric<IsP2>.self)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T032conditional_conformance_subclass24subclassgeneric_concreteyyF() #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa()
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl()
// CHECK-NEXT: call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete SubclassGeneric<IsP2> : Base.
// CHECK-LABEL: define linkonce_odr hidden i8** @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl() #2 {
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL, align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa()
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T032conditional_conformance_subclass4IsP2VAA0E0AAWP, i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 1)
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: %6 = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** %6
// CHECK-NEXT: }
public func subclassconcrete() {
takes_p1(SubclassConcrete.self)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T032conditional_conformance_subclass16subclassconcreteyyF() #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass16SubclassConcreteCMa()
// CHECK-NEXT: [[SubclassConcrete_P1:%.*]] = call i8** @_T032conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl()
// CHECK-NEXT: call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define linkonce_odr hidden i8** @_T032conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl() #2 {
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @_T032conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL, align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass16SubclassConcreteCMa()
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T032conditional_conformance_subclass4IsP2VAA0E0AAWP, i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 1)
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @_T032conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: %6 = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** %6
// CHECK-NEXT: }
public func subclassgenericconcrete() {
takes_p1(SubclassGenericConcrete.self)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T032conditional_conformance_subclass23subclassgenericconcreteyyF() #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass23SubclassGenericConcreteCMa()
// CHECK-NEXT: [[SubclassGenericConcrete_P1:%.*]] = call i8** @_T032conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl()
// CHECK-NEXT: call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define linkonce_odr hidden i8** @_T032conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl() #2 {
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @_T032conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL, align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass23SubclassGenericConcreteCMa()
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T032conditional_conformance_subclass4IsP2VAA0E0AAWP, i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 1)
// CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @_T032conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: %6 = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** %6
// CHECK-NEXT: }
// witness tabel instantiation function for Base : P1
// CHECK-LABEL: define internal void @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWI(i8**, %swift.type*, i8**) #0 {
// CHECK-NEXT: entry:
// CHECK-NEXT: [[CONDITIONAL_TABLE_SLICE:%.*]] = bitcast i8** %2 to %swift.witness_table_slice*
// CHECK-NEXT: [[TABLES_PTR:%.*]] = getelementptr inbounds %swift.witness_table_slice, %swift.witness_table_slice* [[CONDITIONAL_TABLE_SLICE]], i32 0, i32 0
// CHECK-NEXT: [[TABLES:%.*]] = load i8***, i8**** [[TABLES_PTR]], align 8
// CHECK-NEXT: [[COUNT_PTR:%.*]] = getelementptr inbounds %swift.witness_table_slice, %swift.witness_table_slice* [[CONDITIONAL_TABLE_SLICE]], i32 0, i32 1
// CHECK-NEXT: [[COUNT:%.*]] = load i64, i64* [[COUNT_PTR]], align 8
// CHECK-NEXT: [[COND:%.*]] = icmp eq i64 [[COUNT]], 1
// CHECK-NEXT: br i1 [[COND]], label %cont, label %bad_witness_table_count
// CHECK: cont:
// CHECK-NEXT: [[A_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0
// CHECK-NEXT: [[A_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1
// CHECK-NEXT: [[A_P2:%.*]] = load i8**, i8*** [[A_P2_SRC]], align 8
// CHECK-NEXT: [[CAST_A_P2_DEST:%.*]] = bitcast i8** [[A_P2_DEST]] to i8***
// CHECK-NEXT: store i8** [[A_P2]], i8*** [[CAST_A_P2_DEST]], align 8
// CHECK-NEXT: ret void
// CHECK: bad_witness_table_count:
// CHECK-NEXT: call void @llvm.trap()
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
|
apache-2.0
|
d856e830e8158d6cfa624cdf2368abdf
| 67.073892 | 376 | 0.689558 | 3.106091 | false | false | false | false |
cplaverty/KeitaiWaniKani
|
WaniKaniKit/Database/Coder/AuxiliaryMeaning+DatabaseCodable.swift
|
1
|
1920
|
//
// AuxiliaryMeaning+BulkDatabaseCodable.swift
// WaniKaniKit
//
// Copyright © 2019 Chris Laverty. All rights reserved.
//
import FMDB
private let table = Tables.auxiliaryMeanings
extension AuxiliaryMeaning: BulkDatabaseCodable {
static func read(from database: FMDatabase, id: Int) throws -> [AuxiliaryMeaning] {
let query = """
SELECT \(table.type), \(table.meaning)
FROM \(table)
WHERE \(table.subjectID) = ?
ORDER BY \(table.index)
"""
let resultSet = try database.executeQuery(query, values: [id])
defer { resultSet.close() }
var items = [AuxiliaryMeaning]()
while resultSet.next() {
items.append(AuxiliaryMeaning(type: resultSet.string(forColumn: table.type.name)!,
meaning: resultSet.string(forColumn: table.meaning.name)!))
}
return items
}
static func read(from database: FMDatabase, ids: [Int]) throws -> [Int: [AuxiliaryMeaning]] {
var items = [Int: [AuxiliaryMeaning]]()
items.reserveCapacity(ids.count)
for id in ids {
items[id] = try read(from: database, id: id)
}
return items
}
static func write(items: [AuxiliaryMeaning], to database: FMDatabase, id: Int) throws {
try database.executeUpdate("DELETE FROM \(table) WHERE \(table.subjectID) = ?", values: [id])
let query = """
INSERT OR REPLACE INTO \(table)
(\(table.subjectID.name), \(table.index.name), \(table.type.name), \(table.meaning.name))
VALUES (?, ?, ?, ?)
"""
for (index, item) in items.enumerated() {
let values: [Any] = [
id, index, item.type, item.meaning
]
try database.executeUpdate(query, values: values)
}
}
}
|
mit
|
0eadb623b18ff6463595359ee1958d7f
| 30.983333 | 101 | 0.560709 | 4.473193 | false | false | false | false |
JevinSidhu/Prologue
|
Koloda/ViewController.swift
|
9
|
2160
|
//
// ViewController.swift
// TinderCardsSwift
//
// Created by Eugene Andreyev on 4/23/15.
// Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//
import UIKit
import Koloda
private var numberOfCards: UInt = 5
class ViewController: UIViewController, KolodaViewDataSource, KolodaViewDelegate {
@IBOutlet weak var kolodaView: KolodaView!
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
kolodaView.dataSource = self
kolodaView.delegate = self
}
//MARK: IBActions
@IBAction func leftButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Left)
}
@IBAction func rightButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Right)
}
@IBAction func undoButtonTapped() {
kolodaView?.revertAction()
}
//MARK: KolodaViewDataSource
func kolodaNumberOfCards(koloda: KolodaView) -> UInt {
return numberOfCards
}
func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView {
return UIImageView(image: UIImage(named: "Card_like_\(index + 1)"))
}
func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView? {
return NSBundle.mainBundle().loadNibNamed("OverlayView",
owner: self, options: nil)[0] as? OverlayView
}
//MARK: KolodaViewDelegate
func kolodaDidSwipedCardAtIndex(koloda: KolodaView, index: UInt, direction: SwipeResultDirection) {
//Example: loading more cards
if index >= 3 {
numberOfCards = 6
kolodaView.reloadData()
}
}
func kolodaDidRunOutOfCards(koloda: KolodaView) {
//Example: reloading
kolodaView.resetCurrentCardNumber()
}
func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://yalantis.com/")!)
}
func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool {
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
c3fdd4a86312aa55b16fa96bf621daa2
| 25.666667 | 103 | 0.649537 | 4.931507 | false | false | false | false |
nanthi1990/SwiftCharts
|
SwiftCharts/Axis/ChartAxisYLowLayerDefault.swift
|
7
|
1781
|
//
// ChartAxisYLowLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartAxisYLowLayerDefault: ChartAxisYLayerDefault {
override var low: Bool {return true}
override var lineP1: CGPoint {
return CGPointMake(self.p1.x + self.lineOffset, self.p1.y)
}
override var lineP2: CGPoint {
return CGPointMake(self.p2.x + self.lineOffset, self.p2.y)
}
private lazy var labelsOffset: CGFloat = {
return self.axisTitleLabelsWidth + self.settings.axisTitleLabelsToLabelsSpacing
}()
private lazy var lineOffset: CGFloat = {
return self.labelsOffset + self.labelsMaxWidth + self.settings.labelsToAxisSpacingY + self.settings.axisStrokeWidth
}()
override func initDrawers() {
self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: 0)
self.labelDrawers = self.generateLabelDrawers(offset: self.labelsOffset)
self.lineDrawer = self.generateLineDrawer(offset: self.lineOffset)
}
override func generateLineDrawer(#offset: CGFloat) -> ChartLineDrawer {
let halfStrokeWidth = self.settings.axisStrokeWidth / 2 // we want that the stroke ends at the end of the frame, not be in the middle of it
let p1 = CGPointMake(self.p1.x + offset - halfStrokeWidth, self.p1.y)
let p2 = CGPointMake(self.p2.x + offset - halfStrokeWidth, self.p2.y)
return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor)
}
override func labelsX(#offset: CGFloat, labelWidth: CGFloat) -> CGFloat {
let labelsXRight = self.p1.x + offset + self.labelsMaxWidth
return labelsXRight - labelWidth
}
}
|
apache-2.0
|
58279fb3edc73e54ce12e97191fb5225
| 36.104167 | 147 | 0.691185 | 4.14186 | false | false | false | false |
JGiola/swift-corelibs-foundation
|
Foundation/Unit.swift
|
3
|
68702
|
/*
NSUnitConverter describes how to convert a unit to and from the base unit of its dimension. Use the NSUnitConverter protocol to implement new ways of converting a unit.
*/
open class UnitConverter : NSObject {
/*
The following methods perform conversions to and from the base unit of a unit class's dimension. Each unit is defined against the base unit for the dimension to which the unit belongs.
These methods are implemented differently depending on the type of conversion. The default implementation in NSUnitConverter simply returns the value.
These methods exist for the sole purpose of creating custom conversions for units in order to support converting a value from one kind of unit to another in the same dimension. NSUnitConverter is an abstract class that is meant to be subclassed. There is no need to call these methods directly to do a conversion -- the correct way to convert a measurement is to use [NSMeasurement measurementByConvertingToUnit:]. measurementByConvertingToUnit: uses the following 2 methods internally to perform the conversion.
When creating a custom unit converter, you must override these two methods to implement the conversion to and from a value in terms of a unit and the corresponding value in terms of the base unit of that unit's dimension in order for conversion to work correctly.
*/
/*
This method takes a value in terms of a unit and returns the corresponding value in terms of the base unit of the original unit's dimension.
@param value Value in terms of the unit class
@return Value in terms of the base unit
*/
open func baseUnitValue(fromValue value: Double) -> Double {
return value
}
/*
This method takes in a value in terms of the base unit of a unit's dimension and returns the equivalent value in terms of the unit.
@param baseUnitValue Value in terms of the base unit
@return Value in terms of the unit class
*/
open func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
return baseUnitValue
}
}
open class UnitConverterLinear : UnitConverter, NSSecureCoding {
open private(set) var coefficient: Double
open private(set) var constant: Double
public convenience init(coefficient: Double) {
self.init(coefficient: coefficient, constant: 0)
}
public init(coefficient: Double, constant: Double) {
self.coefficient = coefficient
self.constant = constant
}
open override func baseUnitValue(fromValue value: Double) -> Double {
return value * coefficient + constant
}
open override func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
return (baseUnitValue - constant) / coefficient
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let coefficient = aDecoder.decodeDouble(forKey: "NS.coefficient")
let constant = aDecoder.decodeDouble(forKey: "NS.constant")
self.init(coefficient: coefficient, constant: constant)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.coefficient, forKey:"NS.coefficient")
aCoder.encode(self.constant, forKey:"NS.constant")
}
public static var supportsSecureCoding: Bool { return true }
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitConverterLinear else {
return false
}
if self === other {
return true
}
return self.coefficient == other.coefficient
&& self.constant == other.constant
}
}
private class UnitConverterReciprocal : UnitConverter, NSSecureCoding {
private var reciprocal: Double
fileprivate init(reciprocal: Double) {
self.reciprocal = reciprocal
}
fileprivate override func baseUnitValue(fromValue value: Double) -> Double {
return reciprocal / value
}
fileprivate override func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
return reciprocal / baseUnitValue
}
fileprivate required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let reciprocal = aDecoder.decodeDouble(forKey: "NS.reciprocal")
self.init(reciprocal: reciprocal)
}
fileprivate func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.reciprocal, forKey:"NS.reciprocal")
}
fileprivate static var supportsSecureCoding: Bool { return true }
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitConverterReciprocal else {
return false
}
if self === other {
return true
}
return self.reciprocal == other.reciprocal
}
}
/*
NSUnit is the base class for all unit types (dimensional and dimensionless).
*/
open class Unit : NSObject, NSCopying, NSSecureCoding {
open private(set) var symbol: String
public required init(symbol: String) {
self.symbol = symbol
}
open func copy(with zone: NSZone?) -> Any {
return self
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard let symbol = aDecoder.decodeObject(forKey: "NS.symbol") as? String
else { return nil }
self.symbol = symbol
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.symbol._bridgeToObjectiveC(), forKey:"NS.symbol")
}
public static var supportsSecureCoding: Bool { return true }
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? Unit else {
return false
}
if self === other {
return true
}
return self.symbol == other.symbol
}
}
open class Dimension : Unit {
open private(set) var converter: UnitConverter
public required init(symbol: String, converter: UnitConverter) {
self.converter = converter
super.init(symbol: symbol)
}
/*
This class method returns an instance of the dimension class that represents the base unit of that dimension.
e.g.
NSUnitSpeed *metersPerSecond = [NSUnitSpeed baseUnit];
*/
open class func baseUnit() -> Self {
fatalError("*** You must override baseUnit in your class to define its base unit.")
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard
let symbol = aDecoder.decodeObject(forKey: "NS.symbol") as? String,
let converter = aDecoder.decodeObject(forKey: "NS.converter") as? UnitConverter
else { return nil }
self.converter = converter
super.init(symbol: symbol)
}
public required init(symbol: String) {
let T = type(of: self)
fatalError("\(T) must be initialized with designated initializer \(T).init(symbol: String, converter: UnitConverter)")
}
open override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.converter, forKey:"NS.converter")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? Dimension else {
return false
}
if self === other {
return true
}
return super.isEqual(object) && self.converter == other.converter
}
}
public final class UnitAcceleration : Dimension {
/*
Base unit - metersPerSecondSquared
*/
private struct Symbol {
static let metersPerSecondSquared = "m/s²"
static let gravity = "g"
}
private struct Coefficient {
static let metersPerSecondSquared = 1.0
static let gravity = 9.81
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var metersPerSecondSquared: UnitAcceleration {
get {
return UnitAcceleration(symbol: Symbol.metersPerSecondSquared, coefficient: Coefficient.metersPerSecondSquared)
}
}
public class var gravity: UnitAcceleration {
get {
return UnitAcceleration(symbol: Symbol.gravity, coefficient: Coefficient.gravity)
}
}
public override class func baseUnit() -> UnitAcceleration {
return .metersPerSecondSquared
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitAcceleration else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitAngle : Dimension {
/*
Base unit - degrees
*/
private struct Symbol {
static let degrees = "°"
static let arcMinutes = "ʹ"
static let arcSeconds = "ʹʹ"
static let radians = "rad"
static let gradians = "grad"
static let revolutions = "rev"
}
private struct Coefficient {
static let degrees = 1.0
static let arcMinutes = 1.0 / 60.0
static let arcSeconds = 1.0 / 3600.0
static let radians = 180.0 / .pi
static let gradians = 0.9
static let revolutions = 360.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var degrees: UnitAngle {
get {
return UnitAngle(symbol: Symbol.degrees, coefficient: Coefficient.degrees)
}
}
public class var arcMinutes: UnitAngle {
get {
return UnitAngle(symbol: Symbol.arcMinutes, coefficient: Coefficient.arcMinutes)
}
}
public class var arcSeconds: UnitAngle {
get {
return UnitAngle(symbol: Symbol.arcSeconds, coefficient: Coefficient.arcSeconds)
}
}
public class var radians: UnitAngle {
get {
return UnitAngle(symbol: Symbol.radians, coefficient: Coefficient.radians)
}
}
public class var gradians: UnitAngle {
get {
return UnitAngle(symbol: Symbol.gradians, coefficient: Coefficient.gradians)
}
}
public class var revolutions: UnitAngle {
get {
return UnitAngle(symbol: Symbol.revolutions, coefficient: Coefficient.revolutions)
}
}
public override class func baseUnit() -> UnitAngle {
return .degrees
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitAngle else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitArea : Dimension {
/*
Base unit - squareMeters
*/
private struct Symbol {
static let squareMegameters = "Mm²"
static let squareKilometers = "km²"
static let squareMeters = "m²"
static let squareCentimeters = "cm²"
static let squareMillimeters = "mm²"
static let squareMicrometers = "µm²"
static let squareNanometers = "nm²"
static let squareInches = "in²"
static let squareFeet = "ft²"
static let squareYards = "yd²"
static let squareMiles = "mi²"
static let acres = "ac"
static let ares = "a"
static let hectares = "ha"
}
private struct Coefficient {
static let squareMegameters = 1e12
static let squareKilometers = 1e6
static let squareMeters = 1.0
static let squareCentimeters = 1e-4
static let squareMillimeters = 1e-6
static let squareMicrometers = 1e-12
static let squareNanometers = 1e-18
static let squareInches = 0.00064516
static let squareFeet = 0.092903
static let squareYards = 0.836127
static let squareMiles = 2.59e+6
static let acres = 4046.86
static let ares = 100.0
static let hectares = 10000.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var squareMegameters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMegameters, coefficient: Coefficient.squareMegameters)
}
}
public class var squareKilometers: UnitArea {
get {
return UnitArea(symbol: Symbol.squareKilometers, coefficient: Coefficient.squareKilometers)
}
}
public class var squareMeters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMeters, coefficient: Coefficient.squareMeters)
}
}
public class var squareCentimeters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareCentimeters, coefficient: Coefficient.squareCentimeters)
}
}
public class var squareMillimeters: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMillimeters, coefficient: Coefficient.squareMillimeters)
}
}
public class var squareMicrometers: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMicrometers, coefficient: Coefficient.squareMicrometers)
}
}
public class var squareNanometers: UnitArea {
get {
return UnitArea(symbol: Symbol.squareNanometers, coefficient: Coefficient.squareNanometers)
}
}
public class var squareInches: UnitArea {
get {
return UnitArea(symbol: Symbol.squareInches, coefficient: Coefficient.squareInches)
}
}
public class var squareFeet: UnitArea {
get {
return UnitArea(symbol: Symbol.squareFeet, coefficient: Coefficient.squareFeet)
}
}
public class var squareYards: UnitArea {
get {
return UnitArea(symbol: Symbol.squareYards, coefficient: Coefficient.squareYards)
}
}
public class var squareMiles: UnitArea {
get {
return UnitArea(symbol: Symbol.squareMiles, coefficient: Coefficient.squareMiles)
}
}
public class var acres: UnitArea {
get {
return UnitArea(symbol: Symbol.acres, coefficient: Coefficient.acres)
}
}
public class var ares: UnitArea {
get {
return UnitArea(symbol: Symbol.ares, coefficient: Coefficient.ares)
}
}
public class var hectares: UnitArea {
get {
return UnitArea(symbol: Symbol.hectares, coefficient: Coefficient.hectares)
}
}
public override class func baseUnit() -> UnitArea {
return .squareMeters
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitArea else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitConcentrationMass : Dimension {
/*
Base unit - gramsPerLiter
*/
private struct Symbol {
static let gramsPerLiter = "g/L"
static let milligramsPerDeciliter = "mg/dL"
static let millimolesPerLiter = "mmol/L"
}
private struct Coefficient {
static let gramsPerLiter = 1.0
static let milligramsPerDeciliter = 0.01
static let millimolesPerLiter = 18.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var gramsPerLiter: UnitConcentrationMass {
get {
return UnitConcentrationMass(symbol: Symbol.gramsPerLiter, coefficient: Coefficient.gramsPerLiter)
}
}
public class var milligramsPerDeciliter: UnitConcentrationMass {
get {
return UnitConcentrationMass(symbol: Symbol.milligramsPerDeciliter, coefficient: Coefficient.milligramsPerDeciliter)
}
}
public class func millimolesPerLiter(withGramsPerMole gramsPerMole: Double) -> UnitConcentrationMass {
return UnitConcentrationMass(symbol: Symbol.millimolesPerLiter, coefficient: Coefficient.millimolesPerLiter * gramsPerMole)
}
public override class func baseUnit() -> UnitConcentrationMass {
return UnitConcentrationMass.gramsPerLiter
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitConcentrationMass else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitDispersion : Dimension {
/*
Base unit - partsPerMillion
*/
private struct Symbol {
static let partsPerMillion = "ppm"
}
private struct Coefficient {
static let partsPerMillion = 1.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var partsPerMillion: UnitDispersion {
get {
return UnitDispersion(symbol: Symbol.partsPerMillion, coefficient: Coefficient.partsPerMillion)
}
}
public override class func baseUnit() -> UnitDispersion {
return .partsPerMillion
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitDispersion else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitDuration : Dimension {
/*
Base unit - seconds
*/
private struct Symbol {
static let seconds = "s"
static let minutes = "m"
static let hours = "h"
}
private struct Coefficient {
static let seconds = 1.0
static let minutes = 60.0
static let hours = 3600.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var seconds: UnitDuration {
get {
return UnitDuration(symbol: Symbol.seconds, coefficient: Coefficient.seconds)
}
}
public class var minutes: UnitDuration {
get {
return UnitDuration(symbol: Symbol.minutes, coefficient: Coefficient.minutes)
}
}
public class var hours: UnitDuration {
get {
return UnitDuration(symbol: Symbol.hours, coefficient: Coefficient.hours)
}
}
public override class func baseUnit() -> UnitDuration {
return .seconds
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitDuration else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitElectricCharge : Dimension {
/*
Base unit - coulombs
*/
private struct Symbol {
static let coulombs = "C"
static let megaampereHours = "MAh"
static let kiloampereHours = "kAh"
static let ampereHours = "Ah"
static let milliampereHours = "mAh"
static let microampereHours = "µAh"
}
private struct Coefficient {
static let coulombs = 1.0
static let megaampereHours = 3.6e9
static let kiloampereHours = 3600000.0
static let ampereHours = 3600.0
static let milliampereHours = 3.6
static let microampereHours = 0.0036
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var coulombs: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.coulombs, coefficient: Coefficient.coulombs)
}
}
public class var megaampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.megaampereHours, coefficient: Coefficient.megaampereHours)
}
}
public class var kiloampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.kiloampereHours, coefficient: Coefficient.kiloampereHours)
}
}
public class var ampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.ampereHours, coefficient: Coefficient.ampereHours)
}
}
public class var milliampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.milliampereHours, coefficient: Coefficient.milliampereHours)
}
}
public class var microampereHours: UnitElectricCharge {
get {
return UnitElectricCharge(symbol: Symbol.microampereHours, coefficient: Coefficient.microampereHours)
}
}
public override class func baseUnit() -> UnitElectricCharge {
return .coulombs
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricCharge else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitElectricCurrent : Dimension {
/*
Base unit - amperes
*/
private struct Symbol {
static let megaamperes = "MA"
static let kiloamperes = "kA"
static let amperes = "A"
static let milliamperes = "mA"
static let microamperes = "µA"
}
private struct Coefficient {
static let megaamperes = 1e6
static let kiloamperes = 1e3
static let amperes = 1.0
static let milliamperes = 1e-3
static let microamperes = 1e-6
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var megaamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.megaamperes, coefficient: Coefficient.megaamperes)
}
}
public class var kiloamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.kiloamperes, coefficient: Coefficient.kiloamperes)
}
}
public class var amperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.amperes, coefficient: Coefficient.amperes)
}
}
public class var milliamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.milliamperes, coefficient: Coefficient.milliamperes)
}
}
public class var microamperes: UnitElectricCurrent {
get {
return UnitElectricCurrent(symbol: Symbol.microamperes, coefficient: Coefficient.microamperes)
}
}
public override class func baseUnit() -> UnitElectricCurrent {
return .amperes
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricCurrent else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitElectricPotentialDifference : Dimension {
/*
Base unit - volts
*/
private struct Symbol {
static let megavolts = "MV"
static let kilovolts = "kV"
static let volts = "V"
static let millivolts = "mV"
static let microvolts = "µV"
}
private struct Coefficient {
static let megavolts = 1e6
static let kilovolts = 1e3
static let volts = 1.0
static let millivolts = 1e-3
static let microvolts = 1e-6
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var megavolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.megavolts, coefficient: Coefficient.megavolts)
}
}
public class var kilovolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.kilovolts, coefficient: Coefficient.kilovolts)
}
}
public class var volts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.volts, coefficient: Coefficient.volts)
}
}
public class var millivolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.millivolts, coefficient: Coefficient.millivolts)
}
}
public class var microvolts: UnitElectricPotentialDifference {
get {
return UnitElectricPotentialDifference(symbol: Symbol.microvolts, coefficient: Coefficient.microvolts)
}
}
public override class func baseUnit() -> UnitElectricPotentialDifference {
return .volts
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricPotentialDifference else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitElectricResistance : Dimension {
/*
Base unit - ohms
*/
private struct Symbol {
static let megaohms = "MΩ"
static let kiloohms = "kΩ"
static let ohms = "Ω"
static let milliohms = "mΩ"
static let microohms = "µΩ"
}
private struct Coefficient {
static let megaohms = 1e6
static let kiloohms = 1e3
static let ohms = 1.0
static let milliohms = 1e-3
static let microohms = 1e-6
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var megaohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.megaohms, coefficient: Coefficient.megaohms)
}
}
public class var kiloohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.kiloohms, coefficient: Coefficient.kiloohms)
}
}
public class var ohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.ohms, coefficient: Coefficient.ohms)
}
}
public class var milliohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.milliohms, coefficient: Coefficient.milliohms)
}
}
public class var microohms: UnitElectricResistance {
get {
return UnitElectricResistance(symbol: Symbol.microohms, coefficient: Coefficient.microohms)
}
}
public override class func baseUnit() -> UnitElectricResistance {
return .ohms
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitElectricResistance else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitEnergy : Dimension {
/*
Base unit - joules
*/
private struct Symbol {
static let kilojoules = "kJ"
static let joules = "J"
static let kilocalories = "kCal"
static let calories = "cal"
static let kilowattHours = "kWh"
}
private struct Coefficient {
static let kilojoules = 1e3
static let joules = 1.0
static let kilocalories = 4184.0
static let calories = 4.184
static let kilowattHours = 3600000.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var kilojoules: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.kilojoules, coefficient: Coefficient.kilojoules)
}
}
public class var joules: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.joules, coefficient: Coefficient.joules)
}
}
public class var kilocalories: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.kilocalories, coefficient: Coefficient.kilocalories)
}
}
public class var calories: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.calories, coefficient: Coefficient.calories)
}
}
public class var kilowattHours: UnitEnergy {
get {
return UnitEnergy(symbol: Symbol.kilowattHours, coefficient: Coefficient.kilowattHours)
}
}
public override class func baseUnit() -> UnitEnergy {
return .joules
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitEnergy else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitFrequency : Dimension {
/*
Base unit - hertz
*/
private struct Symbol {
static let terahertz = "THz"
static let gigahertz = "GHz"
static let megahertz = "MHz"
static let kilohertz = "kHz"
static let hertz = "Hz"
static let millihertz = "mHz"
static let microhertz = "µHz"
static let nanohertz = "nHz"
}
private struct Coefficient {
static let terahertz = 1e12
static let gigahertz = 1e9
static let megahertz = 1e6
static let kilohertz = 1e3
static let hertz = 1.0
static let millihertz = 1e-3
static let microhertz = 1e-6
static let nanohertz = 1e-9
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var terahertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.terahertz, coefficient: Coefficient.terahertz)
}
}
public class var gigahertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.gigahertz, coefficient: Coefficient.gigahertz)
}
}
public class var megahertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.megahertz, coefficient: Coefficient.megahertz)
}
}
public class var kilohertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.kilohertz, coefficient: Coefficient.kilohertz)
}
}
public class var hertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.hertz, coefficient: Coefficient.hertz)
}
}
public class var millihertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.millihertz, coefficient: Coefficient.millihertz)
}
}
public class var microhertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.microhertz, coefficient: Coefficient.microhertz)
}
}
public class var nanohertz: UnitFrequency {
get {
return UnitFrequency(symbol: Symbol.nanohertz, coefficient: Coefficient.nanohertz)
}
}
public override class func baseUnit() -> UnitFrequency {
return .hertz
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitFrequency else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitFuelEfficiency : Dimension {
/*
Base unit - litersPer100Kilometers
*/
private struct Symbol {
static let litersPer100Kilometers = "L/100km"
static let milesPerImperialGallon = "mpg"
static let milesPerGallon = "mpg"
}
private struct Coefficient {
static let litersPer100Kilometers = 1.0
static let milesPerImperialGallon = 282.481
static let milesPerGallon = 235.215
}
private convenience init(symbol: String, reciprocal: Double) {
self.init(symbol: symbol, converter: UnitConverterReciprocal(reciprocal: reciprocal))
}
public class var litersPer100Kilometers: UnitFuelEfficiency {
get {
return UnitFuelEfficiency(symbol: Symbol.litersPer100Kilometers, reciprocal: Coefficient.litersPer100Kilometers)
}
}
public class var milesPerImperialGallon: UnitFuelEfficiency {
get {
return UnitFuelEfficiency(symbol: Symbol.milesPerImperialGallon, reciprocal: Coefficient.milesPerImperialGallon)
}
}
public class var milesPerGallon: UnitFuelEfficiency {
get {
return UnitFuelEfficiency(symbol: Symbol.milesPerGallon, reciprocal: Coefficient.milesPerGallon)
}
}
public override class func baseUnit() -> UnitFuelEfficiency {
return .litersPer100Kilometers
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitFuelEfficiency else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitLength : Dimension {
/*
Base unit - meters
*/
private struct Symbol {
static let megameters = "Mm"
static let kilometers = "km"
static let hectometers = "hm"
static let decameters = "dam"
static let meters = "m"
static let decimeters = "dm"
static let centimeters = "cm"
static let millimeters = "mm"
static let micrometers = "µm"
static let nanometers = "nm"
static let picometers = "pm"
static let inches = "in"
static let feet = "ft"
static let yards = "yd"
static let miles = "mi"
static let scandinavianMiles = "smi"
static let lightyears = "ly"
static let nauticalMiles = "NM"
static let fathoms = "ftm"
static let furlongs = "fur"
static let astronomicalUnits = "ua"
static let parsecs = "pc"
}
private struct Coefficient {
static let megameters = 1e6
static let kilometers = 1e3
static let hectometers = 1e2
static let decameters = 1e1
static let meters = 1.0
static let decimeters = 1e-1
static let centimeters = 1e-2
static let millimeters = 1e-3
static let micrometers = 1e-6
static let nanometers = 1e-9
static let picometers = 1e-12
static let inches = 0.0254
static let feet = 0.3048
static let yards = 0.9144
static let miles = 1609.34
static let scandinavianMiles = 10000.0
static let lightyears = 9.461e+15
static let nauticalMiles = 1852.0
static let fathoms = 1.8288
static let furlongs = 201.168
static let astronomicalUnits = 1.496e+11
static let parsecs = 3.086e+16
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var megameters: UnitLength {
get {
return UnitLength(symbol: Symbol.megameters, coefficient: Coefficient.megameters)
}
}
public class var kilometers: UnitLength {
get {
return UnitLength(symbol: Symbol.kilometers, coefficient: Coefficient.kilometers)
}
}
public class var hectometers: UnitLength {
get {
return UnitLength(symbol: Symbol.hectometers, coefficient: Coefficient.hectometers)
}
}
public class var decameters: UnitLength {
get {
return UnitLength(symbol: Symbol.decameters, coefficient: Coefficient.decameters)
}
}
public class var meters: UnitLength {
get {
return UnitLength(symbol: Symbol.meters, coefficient: Coefficient.meters)
}
}
public class var decimeters: UnitLength {
get {
return UnitLength(symbol: Symbol.decimeters, coefficient: Coefficient.decimeters)
}
}
public class var centimeters: UnitLength {
get {
return UnitLength(symbol: Symbol.centimeters, coefficient: Coefficient.centimeters)
}
}
public class var millimeters: UnitLength {
get {
return UnitLength(symbol: Symbol.millimeters, coefficient: Coefficient.millimeters)
}
}
public class var micrometers: UnitLength {
get {
return UnitLength(symbol: Symbol.micrometers, coefficient: Coefficient.micrometers)
}
}
public class var nanometers: UnitLength {
get {
return UnitLength(symbol: Symbol.nanometers, coefficient: Coefficient.nanometers)
}
}
public class var picometers: UnitLength {
get {
return UnitLength(symbol: Symbol.picometers, coefficient: Coefficient.picometers)
}
}
public class var inches: UnitLength {
get {
return UnitLength(symbol: Symbol.inches, coefficient: Coefficient.inches)
}
}
public class var feet: UnitLength {
get {
return UnitLength(symbol: Symbol.feet, coefficient: Coefficient.feet)
}
}
public class var yards: UnitLength {
get {
return UnitLength(symbol: Symbol.yards, coefficient: Coefficient.yards)
}
}
public class var miles: UnitLength {
get {
return UnitLength(symbol: Symbol.miles, coefficient: Coefficient.miles)
}
}
public class var scandinavianMiles: UnitLength {
get {
return UnitLength(symbol: Symbol.scandinavianMiles, coefficient: Coefficient.scandinavianMiles)
}
}
public class var lightyears: UnitLength {
get {
return UnitLength(symbol: Symbol.lightyears, coefficient: Coefficient.lightyears)
}
}
public class var nauticalMiles: UnitLength {
get {
return UnitLength(symbol: Symbol.nauticalMiles, coefficient: Coefficient.nauticalMiles)
}
}
public class var fathoms: UnitLength {
get {
return UnitLength(symbol: Symbol.fathoms, coefficient: Coefficient.fathoms)
}
}
public class var furlongs: UnitLength {
get {
return UnitLength(symbol: Symbol.furlongs, coefficient: Coefficient.furlongs)
}
}
public class var astronomicalUnits: UnitLength {
get {
return UnitLength(symbol: Symbol.astronomicalUnits, coefficient: Coefficient.astronomicalUnits)
}
}
public class var parsecs: UnitLength {
get {
return UnitLength(symbol: Symbol.parsecs, coefficient: Coefficient.parsecs)
}
}
public override class func baseUnit() -> UnitLength {
return .meters
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitLength else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitIlluminance : Dimension {
/*
Base unit - lux
*/
private struct Symbol {
static let lux = "lx"
}
private struct Coefficient {
static let lux = 1.0
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var lux: UnitIlluminance {
get {
return UnitIlluminance(symbol: Symbol.lux, coefficient: Coefficient.lux)
}
}
public override class func baseUnit() -> UnitIlluminance {
return .lux
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitIlluminance else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitMass : Dimension {
/*
Base unit - kilograms
*/
private struct Symbol {
static let kilograms = "kg"
static let grams = "g"
static let decigrams = "dg"
static let centigrams = "cg"
static let milligrams = "mg"
static let micrograms = "µg"
static let nanograms = "ng"
static let picograms = "pg"
static let ounces = "oz"
static let pounds = "lb"
static let stones = "st"
static let metricTons = "t"
static let shortTons = "ton"
static let carats = "ct"
static let ouncesTroy = "oz t"
static let slugs = "slug"
}
private struct Coefficient {
static let kilograms = 1.0
static let grams = 1e-3
static let decigrams = 1e-4
static let centigrams = 1e-5
static let milligrams = 1e-6
static let micrograms = 1e-9
static let nanograms = 1e-12
static let picograms = 1e-15
static let ounces = 0.0283495
static let pounds = 0.453592
static let stones = 0.157473
static let metricTons = 1000.0
static let shortTons = 907.185
static let carats = 0.0002
static let ouncesTroy = 0.03110348
static let slugs = 14.5939
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var kilograms: UnitMass {
get {
return UnitMass(symbol: Symbol.kilograms, coefficient: Coefficient.kilograms)
}
}
public class var grams: UnitMass {
get {
return UnitMass(symbol: Symbol.grams, coefficient: Coefficient.grams)
}
}
public class var decigrams: UnitMass {
get {
return UnitMass(symbol: Symbol.decigrams, coefficient: Coefficient.decigrams)
}
}
public class var centigrams: UnitMass {
get {
return UnitMass(symbol: Symbol.centigrams, coefficient: Coefficient.centigrams)
}
}
public class var milligrams: UnitMass {
get {
return UnitMass(symbol: Symbol.milligrams, coefficient: Coefficient.milligrams)
}
}
public class var micrograms: UnitMass {
get {
return UnitMass(symbol: Symbol.micrograms, coefficient: Coefficient.micrograms)
}
}
public class var nanograms: UnitMass {
get {
return UnitMass(symbol: Symbol.nanograms, coefficient: Coefficient.nanograms)
}
}
public class var picograms: UnitMass {
get {
return UnitMass(symbol: Symbol.picograms, coefficient: Coefficient.picograms)
}
}
public class var ounces: UnitMass {
get {
return UnitMass(symbol: Symbol.ounces, coefficient: Coefficient.ounces)
}
}
public class var pounds: UnitMass {
get {
return UnitMass(symbol: Symbol.pounds, coefficient: Coefficient.pounds)
}
}
public class var stones: UnitMass {
get {
return UnitMass(symbol: Symbol.stones, coefficient: Coefficient.stones)
}
}
public class var metricTons: UnitMass {
get {
return UnitMass(symbol: Symbol.metricTons, coefficient: Coefficient.metricTons)
}
}
public class var shortTons: UnitMass {
get {
return UnitMass(symbol: Symbol.shortTons, coefficient: Coefficient.shortTons)
}
}
public class var carats: UnitMass {
get {
return UnitMass(symbol: Symbol.carats, coefficient: Coefficient.carats)
}
}
public class var ouncesTroy: UnitMass {
get {
return UnitMass(symbol: Symbol.ouncesTroy, coefficient: Coefficient.ouncesTroy)
}
}
public class var slugs: UnitMass {
get {
return UnitMass(symbol: Symbol.slugs, coefficient: Coefficient.slugs)
}
}
public override class func baseUnit() -> UnitMass {
return .kilograms
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitMass else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitPower : Dimension {
/*
Base unit - watts
*/
private struct Symbol {
static let terawatts = "TW"
static let gigawatts = "GW"
static let megawatts = "MW"
static let kilowatts = "kW"
static let watts = "W"
static let milliwatts = "mW"
static let microwatts = "µW"
static let nanowatts = "nW"
static let picowatts = "pW"
static let femtowatts = "fW"
static let horsepower = "hp"
}
private struct Coefficient {
static let terawatts = 1e12
static let gigawatts = 1e9
static let megawatts = 1e6
static let kilowatts = 1e3
static let watts = 1.0
static let milliwatts = 1e-3
static let microwatts = 1e-6
static let nanowatts = 1e-9
static let picowatts = 1e-12
static let femtowatts = 1e-15
static let horsepower = 745.7
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var terawatts: UnitPower {
get {
return UnitPower(symbol: Symbol.terawatts, coefficient: Coefficient.terawatts)
}
}
public class var gigawatts: UnitPower {
get {
return UnitPower(symbol: Symbol.gigawatts, coefficient: Coefficient.gigawatts)
}
}
public class var megawatts: UnitPower {
get {
return UnitPower(symbol: Symbol.megawatts, coefficient: Coefficient.megawatts)
}
}
public class var kilowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.kilowatts, coefficient: Coefficient.kilowatts)
}
}
public class var watts: UnitPower {
get {
return UnitPower(symbol: Symbol.watts, coefficient: Coefficient.watts)
}
}
public class var milliwatts: UnitPower {
get {
return UnitPower(symbol: Symbol.milliwatts, coefficient: Coefficient.milliwatts)
}
}
public class var microwatts: UnitPower {
get {
return UnitPower(symbol: Symbol.microwatts, coefficient: Coefficient.microwatts)
}
}
public class var nanowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.nanowatts, coefficient: Coefficient.nanowatts)
}
}
public class var picowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.picowatts, coefficient: Coefficient.picowatts)
}
}
public class var femtowatts: UnitPower {
get {
return UnitPower(symbol: Symbol.femtowatts, coefficient: Coefficient.femtowatts)
}
}
public class var horsepower: UnitPower {
get {
return UnitPower(symbol: Symbol.horsepower, coefficient: Coefficient.horsepower)
}
}
public override class func baseUnit() -> UnitPower {
return .watts
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitPower else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitPressure : Dimension {
/*
Base unit - newtonsPerMetersSquared (equivalent to 1 pascal)
*/
private struct Symbol {
static let newtonsPerMetersSquared = "N/m²"
static let gigapascals = "GPa"
static let megapascals = "MPa"
static let kilopascals = "kPa"
static let hectopascals = "hPa"
static let inchesOfMercury = "inHg"
static let bars = "bar"
static let millibars = "mbar"
static let millimetersOfMercury = "mmHg"
static let poundsForcePerSquareInch = "psi"
}
private struct Coefficient {
static let newtonsPerMetersSquared = 1.0
static let gigapascals = 1e9
static let megapascals = 1e6
static let kilopascals = 1e3
static let hectopascals = 1e2
static let inchesOfMercury = 3386.39
static let bars = 1e5
static let millibars = 1e2
static let millimetersOfMercury = 133.322
static let poundsForcePerSquareInch = 6894.76
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var newtonsPerMetersSquared: UnitPressure {
get {
return UnitPressure(symbol: Symbol.newtonsPerMetersSquared, coefficient: Coefficient.newtonsPerMetersSquared)
}
}
public class var gigapascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.gigapascals, coefficient: Coefficient.gigapascals)
}
}
public class var megapascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.megapascals, coefficient: Coefficient.megapascals)
}
}
public class var kilopascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.kilopascals, coefficient: Coefficient.kilopascals)
}
}
public class var hectopascals: UnitPressure {
get {
return UnitPressure(symbol: Symbol.hectopascals, coefficient: Coefficient.hectopascals)
}
}
public class var inchesOfMercury: UnitPressure {
get {
return UnitPressure(symbol: Symbol.inchesOfMercury, coefficient: Coefficient.inchesOfMercury)
}
}
public class var bars: UnitPressure {
get {
return UnitPressure(symbol: Symbol.bars, coefficient: Coefficient.bars)
}
}
public class var millibars: UnitPressure {
get {
return UnitPressure(symbol: Symbol.millibars, coefficient: Coefficient.millibars)
}
}
public class var millimetersOfMercury: UnitPressure {
get {
return UnitPressure(symbol: Symbol.millimetersOfMercury, coefficient: Coefficient.millimetersOfMercury)
}
}
public class var poundsForcePerSquareInch: UnitPressure {
get {
return UnitPressure(symbol: Symbol.poundsForcePerSquareInch, coefficient: Coefficient.poundsForcePerSquareInch)
}
}
public override class func baseUnit() -> UnitPressure {
return .newtonsPerMetersSquared
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitPressure else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitSpeed : Dimension {
/*
Base unit - metersPerSecond
*/
private struct Symbol {
static let metersPerSecond = "m/s"
static let kilometersPerHour = "km/h"
static let milesPerHour = "mph"
static let knots = "kn"
}
private struct Coefficient {
static let metersPerSecond = 1.0
static let kilometersPerHour = 0.277778
static let milesPerHour = 0.44704
static let knots = 0.514444
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var metersPerSecond: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.metersPerSecond, coefficient: Coefficient.metersPerSecond)
}
}
public class var kilometersPerHour: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.kilometersPerHour, coefficient: Coefficient.kilometersPerHour)
}
}
public class var milesPerHour: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.milesPerHour, coefficient: Coefficient.milesPerHour)
}
}
public class var knots: UnitSpeed {
get {
return UnitSpeed(symbol: Symbol.knots, coefficient: Coefficient.knots)
}
}
public override class func baseUnit() -> UnitSpeed {
return .metersPerSecond
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitSpeed else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitTemperature : Dimension {
/*
Base unit - kelvin
*/
private struct Symbol {
static let kelvin = "K"
static let celsius = "°C"
static let fahrenheit = "°F"
}
private struct Coefficient {
static let kelvin = 1.0
static let celsius = 1.0
static let fahrenheit = 0.55555555555556
}
private struct Constant {
static let kelvin = 0.0
static let celsius = 273.15
static let fahrenheit = 255.37222222222427
}
private convenience init(symbol: String, coefficient: Double, constant: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant))
}
public class var kelvin: UnitTemperature {
get {
return UnitTemperature(symbol: Symbol.kelvin, coefficient: Coefficient.kelvin, constant: Constant.kelvin)
}
}
public class var celsius: UnitTemperature {
get {
return UnitTemperature(symbol: Symbol.celsius, coefficient: Coefficient.celsius, constant: Constant.celsius)
}
}
public class var fahrenheit: UnitTemperature {
get {
return UnitTemperature(symbol: Symbol.fahrenheit, coefficient: Coefficient.fahrenheit, constant: Constant.fahrenheit)
}
}
public override class func baseUnit() -> UnitTemperature {
return .kelvin
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitTemperature else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
public final class UnitVolume : Dimension {
/*
Base unit - liters
*/
private struct Symbol {
static let megaliters = "ML"
static let kiloliters = "kL"
static let liters = "L"
static let deciliters = "dl"
static let centiliters = "cL"
static let milliliters = "mL"
static let cubicKilometers = "km³"
static let cubicMeters = "m³"
static let cubicDecimeters = "dm³"
static let cubicCentimeters = "cm³"
static let cubicMillimeters = "mm³"
static let cubicInches = "in³"
static let cubicFeet = "ft³"
static let cubicYards = "yd³"
static let cubicMiles = "mi³"
static let acreFeet = "af"
static let bushels = "bsh"
static let teaspoons = "tsp"
static let tablespoons = "tbsp"
static let fluidOunces = "fl oz"
static let cups = "cup"
static let pints = "pt"
static let quarts = "qt"
static let gallons = "gal"
static let imperialTeaspoons = "tsp Imperial"
static let imperialTablespoons = "tbsp Imperial"
static let imperialFluidOunces = "fl oz Imperial"
static let imperialPints = "pt Imperial"
static let imperialQuarts = "qt Imperial"
static let imperialGallons = "gal Imperial"
static let metricCups = "metric cup Imperial"
}
private struct Coefficient {
static let megaliters = 1e6
static let kiloliters = 1e3
static let liters = 1.0
static let deciliters = 1e-1
static let centiliters = 1e-2
static let milliliters = 1e-3
static let cubicKilometers = 1e12
static let cubicMeters = 1000.0
static let cubicDecimeters = 1.0
static let cubicCentimeters = 0.01
static let cubicMillimeters = 0.001
static let cubicInches = 0.0163871
static let cubicFeet = 28.3168
static let cubicYards = 764.555
static let cubicMiles = 4.168e+12
static let acreFeet = 1.233e+6
static let bushels = 35.2391
static let teaspoons = 0.00492892
static let tablespoons = 0.0147868
static let fluidOunces = 0.0295735
static let cups = 0.24
static let pints = 0.473176
static let quarts = 0.946353
static let gallons = 3.78541
static let imperialTeaspoons = 0.00591939
static let imperialTablespoons = 0.0177582
static let imperialFluidOunces = 0.0284131
static let imperialPints = 0.568261
static let imperialQuarts = 1.13652
static let imperialGallons = 4.54609
static let metricCups = 0.25
}
private convenience init(symbol: String, coefficient: Double) {
self.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient))
}
public class var megaliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.megaliters, coefficient: Coefficient.megaliters)
}
}
public class var kiloliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.kiloliters, coefficient: Coefficient.kiloliters)
}
}
public class var liters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.liters, coefficient: Coefficient.liters)
}
}
public class var deciliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.deciliters, coefficient: Coefficient.deciliters)
}
}
public class var centiliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.centiliters, coefficient: Coefficient.centiliters)
}
}
public class var milliliters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.milliliters, coefficient: Coefficient.milliliters)
}
}
public class var cubicKilometers: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicKilometers, coefficient: Coefficient.cubicKilometers)
}
}
public class var cubicMeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicMeters, coefficient: Coefficient.cubicMeters)
}
}
public class var cubicDecimeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicDecimeters, coefficient: Coefficient.cubicDecimeters)
}
}
public class var cubicCentimeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicCentimeters, coefficient: Coefficient.cubicCentimeters)
}
}
public class var cubicMillimeters: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicMillimeters, coefficient: Coefficient.cubicMillimeters)
}
}
public class var cubicInches: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicInches, coefficient: Coefficient.cubicInches)
}
}
public class var cubicFeet: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicFeet, coefficient: Coefficient.cubicFeet)
}
}
public class var cubicYards: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicYards, coefficient: Coefficient.cubicYards)
}
}
public class var cubicMiles: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cubicMiles, coefficient: Coefficient.cubicMiles)
}
}
public class var acreFeet: UnitVolume {
get {
return UnitVolume(symbol: Symbol.acreFeet, coefficient: Coefficient.acreFeet)
}
}
public class var bushels: UnitVolume {
get {
return UnitVolume(symbol: Symbol.bushels, coefficient: Coefficient.bushels)
}
}
public class var teaspoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.teaspoons, coefficient: Coefficient.teaspoons)
}
}
public class var tablespoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.tablespoons, coefficient: Coefficient.tablespoons)
}
}
public class var fluidOunces: UnitVolume {
get {
return UnitVolume(symbol: Symbol.fluidOunces, coefficient: Coefficient.fluidOunces)
}
}
public class var cups: UnitVolume {
get {
return UnitVolume(symbol: Symbol.cups, coefficient: Coefficient.cups)
}
}
public class var pints: UnitVolume {
get {
return UnitVolume(symbol: Symbol.pints, coefficient: Coefficient.pints)
}
}
public class var quarts: UnitVolume {
get {
return UnitVolume(symbol: Symbol.quarts, coefficient: Coefficient.quarts)
}
}
public class var gallons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.gallons, coefficient: Coefficient.gallons)
}
}
public class var imperialTeaspoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialTeaspoons, coefficient: Coefficient.imperialTeaspoons)
}
}
public class var imperialTablespoons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialTablespoons, coefficient: Coefficient.imperialTablespoons)
}
}
public class var imperialFluidOunces: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialFluidOunces, coefficient: Coefficient.imperialFluidOunces)
}
}
public class var imperialPints: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialPints, coefficient: Coefficient.imperialPints)
}
}
public class var imperialQuarts: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialQuarts, coefficient: Coefficient.imperialQuarts)
}
}
public class var imperialGallons: UnitVolume {
get {
return UnitVolume(symbol: Symbol.imperialGallons, coefficient: Coefficient.imperialGallons)
}
}
public class var metricCups: UnitVolume {
get {
return UnitVolume(symbol: Symbol.metricCups, coefficient: Coefficient.metricCups)
}
}
public override class func baseUnit() -> UnitVolume {
return .liters
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? UnitVolume else {
return false
}
if self === other {
return true
}
return super.isEqual(object)
}
}
|
apache-2.0
|
32c5660c07c3a09d8981c4de33c12cf8
| 29.367094 | 520 | 0.590999 | 4.64641 | false | false | false | false |
khizkhiz/swift
|
test/DebugInfo/inlinescopes.swift
|
2
|
1322
|
// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo "public var x = Int64()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll
// RUN: FileCheck %s < %t.ll
// RUN: FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll
// CHECK: define{{( protected)?( signext)?}} i32 @main
// CHECK: tail call { i64, i1 } @llvm.smul.with.overflow.i64(i64 %[[C:.*]], i64 %[[C]]), !dbg ![[MULSCOPE:.*]]
// CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "inlinescopes.swift"
import FooBar
func markUsed<T>(t: T) {}
@inline(__always)
func square(x: Int64) -> Int64 {
// CHECK-DAG: ![[MULSCOPE]] = !DILocation(line: [[@LINE+2]], column: {{.*}}, scope: ![[MUL:.*]], inlinedAt: ![[INLINED:.*]])
// CHECK-DAG: ![[MUL:.*]] = distinct !DILexicalBlock(
let res = x * x
// *(Int, Int) is a transparent function and should not show up in the debug info.
// TRANSPARENT-CHECK-NOT: !DISubprogram(name: "_TFsoi1mFTSiSi_Si"
return res
}
let c = Int64(x)
// CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]]
let y = square(c)
markUsed(y)
// Check if the inlined and removed square function still has the correct linkage name in the debug info.
// CHECK-DAG: !DISubprogram(name: "square", linkageName: "_TF4main6squareFVs5Int64S0_"
|
apache-2.0
|
ed8b1be8e66b6d503e1a10e50b89a7cc
| 41.645161 | 124 | 0.633888 | 3.004545 | false | false | false | false |
tanweirush/TodayHistory
|
TodayHistory/ctrl/THDictionaryDetailVC.swift
|
1
|
1734
|
//
// THDictionaryDetailVC.swift
// TodayHistory
//
// Created by 谭伟 on 15/11/17.
// Copyright © 2015年 谭伟. All rights reserved.
//
import UIKit
class THDictionaryDetailVC: UIViewController, NetWorkManagerDelegate {
@IBOutlet weak var tv_text: UITextView!
@IBOutlet weak var aiv_loadding: UIActivityIndicatorView!
var forSearchWord:NSString!
// private lazy var net:NetWorkManager = {
// let n:NetWorkManager = NetWorkManager()
// n.delegate = self
// return n
// }()
private var net:NetWorkManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
let n:NetWorkManager = NetWorkManager()
n.delegate = self
n.getDictionaryWithWords(Words: self.forSearchWord)
self.net = n
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
func dictionaryRequestData(word: NSDictionary, sender: NetWorkManager) {
self.aiv_loadding.stopAnimating()
}
/*
// 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
|
0c3c8950bf42ba6ed93c60390df76a98
| 27.245902 | 106 | 0.663958 | 4.669377 | false | false | false | false |
hejeffery/Animation
|
Animation/Animation/LayerAnimation/View/VolumeView.swift
|
1
|
2783
|
//
// VolumeView.swift
// Animation
//
// Created by HeJeffery on 2017/10/3.
// Copyright © 2017年 JefferyHe. All rights reserved.
//
import UIKit
class VolumeView: UIView {
fileprivate let viewH: CGFloat = 60
fileprivate let viewW: CGFloat = 116
private lazy var rectLayer: CALayer = {
let rectLayer = CALayer()
rectLayer.frame = CGRect(x: 0, y: 0, width: 20, height: viewH)
// 调整anchor point
rectLayer.anchorPoint = CGPoint(x: 0.5, y: 1)
// 校正position
rectLayer.position = CGPoint(x: 10, y: viewH)
rectLayer.backgroundColor = UIColor.red.cgColor
return rectLayer
}()
private lazy var replicatorLayer: CAReplicatorLayer = {
let replicatorLayer = CAReplicatorLayer()
replicatorLayer.frame = self.bounds
replicatorLayer.instanceCount = 5
replicatorLayer.instanceDelay = 0.2
// 为毛这里是24?每个小矩形的宽的20,总共是5个小矩形,每个小矩形间隔4,总的宽度是116。这里的24是相对于原始层的x轴的偏移量
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(24, 0, 0)
replicatorLayer.addSublayer(self.rectLayer)
self.rectLayer.add(animationGroup, forKey: nil)
return replicatorLayer
}()
private lazy var animationGroup: CAAnimationGroup = {
let animationGroup = CAAnimationGroup()
animationGroup.duration = 0.5
animationGroup.autoreverses = true
animationGroup.repeatCount = Float.infinity
animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animationGroup.fillMode = kCAFillModeBackwards
animationGroup.isRemovedOnCompletion = false
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.y")
scaleAnimation.fromValue = 1.0
scaleAnimation.toValue = 0.2
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 0.1
alphaAnimation.toValue = 1.0
animationGroup.animations = [scaleAnimation, alphaAnimation]
return animationGroup
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override var frame: CGRect {
set {
var newFrame = newValue
newFrame.size.width = viewW
newFrame.size.height = viewH
super.frame = newFrame
}
get {
return super.frame
}
}
func setup() {
layer.addSublayer(replicatorLayer)
}
}
|
mit
|
949c4b5ed4243e99722afe8418f19129
| 29.295455 | 104 | 0.633533 | 4.820976 | false | false | false | false |
dcunited001/SpectraNu
|
Spectra/SpectraXML/Nodes.swift
|
1
|
43086
|
//
// Nodes.swift
//
//
// Created by David Conner on 3/9/16.
//
//
import Foundation
import simd
import Fuzi
import Swinject
import ModelIO
public enum SpectraNodeType: String {
case World = "world" // TODO: design node & object
case Transform = "transform"
case Asset = "asset"
case BufferAllocator = "buffer-allocator"
case BufferAllocatorGenerator = "buffer-allocator-generator"
case Object = "object"
case Mesh = "mesh"
case MeshGenerator = "mesh-generator"
case Submesh = "submesh"
case SubmeshGenerator = "submesh-generator"
// wtf submesh? not really sure how to add "attributes" to mesh using submeshes
case Camera = "camera"
case CameraGenerator = "camera-generator"
case PhysicalLens = "physical-lens"
case PhysicalImagingSurface = "physical-imaging-surface"
case StereoscopicCamera = "stereoscopic-camera"
case VertexAttribute = "vertex-attribute"
case VertexDescriptor = "vertex-descriptor"
case Material = "material"
case MaterialProperty = "material-property"
case ScatteringFunction = "scattering-function"
case Texture = "texture"
case TextureGenerator = "texture-generator"
case TextureFilter = "texture-filter"
case TextureSampler = "texture-sampler"
case Light = "light"
case LightGenerator = "light-generator"
}
public struct GeneratorArg {
public var name: String
public var type: String
public var value: String
// TODO: how to specify lists of arguments with generator arg
public init(name: String, type: String, value: String) {
self.name = name
self.type = type
self.value = value
}
public init(elem: XMLElement) {
self.name = elem.attributes["name"]!
self.type = elem.attributes["type"]!
self.value = elem.attributes["value"]!
}
public enum GeneratorArgType: String {
// TODO: decide on whether this is really necessary to enumerate types (it's not .. really)
// - node this can really be translated in the mesh generator
case String = "String"
case Float = "Float"
case Float2 = "Float2"
case Float3 = "Float3"
case Float4 = "Float4"
case Int = "Int"
case Int2 = "Int2"
case Int3 = "Int3"
case Int4 = "Int4"
case Mesh = "Mesh"
}
public static func parseGenArgs(elem: XMLElement, selector: String) -> [String: GeneratorArg] {
return elem.css(selector).reduce([:]) { (var args, el) in
let name = el.attributes["name"]!
args[name] = GeneratorArg(elem: el)
return args
}
}
// TODO: delete? do i really need type checking for generator args?
// public func parseValue<T>() -> T? {
// TODO: populate type enum
// switch self.type {
// case .Float: return Float(value) as! T
// case .Float2: return SpectraSimd.parseFloat2(value) as! T
// case .Float3: return SpectraSimd.parseFloat3(value) as! T
// case .Float4: return SpectraSimd.parseFloat4(value) as! T
// }
// TODO: how to switch based on type
// switch T.self {
// case Float.self: return Float(value) as! T
// case is float2: return (value) as! T
// default: return nil
// }
// }
}
public class AssetNode: SpectraParserNode { // TODO: implement SpectraParserNode protocol
public typealias NodeType = AssetNode
public typealias MDLType = MDLAsset
public var id: String?
public var urlString: String?
public var resource: String?
public var vertexDescriptor: VertexDescriptorNode?
public var bufferAllocator: String = "default"
// TODO: error handling for preserveTopology
// - (when true the constructor throws. for now, my protocol can't handle this)
public var preserveTopology: Bool = false
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let urlString = elem.attributes["url"] { self.urlString = urlString }
if let resource = elem.attributes["resource"] { self.resource = resource }
if let bufferAllocId = elem.attributes["buffer-allocator"] { self.bufferAllocator = bufferAllocId }
if let vertexDescId = elem.attributes["vertex-descriptor"] {
self.vertexDescriptor = nodes.resolve(VertexDescriptorNode.self, name: vertexDescId)
} // TODO: else if contains a vertexDescriptor node
// TODO: else set to default vertexDescriptor?
if let preserveTopology = elem.attributes["preserve-topology"] {
let valAsBool = NSString(string: preserveTopology).boolValue
self.preserveTopology = valAsBool
}
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let url = NSURL(string: self.urlString!)
let models = containers["model"]
let resources = containers["resources"]
let vertexDescriptor = self.vertexDescriptor?.generate(containers, options: options)
let bufferAllocator = resources?.resolve(MDLMeshBufferAllocator.self, name: self.bufferAllocator)
let asset = MDLAsset(URL: url!, vertexDescriptor: vertexDescriptor, bufferAllocator: bufferAllocator)
// TODO: change to call with preserveTopology (it throws though)
return asset
}
public func copy() -> NodeType {
let cp = AssetNode()
cp.id = self.id
cp.urlString = self.urlString
cp.resource = self.resource
cp.vertexDescriptor = self.vertexDescriptor
cp.bufferAllocator = self.bufferAllocator
return cp
}
}
public class VertexAttributeNode: SpectraParserNode {
public typealias MDLType = MDLVertexAttribute
public typealias NodeType = VertexAttributeNode
public var id: String?
public var name: String?
public var format: MDLVertexFormat?
public var offset: Int = 0
public var bufferIndex: Int = 0
public var initializationValue: float4 = float4()
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let name = elem.attributes["name"] { self.name = name }
if let offset = elem.attributes["offset"] { self.offset = Int(offset)! }
if let bufferIndex = elem.attributes["buffer-index"] { self.bufferIndex = Int(bufferIndex)! }
if let format = elem.attributes["format"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlVertexFormat")!.getValue(format)
self.format = MDLVertexFormat(rawValue: enumVal)!
}
if let initializationValue = elem.attributes["initialization-value"] {
self.initializationValue = SpectraSimd.parseFloat4(initializationValue)
}
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let attr = MDLVertexAttribute()
attr.name = self.name!
attr.format = self.format!
attr.offset = self.offset
attr.bufferIndex = self.bufferIndex
attr.initializationValue = self.initializationValue
return attr
}
public func copy() -> NodeType {
let cp = VertexAttributeNode()
cp.id = self.id
cp.name = self.name
cp.format = self.format
cp.offset = self.offset
cp.bufferIndex = self.bufferIndex
cp.initializationValue = self.initializationValue
return cp
}
}
public class VertexDescriptorNode: SpectraParserNode {
public typealias NodeType = VertexDescriptorNode
public typealias MDLType = MDLVertexDescriptor
public var id: String?
public var parentDescriptor: VertexDescriptorNode?
public var attributes: [VertexAttributeNode] = []
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let parentDescriptor = elem.attributes["parent-descriptor"] {
let parentDesc = nodes.resolve(VertexDescriptorNode.self, name: parentDescriptor)!
self.parentDescriptor = parentDesc
}
let attributeSelector = "vertex-attributes > vertex-attribute"
for (idx, el) in elem.css(attributeSelector).enumerate() {
if let ref = el.attributes["ref"] {
let vertexAttr = nodes.resolve(VertexAttributeNode.self, name: ref)!
attributes.append(vertexAttr)
} else {
let vertexAttr = VertexAttributeNode()
vertexAttr.parseXML(nodes, elem: el)
attributes.append(vertexAttr)
}
}
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
var desc = parentDescriptor?.generate(containers, options: options) ?? MDLVertexDescriptor()
for attr in self.attributes {
let vertexAttr = attr.generate(containers, options: options)
desc.addOrReplaceAttribute(vertexAttr)
}
// this automatically sets the offset correctly,
// - but attributes must be assigned and configured by this point
desc.setPackedOffsets()
desc.setPackedStrides()
return desc
}
public func copy() -> VertexDescriptorNode {
let cp = VertexDescriptorNode()
cp.id = self.id
cp.attributes = self.attributes
cp.parentDescriptor = self.parentDescriptor
return cp
}
}
public class TransformNode: SpectraParserNode {
public typealias NodeType = TransformNode
public typealias MDLType = MDLTransform
public var id: String?
public var scale: float3 = float3(1.0, 1.0, 1.0)
public var rotation: float3 = float3(0.0, 0.0, 0.0)
public var translation: float3 = float3(0.0, 0.0, 0.0)
public var shear: float3 = float3(0.0, 0.0, 0.0)
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
// N.B. scale first, then rotate, finally translate
// - but how can a shear operation be composed into this?
if let id = elem.attributes["id"] { self.id = id }
if let scale = elem.attributes["scale"] { self.scale = SpectraSimd.parseFloat3(scale) }
if let shear = elem.attributes["shear"] { self.shear = SpectraSimd.parseFloat3(shear) }
if let translation = elem.attributes["translation"] { self.translation = SpectraSimd.parseFloat3(translation) }
if let rotation = elem.attributes["rotation"] {
self.rotation = SpectraSimd.parseFloat3(rotation)
} else if let rotationDeg = elem.attributes["rotation-deg"] {
let rotationDegrees = SpectraSimd.parseFloat3(rotationDeg)
self.rotation = Float(M_PI / 180.0) * rotationDegrees
}
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let transform = MDLTransform()
transform.scale = self.scale
transform.shear = self.shear
transform.rotation = self.rotation
transform.translation = self.translation
return transform
}
public func copy() -> TransformNode {
let cp = TransformNode()
cp.id = self.id
cp.scale = self.scale
cp.shear = self.shear
cp.rotation = self.rotation
cp.translation = self.translation
return cp
}
}
// TODO: BufferAllocator = "buffer-allocator"
// TODO: BufferAllocatorGenerator = "buffer-allocator-generator"
public class ObjectNode { // SpectraParserNode
// stub
}
public class MeshNode: SpectraParserNode {
public typealias NodeType = MeshNode
public typealias MDLType = MDLMesh
public var id: String?
public var generator: String = "ellipsoid_mesh_gen"
public var args: [String: GeneratorArg] = [:]
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(container: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let generator = elem.attributes["generator"] { self.generator = generator }
let genArgsSelector = "generator-args > generator-arg"
self.args = GeneratorArg.parseGenArgs(elem, selector: genArgsSelector)
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let models = containers["models"]!
let meshGen = models.resolve(MeshGenerator.self, name: self.generator)!
let mesh = meshGen.generate(models, args: self.args)
// TODO: register mesh?
return mesh
}
public func copy() -> NodeType {
let cp = MeshNode()
cp.id = self.id
cp.generator = self.generator
cp.args = self.args
return cp
}
}
public class MeshGeneratorNode: SpectraParserNode {
public typealias NodeType = MeshGeneratorNode
public typealias MDLType = MeshGenerator
public var id: String?
public var type: String = "tetrahedron_mesh_gen"
public var args: [String: GeneratorArg] = [:]
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(container: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let type = elem.attributes["type"] { self.type = type }
let genArgsSelector = "generator-args > generator-arg"
self.args = GeneratorArg.parseGenArgs(elem, selector: genArgsSelector)
}
// public func createGenerator(container: Container, options: [String : Any] = [:]) -> MeshGenerator {
// let meshGen = container.resolve(MeshGenerator.self, name: self.type)!
// meshGen.processArgs(container, args: self.args)
// return meshGen
// }
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
// TODO: add to a generators container instead?
let models = containers["models"]!
let meshGen = models.resolve(MeshGenerator.self, name: self.type)!
meshGen.processArgs(models, args: self.args)
return meshGen
}
public func copy() -> NodeType {
let cp = MeshGeneratorNode()
cp.id = self.id
cp.type = self.type
cp.args = self.args
return cp
}
}
public class SubmeshNode: SpectraParserNode {
public typealias NodeType = SubmeshNode
public typealias MDLType = MDLSubmesh
public var id: String?
public var generator: String = "tetrahedron_mesh_gen"
public var args: [String: GeneratorArg] = [:]
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let generator = elem.attributes["generator"] { self.generator = generator }
let genArgsSelector = "generator-args > generator-arg"
self.args = GeneratorArg.parseGenArgs(elem, selector: genArgsSelector)
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let models = containers["models"]!
let submeshGen = models.resolve(SubmeshGenerator.self, name: self.generator)!
let submesh = submeshGen.generate(models, args: self.args)
// TODO: register submesh?
return submesh
}
// // TODO: add to a generators container instead?
// let models = containers["models"]!
// let submeshGen = models.resolve(SubmeshGenerator.self, name: self.type)!
// submeshGen.processArgs(models, args: self.args)
// return submeshGen
public func copy() -> NodeType {
let cp = SubmeshNode()
cp.id = self.id
cp.generator = self.generator
cp.args = self.args
return cp
}
}
public class SubmeshGeneratorNode: SpectraParserNode {
public typealias NodeType = SubmeshGeneratorNode
public typealias MDLType = SubmeshGenerator
public var id: String?
public var type: String = "random_balanced_graph_submesh_gen"
public var args: [String: GeneratorArg] = [:]
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(container: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let type = elem.attributes["type"] { self.type = type }
let genArgsSelector = "generator-args > generator-arg"
self.args = GeneratorArg.parseGenArgs(elem, selector: genArgsSelector)
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
// TODO: add to a generators container instead?
let models = containers["models"]!
let meshGen = models.resolve(SubmeshGenerator.self, name: self.type)!
meshGen.processArgs(models, args: self.args)
// TODO: register submeshGen?
return meshGen
}
public func copy() -> NodeType {
let cp = SubmeshGeneratorNode()
cp.id = self.id
cp.type = self.type
cp.args = self.args
return cp
}
}
// TODO: submeshes: not really sure how to add "attributes" to mesh using submeshes
public class PhysicalLensNode: SpectraParserNode {
public typealias MDLType = PhysicalLensNode
public typealias NodeType = PhysicalLensNode
// for any of this to do anything, renderer must support the math (visual distortion, etc)
public var id: String?
public var worldToMetersConversionScale: Float?
public var barrelDistortion: Float?
public var fisheyeDistortion: Float?
public var opticalVignetting: Float?
public var chromaticAberration: Float?
public var focalLength: Float?
public var fStop: Float?
public var apertureBladeCount: Int?
public var maximumCircleOfConfusion: Float?
public var focusDistance: Float?
// defaults
public static let worldToMetersConversionScale: Float = 1.0
public static let barrelDistortion: Float = 0
public static let fisheyeDistortion: Float = 0
public static let opticalVignetting: Float = 0
public static let chromaticAberration: Float = 0
public static let focalLength: Float = 50
public static let fStop: Float = 5.6
public static let apertureBladeCount: Int = 0
public static let maximumCircleOfConfusion: Float = 0.05
public static let focusDistance: Float = 2.5
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
// doc's don't list default shutterOpenInterval value,
// - but (1/60) * 0.50 = 1/120 for 60fps and 50% shutter
public var shutterOpenInterval: NSTimeInterval = (0.5 * (1.0/60.0))
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let val = elem.attributes["world-to-meters-conversion-scale"] { self.worldToMetersConversionScale = Float(val)! }
if let val = elem.attributes["barrel-distortion"] { self.barrelDistortion = Float(val)! }
if let val = elem.attributes["fisheye-distortion"] { self.fisheyeDistortion = Float(val)! }
if let val = elem.attributes["optical-vignetting"] { self.opticalVignetting = Float(val)! }
if let val = elem.attributes["chromatic-aberration"] { self.chromaticAberration = Float(val)! }
if let val = elem.attributes["focal-length"] { self.focalLength = Float(val)! }
if let val = elem.attributes["f-stop"] { self.fStop = Float(val)! }
if let val = elem.attributes["aperture-blade-count"] { self.apertureBladeCount = Int(val)! }
if let val = elem.attributes["maximum-circle-of-confusion"] { self.maximumCircleOfConfusion = Float(val)! }
if let val = elem.attributes["focus-distance"] { self.focusDistance = Float(val)! }
}
public func applyToCamera(camera: MDLCamera) {
if let val = self.worldToMetersConversionScale { camera.worldToMetersConversionScale = val }
if let val = self.barrelDistortion { camera.barrelDistortion = val }
if let val = self.fisheyeDistortion { camera.fisheyeDistortion = val }
if let val = self.opticalVignetting { camera.opticalVignetting = val }
if let val = self.chromaticAberration { camera.chromaticAberration = val }
if let val = self.focalLength { camera.focalLength = val }
if let val = self.fStop { camera.fStop = val }
if let val = self.apertureBladeCount { camera.apertureBladeCount = val }
if let val = self.maximumCircleOfConfusion { camera.maximumCircleOfConfusion = val }
if let val = self.focusDistance { camera.focusDistance = val }
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
return self.copy()
}
public func copy() -> NodeType {
let cp = PhysicalLensNode()
cp.id = self.id
cp.worldToMetersConversionScale = self.worldToMetersConversionScale
cp.barrelDistortion = self.barrelDistortion
cp.fisheyeDistortion = self.fisheyeDistortion
cp.opticalVignetting = self.opticalVignetting
cp.chromaticAberration = self.chromaticAberration
cp.focalLength = self.focalLength
cp.fStop = self.fStop
cp.apertureBladeCount = self.apertureBladeCount
cp.maximumCircleOfConfusion = self.maximumCircleOfConfusion
cp.focusDistance = self.focusDistance
return cp
}
}
public class PhysicalImagingSurfaceNode: SpectraParserNode {
public typealias NodeType = PhysicalImagingSurfaceNode
public typealias MDLType = PhysicalImagingSurfaceNode
// for any of this to do anything, renderer must support the math (visual distortion, etc)
public var id: String?
public var sensorVerticalAperture: Float?
public var sensorAspect: Float?
public var sensorEnlargement: vector_float2?
public var sensorShift: vector_float2?
public var flash: vector_float3?
public var exposure: vector_float3?
public var exposureCompression: vector_float2?
// defaults
public static let sensorVerticalAperture: Float = 24
public static let sensorAspect: Float = 1.5
public static let sensorEnlargement: vector_float2 = float2(1.0, 1.0)
public static let sensorShift: vector_float2 = float2(0.0, 0.0)
public static let flash: vector_float3 = float3(0.0, 0.0, 0.0)
public static let exposure: vector_float3 = float3(1.0, 1.0, 1.0)
public static let exposureCompression: vector_float2 = float2(1.0, 0.0)
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let val = elem.attributes["sensor-vertical-aperture"] { self.sensorVerticalAperture = Float(val) }
if let val = elem.attributes["sensor-aspect"] { self.sensorAspect = Float(val) }
if let val = elem.attributes["sensor-enlargement"] { self.sensorEnlargement = SpectraSimd.parseFloat2(val) }
if let val = elem.attributes["sensor-shift"] { self.sensorShift = SpectraSimd.parseFloat2(val) }
if let val = elem.attributes["flash"] { self.flash = SpectraSimd.parseFloat3(val) }
if let val = elem.attributes["exposure"] { self.exposure = SpectraSimd.parseFloat3(val) }
if let val = elem.attributes["exposure-compression"] { self.exposureCompression = SpectraSimd.parseFloat2(val) }
}
public func applyToCamera(camera: MDLCamera) {
if let val = self.sensorVerticalAperture { camera.sensorVerticalAperture = val }
if let val = self.sensorAspect { camera.sensorAspect = val }
if let val = self.sensorEnlargement {camera.sensorEnlargement = val }
if let val = self.sensorShift {camera.sensorShift = val }
if let val = self.flash {camera.flash = val }
if let val = self.exposure {camera.exposure = val }
if let val = self.exposureCompression {camera.exposureCompression = val }
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
return self.copy()
}
public func copy() -> NodeType {
let cp = PhysicalImagingSurfaceNode()
cp.id = self.id
cp.sensorVerticalAperture = self.sensorVerticalAperture
cp.sensorAspect = self.sensorAspect
cp.sensorEnlargement = self.sensorEnlargement
cp.sensorShift = self.sensorShift
cp.flash = self.flash
cp.exposure = self.exposure
cp.exposureCompression = self.exposureCompression
return cp
}
}
public class CameraNode: SpectraParserNode {
public typealias MDLType = MDLCamera
public typealias NodeType = CameraNode
public var id: String?
public var nearVisibilityDistance: Float = 0.1
public var farVisibilityDistance: Float = 1000.0
public var fieldOfView: Float = Float(53.999996185302734375)
public var lookAt: float3?
public var lookFrom: float3?
public var physicalLens = PhysicalLensNode()
public var physicalImagingSurface = PhysicalImagingSurfaceNode()
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let val = elem.attributes["near-visibility-distance"] { self.nearVisibilityDistance = Float(val)! }
if let val = elem.attributes["far-visibility-distance"] { self.farVisibilityDistance = Float(val)! }
if let val = elem.attributes["field-of-view"] { self.fieldOfView = Float(val)! }
let lensSelector = SpectraNodeType.PhysicalLens.rawValue
if let lensTag = elem.firstChild(tag: lensSelector) {
if let ref = lensTag.attributes["ref"] {
let lens = nodes.resolve(PhysicalLensNode.self, name: ref)!
self.physicalLens = lens
} else {
let lens = PhysicalLensNode()
lens.parseXML(nodes, elem: lensTag)
if let lensId = lensTag["id"] {
nodes.register(PhysicalLensNode.self, name: lensId) { _ in return
lens.copy() as! PhysicalLensNode
}
}
self.physicalLens = lens
}
}
let imagingSelector = SpectraNodeType.PhysicalImagingSurface.rawValue
if let imagingTag = elem.firstChild(tag: imagingSelector) {
if let ref = imagingTag.attributes["ref"] {
let imgSurface = nodes.resolve(PhysicalImagingSurfaceNode.self, name: ref)!
self.physicalImagingSurface = imgSurface
} else {
let imgSurface = PhysicalImagingSurfaceNode()
imgSurface.parseXML(nodes, elem: imagingTag)
if let imagingSurfaceId = imagingTag["id"] {
nodes.register(PhysicalImagingSurfaceNode.self, name: imagingTag["id"]!) { _ in
return imgSurface.copy() as! PhysicalImagingSurfaceNode
}
}
self.physicalImagingSurface = imgSurface
}
}
if let lookAtAttr = elem.attributes["look-at"] { self.lookAt = SpectraSimd.parseFloat3(lookAtAttr) }
if let lookFromAttr = elem.attributes["look-from"] { self.lookFrom = SpectraSimd.parseFloat3(lookFromAttr) }
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let cam = MDLCamera()
cam.nearVisibilityDistance = self.nearVisibilityDistance
cam.farVisibilityDistance = self.farVisibilityDistance
cam.fieldOfView = self.fieldOfView
self.physicalLens.applyToCamera(cam)
self.physicalImagingSurface.applyToCamera(cam)
if lookAt != nil {
if lookFrom != nil {
cam.lookAt(self.lookAt!)
} else {
cam.lookAt(self.lookAt!, from: self.lookFrom!)
}
}
return cam
}
public func copy() -> NodeType {
let cp = CameraNode()
cp.id = self.id
cp.nearVisibilityDistance = self.nearVisibilityDistance
cp.farVisibilityDistance = self.farVisibilityDistance
cp.fieldOfView = self.fieldOfView
cp.lookAt = self.lookAt
cp.lookFrom = self.lookFrom
cp.physicalLens = self.physicalLens
cp.physicalImagingSurface = self.physicalImagingSurface
return cp
}
}
public class StereoscopicCameraNode: SpectraParserNode {
public typealias MDLType = MDLStereoscopicCamera
public typealias NodeType = StereoscopicCameraNode
public var id: String?
public var nearVisibilityDistance: Float = 0.1
public var farVisibilityDistance: Float = 1000.0
public var fieldOfView: Float = Float(53.999996185302734375)
public var physicalLens = PhysicalLensNode()
public var physicalImagingSurface = PhysicalImagingSurfaceNode()
public var lookAt: float3?
public var lookFrom: float3?
public var interPupillaryDistance: Float = 63.0
public var leftVergence: Float = 0.0
public var rightVergence: Float = 0.0
public var overlap: Float = 0.0
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
let cam = CameraNode()
cam.parseXML(nodes, elem: elem)
let stereoCam = applyCameraToStereoscopic(cam)
if let interPupillaryDistance = elem.attributes["inter-pupillary-distance"] { self.interPupillaryDistance = Float(interPupillaryDistance)! }
if let leftVergence = elem.attributes["left-vergence"] { self.leftVergence = Float(leftVergence)! }
if let rightVergence = elem.attributes["right-vergence"] { self.rightVergence = Float(rightVergence)! }
if let overlap = elem.attributes["overlap"] { self.overlap = Float(overlap)! }
}
public func applyCameraToStereoscopic(cam: CameraNode) {
self.id = cam.id
self.nearVisibilityDistance = cam.nearVisibilityDistance
self.farVisibilityDistance = cam.farVisibilityDistance
self.fieldOfView = cam.fieldOfView
self.physicalLens = cam.physicalLens
self.physicalImagingSurface = cam.physicalImagingSurface
self.lookAt = cam.lookAt
self.lookFrom = cam.lookFrom
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let cam = MDLStereoscopicCamera()
cam.nearVisibilityDistance = self.nearVisibilityDistance
cam.farVisibilityDistance = self.farVisibilityDistance
cam.fieldOfView = self.fieldOfView
cam.interPupillaryDistance = self.interPupillaryDistance
cam.leftVergence = self.leftVergence
cam.rightVergence = self.rightVergence
cam.overlap = self.overlap
self.physicalLens.applyToCamera(cam)
self.physicalImagingSurface.applyToCamera(cam)
if lookAt != nil {
if lookFrom != nil {
cam.lookAt(self.lookAt!)
} else {
cam.lookAt(self.lookAt!, from: self.lookFrom!)
}
}
return cam
}
public func copy() -> NodeType {
let cp = StereoscopicCameraNode()
cp.id = self.id
cp.nearVisibilityDistance = self.nearVisibilityDistance
cp.farVisibilityDistance = self.farVisibilityDistance
cp.fieldOfView = self.fieldOfView
cp.lookAt = self.lookAt
cp.lookFrom = self.lookFrom
cp.physicalLens = self.physicalLens
cp.physicalImagingSurface = self.physicalImagingSurface
return cp
}
}
// TODO: Material = "material"
// TODO: MaterialProperty = "material-property"
// TODO: ScatteringFunction = "scattering-function"
public class TextureNode: SpectraParserNode {
public typealias NodeType = TextureNode
public typealias MDLType = MDLTexture
public var id: String?
public var generator: String = "noise_texture_gen"
public var args: [String: GeneratorArg] = [:]
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(container: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let generator = elem.attributes["generator"] { self.generator = generator }
let genArgsSelector = "generator-args > generator-arg"
self.args = GeneratorArg.parseGenArgs(elem, selector: genArgsSelector)
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let models = containers["models"]!
let textureGen = models.resolve(TextureGenerator.self, name: self.generator)!
let texture = textureGen.generate(models, args: self.args)
// TODO: register texture?
// container.register(MDLTexture.self, name: id!) { _ in
// // don't copy texture
// return texture
// }
return texture
}
public func copy() -> NodeType {
let cp = TextureNode()
cp.id = self.id
cp.generator = self.generator
cp.args = self.args
return cp
}
}
public class TextureGeneratorNode: SpectraParserNode {
public typealias NodeType = TextureGeneratorNode
public typealias MDLType = TextureGenerator
public var id: String?
public var type: String = "noise_texture_gen"
public var args: [String: GeneratorArg] = [:]
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(container: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let type = elem.attributes["type"] { self.type = type }
let genArgsSelector = "generator-args > generator-arg"
self.args = GeneratorArg.parseGenArgs(elem, selector: genArgsSelector)
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
// TODO: add to a generators container instead?
let models = containers["models"]!
let texGen = models.resolve(TextureGenerator.self, name: self.type)!
texGen.processArgs(models, args: self.args)
return texGen
}
public func copy() -> NodeType {
let cp = TextureGeneratorNode()
cp.id = self.id
cp.type = self.type
cp.args = self.args
return cp
}
}
public class TextureFilterNode: SpectraParserNode {
public typealias NodeType = TextureFilterNode
public typealias MDLType = MDLTextureFilter
public var id: String?
public var rWrapMode = MDLMaterialTextureWrapMode.Clamp
public var tWrapMode = MDLMaterialTextureWrapMode.Clamp
public var sWrapMode = MDLMaterialTextureWrapMode.Clamp
public var minFilter = MDLMaterialTextureFilterMode.Nearest
public var magFilter = MDLMaterialTextureFilterMode.Nearest
public var mipFilter = MDLMaterialMipMapFilterMode.Nearest
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let rWrap = elem.attributes["r-wrap-mode"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlMaterialTextureWrapMode")!.getValue(rWrap)
self.rWrapMode = MDLMaterialTextureWrapMode(rawValue: enumVal)!
}
if let tWrap = elem.attributes["t-wrap-mode"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlMaterialTextureWrapMode")!.getValue(tWrap)
self.tWrapMode = MDLMaterialTextureWrapMode(rawValue: enumVal)!
}
if let sWrap = elem.attributes["s-wrap-mode"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlMaterialTextureWrapMode")!.getValue(sWrap)
self.sWrapMode = MDLMaterialTextureWrapMode(rawValue: enumVal)!
}
if let minFilter = elem.attributes["min-filter"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlMaterialTextureFilterMode")!.getValue(minFilter)
self.minFilter = MDLMaterialTextureFilterMode(rawValue: enumVal)!
}
if let magFilter = elem.attributes["mag-filter"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlMaterialTextureFilterMode")!.getValue(magFilter)
self.magFilter = MDLMaterialTextureFilterMode(rawValue: enumVal)!
}
if let mipFilter = elem.attributes["mip-filter"] {
let enumVal = nodes.resolve(SpectraEnum.self, name: "mdlMaterialMipMapFilterMode")!.getValue(mipFilter)
self.mipFilter = MDLMaterialMipMapFilterMode(rawValue: enumVal)!
}
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let filter = MDLTextureFilter()
filter.rWrapMode = self.rWrapMode
filter.tWrapMode = self.tWrapMode
filter.sWrapMode = self.sWrapMode
filter.minFilter = self.minFilter
filter.magFilter = self.magFilter
filter.mipFilter = self.mipFilter
return filter
}
public func copy() -> NodeType {
let cp = TextureFilterNode()
cp.id = self.id
cp.rWrapMode = self.rWrapMode
cp.tWrapMode = self.tWrapMode
cp.sWrapMode = self.sWrapMode
cp.minFilter = self.minFilter
cp.magFilter = self.magFilter
cp.mipFilter = self.mipFilter
return cp
}
}
public class TextureSamplerNode: SpectraParserNode {
public typealias NodeType = TextureSamplerNode
public typealias MDLType = MDLTextureSampler
public var id: String?
public var texture: String?
public var hardwareFilter: String?
public var transform: String?
init() {
}
public required init(nodes: Container, elem: XMLElement) {
parseXML(nodes, elem: elem)
}
// public func parseJSON()
// public func parsePlist()
// public func parseXML(nodeContainer: Container)
// so, as above ^^^ there would instead be a nodeContainer, for parsing SpectraXML
// - this would just contain very easily copyable definitions of nodes - no Model I/O
// - these nodes could also instead be structs
// - these nodes could generate the Model I/O, whenever app developer wants
// - the generate method would instead receive a different container.
// - but, does this really work?
// - (parsing works now because it's assumed
// - to proceed in the order which things are declared)
// - having a separate nodeContainer ensures that each dependency registered
// - can be totally self-contained
public func parseXML(nodes: Container, elem: XMLElement) {
if let id = elem.attributes["id"] { self.id = id }
if let texture = elem.attributes["texture"] { self.texture = texture }
if let hardwareFilter = elem.attributes["hardware-filter"] { self.hardwareFilter = hardwareFilter }
if let transform = elem.attributes["transform"] { self.transform = transform }
}
public func generate(containers: [String: Container] = [:], options: [String: Any] = [:], injector: GeneratorClosure? = nil) -> MDLType {
let models = containers["model"]!
let sampler = MDLTextureSampler()
sampler.texture = models.resolve(MDLTexture.self, name: self.texture)
sampler.hardwareFilter = models.resolve(MDLTextureFilter.self, name: self.texture)
if let transform = models.resolve(MDLTransform.self, name: self.transform) {
sampler.transform = transform
} else {
sampler.transform = MDLTransform()
}
return sampler
}
public func copy() -> NodeType {
let cp = TextureSamplerNode()
cp.id = self.id
cp.texture = self.texture
cp.hardwareFilter = self.hardwareFilter
cp.transform = self.transform
return cp
}
// // implemented copy() as a static method for compatibility for now
// public static func copy(obj: MDLTextureSampler) -> MDLTextureSampler {
// let cp = MDLTextureSampler()
// cp.texture = obj.texture // can't really copy textures for resource reasons
// cp.transform = obj.transform ?? MDLTransform()
// if let filter = obj.hardwareFilter {
// cp.hardwareFilter = TextureFilterNode.copy(filter)
// }
// return cp
// }
}
// TODO: Light = "light"
// TODO: LightGenerator = "light-generator"
|
mit
|
2ab7f4b6bd7ab44b9f9bc70c5e99568f
| 37.298667 | 148 | 0.642065 | 4.232001 | false | false | false | false |
WestlakeAPC/gpa-calculator
|
GPACalculator/IQKeyboardManagerSwift/Categories/IQUIWindow+Hierarchy.swift
|
1
|
2255
|
//
// IQUIWindow+Hierarchy.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract UIWindow hierarchy category. */
public extension UIWindow {
/** @return Returns the current Top Most ViewController in hierarchy. */
@objc override public func topMostController()->UIViewController? {
var topController = rootViewController
while let presentedController = topController?.presentedViewController {
topController = presentedController
}
return topController
}
/** @return Returns the topViewController in stack of topMostController. */
public func currentViewController()->UIViewController? {
var currentViewController = topMostController()
while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil {
currentViewController = (currentViewController as! UINavigationController).topViewController
}
return currentViewController
}
}
|
apache-2.0
|
ea65345de12e8240c496398c47fc8ed1
| 41.54717 | 174 | 0.72949 | 5.609453 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/UnitPriceMeasurementMeasuredType.swift
|
1
|
1707
|
//
// UnitPriceMeasurementMeasuredType.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The accepted types of unit of measurement.
public enum UnitPriceMeasurementMeasuredType: String {
/// Unit of measurements representing areas.
case area = "AREA"
/// Unit of measurements representing lengths.
case length = "LENGTH"
/// Unit of measurements representing volumes.
case volume = "VOLUME"
/// Unit of measurements representing weights.
case weight = "WEIGHT"
case unknownValue = ""
}
}
|
mit
|
35b2c29c3af2cd1e1418dd5e918003ca
| 36.108696 | 81 | 0.739895 | 4.246269 | false | false | false | false |
godenzim/NetKit
|
NetKit/Common/Operation/AsyncOperation.swift
|
1
|
2497
|
//
// AsyncOperation.swift
// NetKit
//
// Created by Mike Godenzi on 23.11.14.
// Copyright (c) 2014 Mike Godenzi. All rights reserved.
//
import Foundation
public class AsyncOperation : NSOperation {
public static let AsyncOperationErrorDomain = "AsyncOperationError"
public enum AsyncOperationError : Int {
case Unknown = -1
case Cancelled
case DependencyError
}
private let block : ((operation : AsyncOperation) -> ())?
override public var asynchronous : Bool {
return true
}
private var isExecuting : Bool = false
override public var executing : Bool {
get {
return isExecuting
}
set {
self.willChangeValueForKey("isExecuting")
isExecuting = newValue
self.didChangeValueForKey("isExecuting")
}
}
private var isFinished : Bool = false
override public var finished : Bool {
get {
return isFinished
}
set {
self.willChangeValueForKey("isFinished")
isFinished = newValue
self.didChangeValueForKey("isFinished")
}
}
public var error : NSError?
public var operationWillFinishHandler : ((AsyncOperation) -> Void)?
public var operationDidFinishHandler : ((AsyncOperation) -> Void)?
public init(block : ((operation : AsyncOperation) -> ())? = nil) {
self.block = block
super.init()
}
public override func start() {
guard !self.cancelled else {
stop(NSError(code: .Cancelled, message: "Operation was cancelled"))
return
}
guard canExecute() else {
stop(error ?? NSError(code: .DependencyError, message: "Dependent operation terminated with error"))
return
}
self.executing = true
perform()
}
public func stop(error : NSError? = nil) {
self.error = error
operationWillFinishHandler?(self)
self.finished = true
self.executing = false
operationDidFinishHandler?(self)
}
public func perform() {
guard let block = self.block else {
stop()
return
}
block(operation: self)
}
public func willEnqueueDependantOperations(operations : [NSOperation]) {
}
private func canExecute() -> Bool {
var result = true
let operations = dependencies
for op in operations {
if let asyncOP = op as? AsyncOperation where asyncOP.error != nil {
result = false
error = asyncOP.error
break
}
}
return result
}
}
extension NSError {
private convenience init(code : AsyncOperation.AsyncOperationError, message: String) {
self.init(domain: AsyncOperation.AsyncOperationErrorDomain, code: code.rawValue, userInfo: [NSLocalizedDescriptionKey: message])
}
}
|
mit
|
9a0faf2938207c2a38b0a329d60da3b9
| 21.294643 | 130 | 0.706448 | 3.812214 | false | false | false | false |
NicolasKim/Roy
|
Example/Pods/GRDB.swift/GRDB/Core/DatabaseFunction.swift
|
1
|
15557
|
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An SQL function or aggregate.
public final class DatabaseFunction {
public let name: String
let argumentCount: Int32?
let pure: Bool
private let kind: Kind
private var nArg: Int32 { return argumentCount ?? -1 }
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Returns an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
///
/// - parameters:
/// - name: The function name.
/// - argumentCount: The number of arguments of the function. If
/// omitted, or nil, the function accepts any number of arguments.
/// - pure: Whether the function is "pure", which means that its results
/// only depends on its inputs. When a function is pure, SQLite has
/// the opportunity to perform additional optimizations. Default value
/// is false.
/// - function: A function that takes an array of DatabaseValue
/// arguments, and returns an optional DatabaseValueConvertible such
/// as Int, String, NSDate, etc. The array is guaranteed to have
/// exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
self.name = name
self.argumentCount = argumentCount
self.pure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
}
/// Returns an SQL aggregate function.
///
/// struct MySum : DatabaseAggregate {
/// var sum: Int = 0
///
/// mutating func step(_ dbValues: [DatabaseValue]) {
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
/// sum += int
/// }
/// }
///
/// func finalize() -> DatabaseValueConvertible? {
/// return sum
/// }
/// }
///
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// }
///
/// - parameters:
/// - name: The function name.
/// - argumentCount: The number of arguments of the aggregate. If
/// omitted, or nil, the aggregate accepts any number of arguments.
/// - pure: Whether the aggregate is "pure", which means that its
/// results only depends on its inputs. When an aggregate is pure,
/// SQLite has the opportunity to perform additional optimizations.
/// Default value is false.
/// - aggregate: A type that implements the DatabaseAggregate protocol.
/// For each step of the aggregation, its `step` method is called with
/// an array of DatabaseValue arguments. The array is guaranteed to
/// have exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
self.name = name
self.argumentCount = argumentCount
self.pure = pure
self.kind = .aggregate { return Aggregate() }
}
/// Calls sqlite3_create_function_v2
/// See https://sqlite.org/c3ref/create_function.html
func install(in db: Database) {
// Retain the function definition
let definition = kind.definition
let definitionP = Unmanaged.passRetained(definition).toOpaque()
let code = sqlite3_create_function_v2(
db.sqliteConnection,
name,
nArg,
eTextRep,
definitionP,
kind.xFunc,
kind.xStep,
kind.xFinal,
{ definitionP in
// Release the function definition
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
})
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
}
}
/// Calls sqlite3_create_function_v2
/// See https://sqlite.org/c3ref/create_function.html
func uninstall(in db: Database) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
name,
nArg,
eTextRep,
nil, nil, nil, nil, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
}
}
/// The way to compute the result of a function.
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
private class FunctionDefinition {
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
self.compute = compute
}
}
/// The way to start an aggregate.
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
private class AggregateDefinition {
let makeAggregate: () -> DatabaseAggregate
init(makeAggregate: @escaping () -> DatabaseAggregate) {
self.makeAggregate = makeAggregate
}
}
/// The current state of an aggregate, storable in SQLite
private class AggregateContext {
var aggregate: DatabaseAggregate
var hasErrored = false
init(aggregate: DatabaseAggregate) {
self.aggregate = aggregate
}
}
/// A function kind: an "SQL function" or an "aggregate".
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
private enum Kind {
/// A regular function: SELECT f(1)
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(() -> DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var definition: AnyObject {
switch self {
case .function(let compute):
return FunctionDefinition(compute: compute)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .function = self else { return nil }
return { (sqliteContext, argc, argv) in
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
}
}
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .aggregate = self else { return nil }
return { (sqliteContext, argc, argv) in
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
let aggregateContext = aggregateContextU.takeUnretainedValue()
assert(!aggregateContext.hasErrored)
do {
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
try aggregateContext.aggregate.step(arguments)
} catch {
aggregateContext.hasErrored = true
DatabaseFunction.report(error: error, in: sqliteContext)
}
}
}
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
guard case .aggregate = self else { return nil }
return { (sqliteContext) in
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
let aggregateContext = aggregateContextU.takeUnretainedValue()
aggregateContextU.release()
guard !aggregateContext.hasErrored else {
return
}
do {
try DatabaseFunction.report(
result: aggregateContext.aggregate.finalize(),
in: sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
}
}
}
/// Helper function that extracts the current state of an aggregate from an
/// sqlite function execution context.
///
/// The result must be released when the aggregate concludes.
///
/// See https://sqlite.org/c3ref/context.html
/// See https://sqlite.org/c3ref/aggregate_context.html
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
// The current aggregate buffer
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
// Buffer contains non-null pointer: load aggregate context
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
return aggregateContextP.pointee
} else {
// Buffer contains null pointer: create aggregate context...
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
.makeAggregate()
let aggregateContext = AggregateContext(aggregate: aggregate)
// retain and store in SQLite's buffer
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
var aggregateContextP = aggregateContextU.toOpaque()
withUnsafeBytes(of: &aggregateContextP) {
aggregateContextBufferP.copyBytes(from: $0)
}
return aggregateContextU
}
}
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
switch result?.databaseValue.storage ?? .null {
case .null:
sqlite3_result_null(sqliteContext)
case .int64(let int64):
sqlite3_result_int64(sqliteContext, int64)
case .double(let double):
sqlite3_result_double(sqliteContext, double)
case .string(let string):
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes { bytes in
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
}
}
}
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
if let error = error as? DatabaseError {
if let message = error.message {
sqlite3_result_error(sqliteContext, message, -1)
}
sqlite3_result_error_code(sqliteContext, error.extendedResultCode.rawValue)
} else {
sqlite3_result_error(sqliteContext, "\(error)", -1)
}
}
}
extension DatabaseFunction : Hashable {
/// The hash value
/// :nodoc:
public var hashValue: Int {
return name.hashValue ^ nArg.hashValue
}
/// Two functions are equal if they share the same name and arity.
/// :nodoc:
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
}
}
/// The protocol for custom SQLite aggregates.
///
/// For example:
///
/// struct MySum : DatabaseAggregate {
/// var sum: Int = 0
///
/// mutating func step(_ dbValues: [DatabaseValue]) {
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
/// sum += int
/// }
/// }
///
/// func finalize() -> DatabaseValueConvertible? {
/// return sum
/// }
/// }
///
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// }
public protocol DatabaseAggregate {
/// Creates an aggregate.
init()
/// This method is called at each step of the aggregation.
///
/// The dbValues argument contains as many values as given to the SQL
/// aggregate function.
///
/// -- One value
/// SELECT maxLength(name) FROM players
///
/// -- Two values
/// SELECT maxFullNameLength(firstName, lastName) FROM players
///
/// This method is never called after the finalize() method has been called.
mutating func step(_ dbValues: [DatabaseValue]) throws
/// Returns the final result
func finalize() throws -> DatabaseValueConvertible?
}
|
mit
|
a6b82dbee0bc3d377facf277f31c3c80
| 40.707775 | 157 | 0.588224 | 4.767698 | false | false | false | false |
Bunn/macGist
|
macGist/GistListViewController.swift
|
1
|
2133
|
//
// GistListViewController.swift
// macGist
//
// Created by Fernando Bunn on 23/11/2017.
// Copyright © 2017 Fernando Bunn. All rights reserved.
//
import Cocoa
protocol GistListViewControllerDelegate: class {
func didSelect(gist: Gist, controller: GistListViewController)
}
class GistListViewController: NSViewController {
weak var delegate: GistListViewControllerDelegate?
@IBOutlet weak var tableView: NSTableView!
let githubAPI = GitHubAPI()
var gists: [Gist] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
updateData()
}
private func updateData() {
githubAPI.fetchGists { (error, gists) in
guard let gists = gists else { return }
self.gists = gists
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
private func updateTableSelection() {
tableView.enumerateAvailableRowViews { (rowView, row) in
if let cell = rowView.view(atColumn: 0) as? GistCell {
cell.selected = rowView.isSelected
}
}
}
}
extension GistListViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return gists.count
}
}
extension GistListViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "GistCell"), owner: self) as? GistCell
let gist = gists[row]
cell?.gist = gist
return cell
}
func tableViewSelectionIsChanging(_ notification: Notification) {
updateTableSelection()
}
func tableViewSelectionDidChange(_ notification: Notification) {
if tableView.selectedRow >= 0 {
let gist = gists[tableView.selectedRow]
delegate?.didSelect(gist: gist, controller: self)
}
updateTableSelection()
}
}
|
mit
|
b167baaaffca3cd554d4a576b837233a
| 27.810811 | 132 | 0.641182 | 4.946636 | false | false | false | false |
Hout/TravisTester
|
Sources/SwiftDateTests/RegionStringTests.swift
|
2
|
4910
|
//
// SwiftDateTests.swift
// SwiftDateTests
//
// Created by Daniele Margutti on 23/11/15.
// Copyright © 2015 Daniele Margutti. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftDate
class DateRegionStringSpec: QuickSpec {
override func spec() {
describe("NSDate extension") {
let utc = Region(calendarName: .Gregorian, timeZoneName: .Gmt, localeName: .English)
context("toString UTC") {
let utcDate = DateInRegion(year: 2015, month: 4, day: 13, hour: 22, minute: 10, region: utc)
it("should return proper ISO 8601 string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.Full))) == "2015-04-13T22:10:00Z"
}
it("should return proper ISO 8601 date string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.Date))) == "2015-04-13"
}
it("should return proper ISO 8601 (year format) string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.Year))) == "2015"
}
it("should return proper ISO 8601 (year/month format) string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.YearMonth))) == "2015-04"
}
it("should return proper ISO 8601 (date format) string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.Date))) == "2015-04-13"
}
it("should return proper ISO 8601 (date time format) string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.DateTime))) == "2015-04-13T22:10Z"
}
it("should return proper ISO 8601 (full format) string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.Full))) == "2015-04-13T22:10:00Z"
}
it("should return proper ISO 8601 (extended with fractional seconds format) string") {
expect(utcDate.toString(DateFormat.ISO8601Format(.Extended))) == "2015-04-13T22:10:00.000Z"
}
it("should return proper Alt RSS date string") {
expect(utcDate.toString(DateFormat.AltRSS)) == "13 Apr 2015 22:10:00 +0000"
}
it("should return proper RSS date string") {
expect(utcDate.toString(DateFormat.RSS)) == "Mon, 13 Apr 2015 22:10:00 +0000"
}
it("should return proper custom date string") {
expect(utcDate.toString(DateFormat.Custom("d MMM YY 'at' HH:mm"))) == "13 Apr 15 at 22:10"
}
it("should return proper custom date string") {
expect(utcDate.toString(DateFormat.Custom("eee d MMM YYYY, m 'minutes after' HH '(timezone is' Z')'"))) == "Mon 13 Apr 2015, 10 minutes after 22 (timezone is +0000)"
}
}
context("toString local") {
let date = NSDate(year: 2015, month: 4, day: 13, hour: 22, minute: 10)
let localDate = date.inRegion()
it("should return proper ISO 8601 string") {
expect(localDate.toString(DateFormat.ISO8601Format(.Full))!.hasPrefix("2015-04-13T22:10:00")) == true
expect(date.toString(DateFormat.ISO8601Format(.Full))!.hasPrefix("2015-04-13T22:10:00")) == true
}
it("should return proper ISO 8601 date string") {
expect(localDate.toString(DateFormat.ISO8601Format(.Date))) == "2015-04-13"
expect(date.toString(DateFormat.ISO8601Format(.Date))) == "2015-04-13"
}
it("should return proper Alt RSS date string") {
expect(localDate.toString(DateFormat.AltRSS)!.hasPrefix("13 Apr 2015 22:10:00")) == true
expect(date.toString(DateFormat.AltRSS)!.hasPrefix("13 Apr 2015 22:10:00")) == true
}
it("should return proper RSS date string") {
expect(localDate.toString(DateFormat.RSS)!.hasPrefix("Mon, 13 Apr 2015 22:10:00")) == true
expect(date.toString(DateFormat.RSS)!.hasPrefix("Mon, 13 Apr 2015 22:10:00")) == true
}
it("should return proper custom date string") {
expect(localDate.toString(DateFormat.Custom("d MMM YY 'at' HH:mm"))) == "13 Apr 15 at 22:10"
expect(date.toString(DateFormat.Custom("d MMM YY 'at' HH:mm"))) == "13 Apr 15 at 22:10"
}
it("should return proper custom date string") {
expect(localDate.toString(DateFormat.Custom("eee d MMM YYYY, m 'minutes after' HH '(timezone is' Z')'"))!.hasPrefix("Mon 13 Apr 2015, 10 minutes after 22 (timezone is ")) == true
expect(date.toString(DateFormat.Custom("eee d MMM YYYY, m 'minutes after' HH '(timezone is' Z')'"))!.hasPrefix("Mon 13 Apr 2015, 10 minutes after 22 (timezone is ")) == true
}
}
}
}
}
|
mit
|
1bb7703250744ee05733fc5e383b00ae
| 43.225225 | 198 | 0.580566 | 4.05033 | false | false | false | false |
CrossWaterBridge/CollectionViewIndex
|
CollectionViewIndexDemo/ViewController.swift
|
1
|
2853
|
//
// Copyright (c) 2018 Hilton Campbell
//
// 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 CollectionViewIndex
class ViewController: UIViewController {
lazy var collectionViewIndex: CollectionViewIndex = {
let collectionViewIndex = CollectionViewIndex()
collectionViewIndex.indexTitles = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"]
collectionViewIndex.addTarget(self, action: #selector(selectedIndexDidChange), for: .valueChanged)
collectionViewIndex.translatesAutoresizingMaskIntoConstraints = false
return collectionViewIndex
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(collectionViewIndex)
let views: [String: AnyObject] = [
"topLayoutGuide": topLayoutGuide,
"bottomLayoutGuide": bottomLayoutGuide,
"collectionViewIndex": collectionViewIndex,
]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[collectionViewIndex]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[topLayoutGuide][collectionViewIndex][bottomLayoutGuide]", options: [], metrics: nil, views: views))
}
@objc func selectedIndexDidChange(_ collectionViewIndex: CollectionViewIndex) {
title = collectionViewIndex.indexTitles[collectionViewIndex.selectedIndex]
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
collectionViewIndex.preferredMaxLayoutHeight = view.bounds.height - topLayoutGuide.length - bottomLayoutGuide.length
}
}
|
mit
|
5ca058a7a353536eb389e001f4b82d0d
| 45.016129 | 180 | 0.70347 | 4.893654 | false | false | false | false |
mleiv/CodableDictionary
|
CodableDictionary.playground/Sources/CodableDictionaryValueType.swift
|
1
|
6072
|
//
// CodableDictionaryValueType.swift
// MEGameTracker
//
// Copyright © 2017 Emily Ivie.
//
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import Foundation
/// A wrapper for the permitted Codable value types.
/// Permits generic dictionary encoding/decoding when used with CodableDictionary.
public enum CodableDictionaryValueType: Codable {
case uuid(UUID)
case bool(Bool)
case int(Int)
case double(Double)
case float(Float)
case date(Date)
case string(String)
case data(Data)
indirect case array([CodableDictionaryValueType])
indirect case dictionary(CodableDictionary)
case empty
// public init(_ value: Date) { self = .date(value) }
// public init(_ value: UUID) { self = .uuid(value) }
// public init(_ value: Int) { self = .int(value) }
// public init(_ value: Float) { self = .float(value) }
// public init(_ value: Bool) { self = .bool(value) }
// public init(_ value: String) { self = .string(value) }
// public init(_ value: Data) { self = .data(value) }
// public init(_ value: CodableDictionary) { self = .dictionary(value) }
// // nil?
public init(_ value: Any?) {
self = {
if let value = value as? CodableDictionaryValueType {
return value
} else if let value = value as? UUID {
return .uuid(value)
} else if let value = value as? Bool {
return .bool(value)
} else if let value = value as? Int {
return .int(value)
} else if let value = value as? Double {
// FYI, Int values are currently encoded to double in CK :(
return .double(value)
} else if let value = value as? Float {
return .float(value)
} else if let value = value as? Date {
return .date(value)
} else if let value = value as? Data {
return .data(value)
} else if let value = value as? String {
return .string(value)
} else if let value = value as? CodableDictionary {
return .dictionary(value)
} else if let value = value as? [Any?] {
return .array(value.map {
guard let row = $0 else { return .empty }
if let d = row as? [String: Any?] {
return CodableDictionaryValueType(CodableDictionary(d))
} else {
return CodableDictionaryValueType(row)
}
})
} else {
return .empty
}
}()
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self = {
if let value = try? container.decode(CodableDictionary.self) {
return .dictionary(value)
} else if let value = try? container.decode([CodableDictionaryValueType].self) {
return .array(value)
} else if let value = try? container.decode(UUID.self) {
return .uuid(value)
} else if let value = try? container.decode(Bool.self) {
return .bool(value)
} else if let value = try? container.decode(Int.self) {
return .int(value)
} else if let value = try? container.decode(Double.self) {
return .double(value)
} else if let value = try? container.decode(Float.self) {
return .float(value)
} else if let value = try? container.decode(Date.self) {
return .date(value)
} else if let value = try? container.decode(Data.self) {
if let stringValue = try? container.decode(String.self),
["Triggers", "BlockedUntil"].contains(stringValue) { // I can't even...
return .string(stringValue)
}
return .data(value)
} else if let value = try? container.decode(String.self) {
return .string(value)
} else {
return .empty
}
}()
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .uuid(let value): try container.encode(value)
case .bool(let value): try container.encode(value)
case .int(let value): try container.encode(value)
case .double(let value): try container.encode(value)
case .float(let value): try container.encode(value)
case .date(let value): try container.encode(value)
case .data(let value): try container.encode(value)
case .string(let value): try container.encode(value)
case .array(let value): try container.encode(value)
case .dictionary(let value): try container.encode(value)
default: try container.encodeNil()
}
}
public var value: Any? {
switch self {
case .uuid(let value): return value
case .bool(let value): return value
case .int(let value): print(value);return value
case .double(let value): return value
case .float(let value): return value
case .date(let value): return value
case .data(let value): return value
case .string(let value): return value
case .array(let value): return value.map { $0.value }
case .dictionary(let value): return value
default: return nil
}
}
}
extension CodableDictionaryValueType: CustomDebugStringConvertible {
public var debugDescription: String {
return String(describing: value)
}
}
extension CodableDictionaryValueType: CustomStringConvertible {
public var description: String {
return String(describing: value)
}
}
|
mit
|
35a640aff2b7ea780ce6bbd94488f20a
| 39.205298 | 93 | 0.570417 | 4.500371 | false | false | false | false |
Boerworz/Gagat
|
Gagat Example/ArchiveTableCellView.swift
|
1
|
1141
|
//
// ArchiveTableCellView.swift
// Gagat
//
// Created by Tim Andersson on 2017-06-03.
// Copyright © 2017 Cocoabeans Software. All rights reserved.
//
import UIKit
class ArchiveTableCellView: UITableViewCell {
struct Style {
let backgroundColor: UIColor
let titleTextColor: UIColor
let descriptionTextColor: UIColor
static let light = Style(
backgroundColor: .white,
titleTextColor: .black,
descriptionTextColor: UIColor(white: 0.4, alpha: 1.0)
)
static let dark = Style(
backgroundColor: UIColor(white: 0.2, alpha: 1.0),
titleTextColor: .white,
descriptionTextColor: UIColor(white: 0.6, alpha: 1.0)
)
}
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var artworkImageView: UIImageView!
@IBOutlet private weak var descriptionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
artworkImageView.layer.cornerRadius = 10.0
}
func apply(style: Style) {
backgroundColor = style.backgroundColor
titleLabel.textColor = style.titleTextColor
descriptionLabel.textColor = style.descriptionTextColor
}
}
|
mit
|
a80bfef31609e355511688cd6d8d2a4e
| 23.782609 | 62 | 0.714912 | 4.100719 | false | false | false | false |
hazzargm/CSSE-290-iOSDev
|
GasStats/GasStats/AppDelegate.swift
|
1
|
5957
|
//
// AppDelegate.swift
// GasStats
//
// Created by Grant Smith on 02/02/15.
// Copyright (c) 2015 Gordon Hazzard & Grant Smith. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let controller = self.window!.rootViewController as LogInViewController
controller.managedObjectContext = self.managedObjectContext
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 "hazzardsmith.GasStats" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
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("GasStats", 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("GasStats.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
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)
// 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()
}
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 saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// 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()
}
}
}
}
|
mit
|
fd05d05ac1bc244af8687d47a22cb26a
| 52.1875 | 287 | 0.74937 | 5.366667 | false | false | false | false |
zdima/ZDComboBox
|
ZDComboBox/ZDComboBox.swift
|
1
|
6266
|
//
// ZDComboBox.swift
// MyFina
//
// Created by Dmitriy Zakharkin on 3/7/15.
// Copyright (c) 2015 ZDima. All rights reserved.
//
import Cocoa
@IBDesignable
public class ZDComboBox: NSTextField {
/// Define key for display name
@IBInspectable var displayKey: String!
/// Define key for child list
@IBInspectable var childsKey: String?
/// NSArrayController or NSTreeController for popup items
@IBOutlet var topLevelObjects: NSObjectController? {
didSet {
onObjectCollectionChange(oldValue,topLevelObjects)
}
}
override public class func cellClass() -> AnyClass? {
return ZDComboBoxCell.self
}
init(frame frameRect: NSRect, displayKey dkey: String) {
displayKey = dkey
super.init(frame: frameRect)
setup()
}
required public init?(coder: NSCoder) {
if let ucoder = coder as? NSKeyedUnarchiver {
// replace class for NSTextFieldCell to use cell object for ZDComboBox
let superCellClassName = "NSTextFieldCell"
let oldValue: AnyClass? = ucoder.classForClassName(superCellClassName)
ucoder.setClass(ZDComboBox.cellClass(), forClassName: superCellClassName)
super.init(coder: coder)
// restore previous setting
ucoder.setClass(oldValue, forClassName: superCellClassName)
} else {
super.init(coder: coder)
}
setup()
}
deinit {
if let oldController = topLevelObjects {
oldController.removeObserver(self, forKeyPath: "content")
}
}
var buttonState: Int {
get {
if let btn = dropDownButton { return btn.state }
return 0
}
set {
if let btn = dropDownButton { btn.state = newValue }
}
}
var isHierarchical: Bool {
if let oCtrl = topLevelObjects as? NSTreeController {
return true
}
return false
}
func setContentRootNode() {
if let cbDelegate = delegate as? ZDComboFieldDelegate,
let content = cbDelegate.popupContent {
if let oCtrl = topLevelObjects as? NSTreeController {
content.rootNodes = oCtrl.arrangedObjects as? [AnyObject]
} else if let oCtrl = topLevelObjects as? NSArrayController {
content.rootNodes = oCtrl.arrangedObjects as? [AnyObject]
} else if topLevelObjects != nil {
let msg = "ControllerTypeError".localized(tableName: "ZDComboBox")
NSException(name: "Invalid argument", reason: msg, userInfo: nil).raise()
content.rootNodes = []
} else {
content.rootNodes = []
}
content.invalidateFilter()
}
}
override public func observeValueForKeyPath( keyPath: String, ofObject object: AnyObject,
change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "content" {
setContentRootNode()
}
}
private var userDelegate: AnyObject?
private var cbDelegate: ZDComboFieldDelegate = ZDComboFieldDelegate()
private var dropDownButton: NSButton?
func setup() {
if delegate == nil {
delegate = cbDelegate
} else if !delegate!.isKindOfClass(ZDComboFieldDelegate.self) {
userDelegate = delegate
delegate = cbDelegate
}
// setup drop down button
let buttonHeight = frame.size.height
let buttonWidth = buttonHeight*ZDComboBoxCell.buttonAspect
let buttonFrame = NSIntegralRect(
NSRect(x: frame.size.width-buttonWidth, y: 0,
width: buttonWidth, height: buttonHeight))
dropDownButton = NSButton(frame: buttonFrame)
dropDownButton!.setButtonType(NSButtonType.PushOnPushOffButton)
dropDownButton!.bezelStyle = NSBezelStyle.ShadowlessSquareBezelStyle
dropDownButton!.image = NSImage(named: "NSDropDownIndicatorTemplate")
dropDownButton!.target = self
dropDownButton!.action = "dropDownButtonClicked:"
self.addSubview(dropDownButton!)
}
override public func resizeSubviewsWithOldSize(oldSize: NSSize) {
// need to move button if frame of a control changed
let buttonHeight = frame.size.height
let buttonWidth = buttonHeight*ZDComboBoxCell.buttonAspect
dropDownButton!.frame = NSIntegralRect(
NSRect(x: frame.size.width-buttonWidth, y: 0,
width: buttonWidth, height: buttonHeight))
super.resizeSubviewsWithOldSize(oldSize)
}
func dropDownButtonClicked(sender: AnyObject) {
if dropDownButton!.state == NSOffState {
ZDPopupWindowManager.popupManager.hidePopup()
} else {
if self.window!.firstResponder != self {
self.window!.makeFirstResponder(self)
}
if let popupDelegate = delegate as? ZDPopupContentDelegate {
if !popupDelegate.showPopupForControl(self) {
dropDownButton!.state = NSOffState
}
}
}
}
override public func setValue(value: AnyObject?, forKey key: String) {
switch(key) {
case "displayKey":
if let string = value as? String {
displayKey = string
}
case "childsKey":
if let string = value as? String {
childsKey = string
}
default:
super.setValue(value, forKey: key)
}
}
dynamic var selectedObject: AnyObject? {
didSet {
// TODO set value of the text field
}
}
override public func selectText(sender: AnyObject?) {
super.selectText(sender)
let insertionPoint: Int = count(stringValue)
var r: NSRange = NSRange(location: insertionPoint,length: 0)
if let textEditor = window!.fieldEditor( true, forObject: self) {
textEditor.selectedRange = r
}
}
public override func textDidBeginEditing(notification: NSNotification) {
}
override public func textDidEndEditing(notification: NSNotification) {
ZDPopupWindowManager.popupManager.hidePopup()
let insertionPoint: Int = count(stringValue)
var r: NSRange = NSRange(location: insertionPoint,length: 0)
if let textEditor = window!.fieldEditor( true, forObject: self) {
textEditor.selectedRange = r
}
if let popupDelegate = delegate as? ZDPopupContentDelegate {
popupDelegate.updateBindingProperty()
}
super.textDidEndEditing(notification)
}
private func onObjectCollectionChange(
oldValue: NSObjectController?,
_ newValue: NSObjectController?) {
setContentRootNode()
if let oldController = oldValue {
oldController.removeObserver(self, forKeyPath: "content")
}
if let newController = topLevelObjects {
let options = NSKeyValueObservingOptions.Old|NSKeyValueObservingOptions.New
newController.addObserver( self, forKeyPath: "content",
options: options, context: nil)
}
}
}
|
mit
|
81b8c02a7a7bb0eab0c829f852c1a84b
| 28.696682 | 90 | 0.719598 | 3.884687 | false | false | false | false |
djflsdl08/BasicIOS
|
Aaron Hillegass/BasicSwift.playground/Contents.swift
|
1
|
3667
|
//: Playground - noun: a place where people can play
// reference materials - iOS Programming: The Big Nerd Ranch Guide
import UIKit
var str = "Hello, playground"
str = "Hello, Swift"
let constStr = str
// constStr = "Hello, world" -> error : 'let' keyword is constant. So you can't change the value.
// type inference : The compiler deduces its type by default. -> option + click
var nextYear : Int
var bodyTemp : Float // 32 bit, Double : 64 bit, Float80 : 80 bit
var hasPet : Bool // true or false
// Collections : Array, Dictionary, Set
// Array : A collection of ordered elements.
var arrayOfInts : Array<Int>
var arrayOfInts2 : [Int]
// Dictionary : A collection of unordered key-value pairs.
var dictionaryOfCapitalsByCountry : Dictionary<String,String>
var dictionaryOfCapitalsByCountry2 : [String:String]
// Set : A collection of unordered elements.
var winningLotteryNumbers : Set<Int>
// Number Literal
let number = 42
let fmStation = 91.1
let countingUp = ["one","two"]
let nameByParkingSpace = [13 : "Alice", 27 : "Bob"]
// Subscripting
let secondElement = countingUp[1]
// Initializer
let emptyString = String()
let emptyArrayOfInts = [Int]()
let emptySetOfFloats = Set<Float>()
// Has default value.
let defaultNumber = Int() // 0
let defaultBool = Bool() // false
let defaultFloat = Float() //0.0
// some Example.
let meaningOfLife = String(number) //"42"
let availableRooms = Set([205,411,412]) //{411,205,412}
let floatFromLiteral = Float(3.14) // 3.14
let easyPi = 3.14 // Default type is Double
let floatFromDouble = Float(easyPi) // 3.14 -> type of 'floatFromDouble' is Float
let floatingPi : Float = 3.14 // 3.14 -> type of 'floatFromDouble' is Float
// The example of Properties.
countingUp.count // 2
emptyString.isEmpty // true
// The example of instance methods.
var countingUp2 = ["one","two"]
countingUp2.append("three") // countingUp2 = ["one","two","three"]
// 'Optional' indicates that the variable may not store any value at all.
var reading1 : Float? // nil
var reading2 : Float? // nil
var reading3 : Float? // nil
reading1 = 9.8
reading2 = 9.2
//reading3 = 9.6
// let avgReading = (reading1 + reading2 + reading2) / 3 -> error : Optional need unwrapping.
// let avgReading = (reading1! + reading2! + reading3!) / 3 -> error : Because the value of reading3 is nil.
// Optional binding
if let r1 = reading1, let r2 = reading2, let r3 = reading3 {
let avgReading = (r1 + r2 + r3) / 3
} else {
let errorString = "Instrument reported a reading that was nil"
}
// Subscripting of Dictionary
let space13Assignee : String? = nameByParkingSpace[13] // "Alice"
let space27Assignee : String? = nameByParkingSpace[27] // "Bob"
let space22Assignee : String? = nameByParkingSpace[22] // nil
if let space29Assignee = nameByParkingSpace[29] {
print("Key 29 is assigned in the dictionary!")
} else {
print("Key 29 is not assigned in the dictionary!")
} // -> "Key 29 is not assigned in the dictionary!"
// loop and insert string
let range = 0..<countingUp.count // range = (0..<2)
for i in range {
let string = countingUp[i] // 2times
}
for string in countingUp {
let value = string // 2times
}
// Tuple
for (i,string) in countingUp.enumerated() {
//(0,"one"),(1,"two")
let value2 = string // 2times
}
for (space,name) in nameByParkingSpace {
let permit = "Space \(space) : \(name)"
}
//Enum : A set of values
enum PieType {
case Apple
case Cherry
case Pecan
}
let name : String
var favoritePie = PieType.Apple
switch favoritePie {
case .Apple : name = "Apple"
case .Cherry : name = "Cherry"
case .Pecan : name = "Pecan"
}
// name = "Apple"
|
mit
|
b9f84841fdb53d071661b8e8ee708a60
| 26.780303 | 108 | 0.684483 | 3.382841 | false | false | false | false |
jantimar/Weather-forecast
|
Weather forecast/SettignsTableViewController.swift
|
1
|
4322
|
//
// SettignsTableViewController.swift
// Weather forecast
//
// Created by Jan Timar on 6.5.2015.
// Copyright (c) 2015 Jan Timar. All rights reserved.
//
import UIKit
class SettignsTableViewController: UITableViewController {
// MARK: Properties
enum TempratureType: String {
case Kelvin = "Kelvin"
case Celsius = "Celsius"
case Fahrenheit = "Fahrenheit"
func unitSymbol() -> String {
switch self {
case .Kelvin: return "K"
case .Celsius: return "℃"
case .Fahrenheit: return "℉"
}
}
}
enum LengthType: String {
case Meters = "Meters"
case Miles = "Miles"
}
private var lengthType: LengthType? {
didSet {
if lengthType != nil {
lengthButton.setTextWithAnimation(lengthType!.rawValue)
defaults.setObject(lengthType!.rawValue, forKey: Constants.LengthUnitKey)
}
}
}
private var tempratureType: TempratureType? {
didSet {
if tempratureType != nil {
tempretureButton.setTextWithAnimation(tempratureType!.rawValue)
defaults.setObject(tempratureType!.rawValue, forKey: Constants.TempratureUnitKey)
}
}
}
private var defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var tempretureButton: UIButton!
@IBOutlet weak var lengthButton: UIButton!
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.whiteColor()
// set header title color
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel.textColor = UIColor(red: 37.0/255.0, green: 142.0/255.0, blue: 1.0, alpha: 1.0)
}
}
// MARK: Life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
// load value from user defaults
if let lengthTypeRawValue = defaults.stringForKey(Constants.LengthUnitKey) {
lengthType = LengthType(rawValue: lengthTypeRawValue)
} else {
lengthType = .Meters
}
if let tempratureTypeRawValue = defaults.stringForKey(Constants.TempratureUnitKey) {
tempratureType = TempratureType(rawValue: tempratureTypeRawValue)
} else {
tempratureType = .Celsius
}
// set gestures
var swipeRight = UISwipeGestureRecognizer(target: self, action: "swipeGesture:")
swipeRight.direction = .Right
self.tableView?.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipeGesture:")
swipeLeft.direction = .Left
self.tableView?.addGestureRecognizer(swipeLeft)
}
// MARK: Buttons press
@IBAction func lengthUnitPress(sender: UIButton) {
if lengthType != nil {
switch lengthType! {
case .Miles:
lengthType = .Meters
case .Meters: fallthrough
default:
lengthType = .Miles
}
}
}
@IBAction func unitOfTempreturePress(sender: UIButton) {
if tempratureType != nil {
switch tempratureType! {
case .Fahrenheit:
tempratureType = .Kelvin
case .Kelvin:
tempratureType = .Celsius
case .Celsius: fallthrough
default:
tempratureType = .Fahrenheit
}
}
}
// MARK: Gestures
@IBAction func swipeGesture(sender: UISwipeGestureRecognizer) {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
if let tabBarController = appDelegate.window?.rootViewController as? UITabBarController {
switch sender.direction {
case UISwipeGestureRecognizerDirection.Left: tabBarController.selectedIndex = 0
case UISwipeGestureRecognizerDirection.Right: tabBarController.selectedIndex = 1
default: break
}
}
}
}
}
|
mit
|
ac2aa23c102738a22c8f18166d90019c
| 30.289855 | 114 | 0.586846 | 5.304668 | false | false | false | false |
gaolichuang/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Contacts/ContactsViewController.swift
|
1
|
11731
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
import MessageUI
class ContactsViewController: ContactsBaseViewController, UISearchBarDelegate, UISearchDisplayDelegate {
// MARK: -
// MARK: Public vars
var tableView: UITableView!
var searchView: UISearchBar?
var searchDisplay: UISearchDisplayController?
var searchSource: ContactsSearchSource?
var binder = Binder()
// MARK: -
// MARK: Constructors
init() {
super.init(contentSection: 1)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabPeople", comment: "People Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("TabIconContacts"),
selectedImage: MainAppTheme.tab.createSelectedIcon("TabIconContactsHighlighted"));
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
tableView = UITableView()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.rowHeight = 76
tableView.backgroundColor = MainAppTheme.list.backyardColor
self.extendedLayoutIncludesOpaqueBars = true
view.addSubview(tableView)
view.backgroundColor = MainAppTheme.list.bgColor
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
self.extendedLayoutIncludesOpaqueBars = true
bindTable(tableView, fade: false);
searchView = UISearchBar()
searchView!.delegate = self
searchView!.frame = CGRectMake(0, 0, 0, 44)
searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
MainAppTheme.search.styleSearchBar(searchView!)
searchDisplay = UISearchDisplayController(searchBar: searchView!, contentsController: self)
searchDisplay?.searchResultsDelegate = self
searchDisplay?.searchResultsTableView.rowHeight = 56
searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
searchDisplay?.searchResultsTableView.backgroundColor = Resources.BackyardColor
searchDisplay?.searchResultsTableView.frame = tableView.frame
let header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(searchView!)
tableView.tableHeaderView = header
searchSource = ContactsSearchSource(searchDisplay: searchDisplay!)
super.viewDidLoad();
navigationItem.title = NSLocalizedString("TabPeople", comment: "People Title")
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "doAddContact")
placeholder.setImage(
UIImage(named: "contacts_list_placeholder"),
title: NSLocalizedString("Placeholder_Contacts_Title", comment: "Placeholder Title"),
subtitle: NSLocalizedString("Placeholder_Contacts_Message", comment: "Placeholder Message"),
actionTitle: NSLocalizedString("Placeholder_Contacts_Action", comment: "Placeholder Action"),
subtitle2: NSLocalizedString("Placeholder_Contacts_Message2", comment: "Placeholder Message2"),
actionTarget: self, actionSelector: Selector("showSmsInvitation"),
action2title: nil,
action2Selector: nil)
binder.bind(Actor.getAppState().isContactsEmpty, closure: { (value: Any?) -> () in
if let empty = value as? JavaLangBoolean {
if Bool(empty.booleanValue()) == true {
self.showPlaceholder()
} else {
self.hidePlaceholder()
}
}
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let selected = tableView.indexPathForSelectedRow
if (selected != nil){
tableView.deselectRowAtIndexPath(selected!, animated: animated);
}
// SearchBar hack
let searchBar = searchDisplay!.searchBar
let superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
// Header hack
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
if (searchDisplay != nil && searchDisplay!.active){
MainAppTheme.search.applyStatusBar()
} else {
MainAppTheme.navigation.applyStatusBar()
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
searchDisplay?.setActive(false, animated: animated)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 1) {
return super.tableView(tableView, numberOfRowsInSection: section)
} else {
return 2
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 1) {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
} else {
if (indexPath.row == 1) {
let reuseId = "cell_invite";
let res = ContactActionCell(reuseIdentifier: reuseId)
res.bind("ic_add_user",
actionTitle: NSLocalizedString("ContactsActionAdd", comment: "Action Title"),
isLast: false)
return res
} else {
let reuseId = "cell_add";
let res = ContactActionCell(reuseIdentifier: reuseId)
res.bind("ic_invite_user",
actionTitle: NSLocalizedString("ContactsActionInvite", comment: "Action Title"),
isLast: false)
return res
}
}
}
// MARK: -
// MARK: Methods
func doAddContact() {
let alertView = UIAlertView(
title: NSLocalizedString("ContactsAddHeader", comment: "Alert Title"),
message: NSLocalizedString("ContactsAddHint", comment: "Alert Hint"),
delegate: self,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Alert Cancel"),
otherButtonTitles: NSLocalizedString("AlertNext", comment: "Alert Next"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.show()
}
func showSmsInvitation() {
showSmsInvitation(nil)
}
// MARK: -
// MARK: UITableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (tableView == self.tableView && indexPath.section == 0) {
if (indexPath.row == 0) {
showSmsInvitation()
} else {
doAddContact()
}
let selected = tableView.indexPathForSelectedRow
if (selected != nil){
tableView.deselectRowAtIndexPath(selected!, animated: true);
}
return
}
var contact: ACContact!;
if (tableView == self.tableView) {
contact = objectAtIndexPath(indexPath) as! ACContact
} else {
contact = searchSource!.objectAtIndexPath(indexPath) as! ACContact
}
navigateToMessagesWithUid(contact.uid)
}
// MARK: -
// MARK: Navigation
func showSmsInvitation(recipients: [String]?) {
if MFMessageComposeViewController.canSendText() {
if AppConfig.appInviteUrl == nil {
// Silently ignore if not configured
return
}
let messageComposeController = MFMessageComposeViewController()
messageComposeController.messageComposeDelegate = self
messageComposeController.body = localized("InviteText")
.replace("{link}", dest: AppConfig.appInviteUrl!)
messageComposeController.recipients = recipients
messageComposeController.navigationBar.tintColor = MainAppTheme.navigation.titleColor
presentViewController(messageComposeController, animated: true, completion: { () -> Void in
MainAppTheme.navigation.applyStatusBarFast()
})
} else {
// TODO: Show or not to show?
UIAlertView(title: "Error", message: "Cannot send SMS", delegate: nil, cancelButtonTitle: "OK").show()
}
}
private func navigateToMessagesWithUid(uid: jint) {
let conversationController = ConversationViewController(peer: ACPeer.userWithInt(uid))
navigateDetail(conversationController)
MainAppTheme.navigation.applyStatusBar()
}
}
// MARK: -
// MARK: MFMessageComposeViewController Delegate
extension ContactsViewController: MFMessageComposeViewControllerDelegate {
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: -
// MARK: UIAlertView Delegate
extension ContactsViewController: UIAlertViewDelegate {
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
// TODO: Localize
if buttonIndex == 1 {
let textField = alertView.textFieldAtIndex(0)!
if textField.text?.length > 0 {
execute(Actor.findUsersCommandWithQuery(textField.text), successBlock: { (val) -> () in
var user: ACUserVM?
user = val as? ACUserVM
if user == nil {
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? ACUserVM {
user = tempUser
}
}
}
}
if user != nil {
self.execute(Actor.addContactCommandWithUid(user!.getId()), successBlock: { (val) -> () in
self.navigateToMessagesWithUid(user!.getId())
}, failureBlock: { (val) -> () in
self.showSmsInvitation([textField.text!])
})
} else {
self.showSmsInvitation([textField.text!])
}
}, failureBlock: { (val) -> () in
self.showSmsInvitation([textField.text!])
})
}
}
}
}
|
mit
|
8c66ca603117b29857460040c5613c64
| 37.339869 | 151 | 0.597903 | 5.850873 | false | false | false | false |
iosliutingxin/DYVeideoVideo
|
DYZB/DYZB/Classes/Main/Model/AnchorGroup.swift
|
1
|
969
|
//
// AnchorGroup.swift
// DYZB
//
// Created by 李孔文 on 2018/3/4.
// Copyright © 2018年 iOS _Liu. All rights reserved.
//
import UIKit
//采用kvc的方式设置模型
class AnchorGroup: NSObject {
//主播模型数组
fileprivate lazy var anchorArray : [AnchorModel] = [AnchorModel]()
//该组中的房间信息
var room_list : [[NSString : NSObject]]?{
didSet{
guard let room_list = room_list else {return}
for dict in room_list{
let group = AnchorModel(dict: dict as [String : AnyObject])
self.anchorArray.append(group)
}
}
}
//组显示的标题
var tag_name : String = ""
//组显示的图标
var icon_name : String = ""
//字典转模型
init(dict:[String:AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
}
}
|
mit
|
7c12ff1d70a3c8e5abfe76d41c852689
| 20.975 | 75 | 0.555176 | 3.788793 | false | false | false | false |
maxvol/RxCloudKit
|
RxCloudKit/RecordModifier.swift
|
1
|
3412
|
//
// RecordModifier.swift
// RxCloudKit
//
// Created by Maxim Volgin on 12/08/2017.
// Copyright (c) RxSwiftCommunity. All rights reserved.
//
import RxSwift
import CloudKit
@available(iOS 10, *)
public enum RecordModifyEvent {
case progress(CKRecord, Double) // save progress
case result(CKRecord, Error?) // save result
case changed([CKRecord])
case deleted([CKRecord.ID])
}
@available(iOS 10, *)
final class RecordModifier {
typealias Observer = AnyObserver<RecordModifyEvent>
fileprivate var index = 0
fileprivate var chunk = 400
private let observer: Observer
private let database: CKDatabase
private let records: [CKRecord]?
private let recordIDs: [CKRecord.ID]?
init(observer: Observer, database: CKDatabase, recordsToSave records: [CKRecord]?, recordIDsToDelete recordIDs: [CKRecord.ID]?) {
self.observer = observer
self.database = database
self.records = records
self.recordIDs = recordIDs
self.batch(recordsToSave: records, recordIDsToDelete: recordIDs)
}
private func batch(recordsToSave records: [CKRecord]?, recordIDsToDelete recordIDs: [CKRecord.ID]?) {
let operation = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: recordIDs)
operation.perRecordProgressBlock = self.perRecordProgressBlock
operation.perRecordCompletionBlock = self.perRecordCompletionBlock
operation.modifyRecordsCompletionBlock = self.modifyRecordsCompletionBlock
database.add(operation)
}
private func batch() {
let tuple = self.tuple()
self.batch(recordsToSave: tuple.0, recordIDsToDelete: tuple.1)
}
private var count: Int {
return max(self.records?.count ?? 0, self.recordIDs?.count ?? 0)
}
private func until() -> Int {
return index + chunk
}
private func tuple() -> ([CKRecord]?, [CKRecord.ID]?) {
let until = self.until()
return (self.records == nil ? nil : Array(self.records![index..<until]), self.recordIDs == nil ? nil : Array(self.recordIDs![index..<until]))
}
// MARK:- callbacks
// save progress
private func perRecordProgressBlock(record: CKRecord, progress: Double) {
observer.on(.next(.progress(record, progress)))
}
// save result
private func perRecordCompletionBlock(record: CKRecord, error: Error?) {
observer.on(.next(.result(record, error)))
}
private func modifyRecordsCompletionBlock(records: [CKRecord]?, recordIDs: [CKRecord.ID]?, error: Error?) {
if let error = error {
if let ckError = error as? CKError {
switch ckError.code {
case .limitExceeded:
self.chunk = Int(self.chunk / 2)
self.batch()
return
default:
break
}
}
observer.on(.error(error))
return
}
if let records = records {
observer.on(.next(.changed(records)))
}
if let recordIDs = recordIDs {
observer.on(.next(.deleted(recordIDs)))
}
if self.until() < self.count {
self.index += self.chunk
self.batch()
} else {
observer.on(.completed)
}
}
}
|
mit
|
9add9648be446a1488d7beb157efa6d6
| 30.592593 | 149 | 0.607855 | 4.765363 | false | false | false | false |
Lweek/Formulary
|
Formulary/Input/NamedTextField.swift
|
2
|
4216
|
//
// NamedTextField.swift
// Formulary
//
// Created by Fabian Canas on 1/17/15.
// Copyright (c) 2015 Fabian Canas. All rights reserved.
//
import UIKit
class NamedTextField: UITextField {
let nameLabel = UILabel()
var nameFont :UIFont = UIFont.systemFontOfSize(12) {
didSet {
nameLabel.font = nameFont
validationLabel.font = nameFont
}
}
var topMargin :CGFloat = 4
var marginForContent :CGFloat {
get {
return text.isEmpty ? 0 : 4
}
}
override var placeholder :String? {
didSet {
nameLabel.text = placeholder
nameLabel.sizeToFit()
}
}
// MARK: Validation
var hasEverResignedFirstResponder = false
override func resignFirstResponder() -> Bool {
hasEverResignedFirstResponder = true
return super.resignFirstResponder()
}
let validationLabel = UILabel()
var validationColor: UIColor = UIColor.redColor() {
didSet {
validationLabel.textColor = validationColor
}
}
var validation: (String?) -> (Bool, String) = { _ in (true, "") }
private func validate() {
let (valid, errorString) = validation(text)
validationLabel.text = errorString
validationLabel.sizeToFit()
if text.isEmpty {
hideLabel(isFirstResponder(), label: nameLabel)
if hasEverResignedFirstResponder && !valid {
showLabel(true, label: validationLabel)
} else {
hideLabel(isFirstResponder(), label: validationLabel)
}
} else {
if hasEverResignedFirstResponder && !valid {
showLabel(true, label: validationLabel)
hideLabel(true, label: nameLabel)
} else {
showLabel(isFirstResponder(), label: nameLabel)
hideLabel(isFirstResponder(), label: validationLabel)
}
}
}
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
validate()
}
private func showLabel(animated: Bool, label: UILabel) {
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
var f = label.frame
f.origin.y = 3
label.frame = f
label.alpha = 1.0
})
}
private func hideLabel(animated: Bool, label: UILabel) {
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
var f = label.frame
f.origin.y = self.nameLabel.font.lineHeight
label.frame = f
label.alpha = 0.0
})
}
override func textRectForBounds(bounds:CGRect) -> CGRect {
var r = super.textRectForBounds(bounds)
var top = ceil(nameLabel.font.lineHeight)
r = UIEdgeInsetsInsetRect(r, UIEdgeInsetsMake(top + topMargin + marginForContent, 0.0, -marginForContent, 0.0))
return CGRectIntegral(r)
}
override func editingRectForBounds(bounds:CGRect) -> CGRect {
var r = super.editingRectForBounds(bounds)
var top = ceil(nameLabel.font.lineHeight)
r = UIEdgeInsetsInsetRect(r, UIEdgeInsetsMake(top + topMargin + marginForContent, 0.0, -marginForContent, 0.0))
return CGRectIntegral(r)
}
// MARK: Appearance
override func tintColorDidChange() {
super.tintColorDidChange()
nameLabel.textColor = tintColor
}
// MARK: Initialize
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
private func sharedInit() {
nameLabel.alpha = 0
nameLabel.textColor = tintColor
nameLabel.font = nameFont
validationLabel.alpha = 0
validationLabel.textColor = validationColor
validationLabel.font = nameFont
addSubview(nameLabel)
addSubview(validationLabel)
self.clipsToBounds = false
}
}
|
mit
|
9f2bd4635ad7300d6a55adb5c5b4e10a
| 27.106667 | 119 | 0.578273 | 4.942556 | false | false | false | false |
dali-lab/DALI-Framework
|
DALI/Classes/DALILights.swift
|
1
|
8055
|
//
// DALILights.swift
// Pods
//
// Created by John Kotz on 9/17/17.
//
//
import Foundation
import SwiftyJSON
import SocketIO
import FutureKit
/**
A class for controlling the lights in the lab
*/
public class DALILights {
private static var scenesMap: [String:[String]] = [:]
private static var scenesAvgColorMap: [String:[String:String]] = [:]
/**
A group of lights. This is defined as one of the rooms in DALI, each one a grouping of lights that can be controlled
*/
public struct Group {
/// The name of the group
public let name: String
/// The formatted name of the group for printing
public var formattedName: String {
if name == "tvspace" {
return "TV Space"
} else {
return name.lowercased().replacingOccurrences(of: "pod:", with: "").capitalized
}
}
/// The name the currently set scene
public let scene: String?
/// The formated scene name for printing
public var formattedScene: String? {
return scene?.capitalized
}
/// The current color set for the group
public let color: String?
/// An average current color. Used for displaying state via color overlay
public var avgColor: String? {
if let color = color {
return color
}else if let scene = scene {
return DALILights.scenesAvgColorMap[self.name]?[scene]
} else {
return nil
}
}
/// Boolean of current power status
public let isOn: Bool
/// The scenes available for this group
public var scenes: [String] {
if name == "all" {
var allSet: Set<String>?
for entry in scenesMap {
var set = Set<String>()
for scene in entry.value {
set.insert(scene)
}
if allSet != nil {
allSet = allSet!.intersection(set)
} else {
allSet = set
}
}
return Array(allSet!).sorted(by: { (string1, string2) -> Bool in
return string1 == "default" || string1 < string2
})
}else if name == "pods" {
var podsSet: Set<String>?
for entry in scenesMap {
if entry.key.contains("pod") {
var set = Set<String>()
for scene in entry.value {
set.insert(scene)
}
if podsSet != nil {
podsSet = podsSet!.intersection(set)
} else {
podsSet = set
}
}
}
return Array(podsSet!).sorted(by: { (string1, string2) -> Bool in
return string1 == "default" || string1 < string2
})
}
if let scenes = DALILights.scenesMap[name] {
return scenes.sorted(by: { (string1, string2) -> Bool in
return string1 == "default" || string1 < string2
})
} else {
return []
}
}
/// Initialize the group
internal init(name: String, scene: String?, color: String?, isOn: Bool) {
self.name = name
self.scene = scene
self.color = color
self.isOn = isOn
}
/**
Set the scene of the group
- parameter scene: The scene to set the lights to
- parameter callback: Called when done
- parameter success: Was successful
- parameter error: The error, if any, encountered
*/
public func set(scene: String) -> Future<Void> {
return setValue(value: scene)
}
/// Used to set the value of the lights. The API uses strings to idenitify actions to take on the lights
internal func setValue(value: String) -> Future<Void> {
do {
return try ServerCommunicator.post(url: "\(DALIapi.config.serverURL)/api/lights/\(name)", json: JSON(["value":value])).onSuccess(block: { (response) in
if !response.success {
throw response.assertedError
}
})
} catch {
return Future(fail: error)
}
}
/**
Set the color of the group
- parameter color: The color to set the lights
- parameter callback: Called when done
- parameter success: Was successful
- parameter error: The error, if any, encountered
*/
public func set(color: String) -> Future<Void> {
return setValue(value: color)
}
/**
Set the power
- parameter on: Boolean = the power is on
- parameter callback: Called when done
- parameter success: Was successful
- parameter error: The error, if any, encountered
*/
public func set(on: Bool) -> Future<Void> {
return setValue(value: on ? "on" : "off")
}
/// All the groups
public static internal(set) var all = Group(name: "all", scene: nil, color: nil, isOn: false)
/// The pod groups
public static internal(set) var pods = Group(name: "pods", scene: nil, color: nil, isOn: false)
}
internal static var updatingSocket: SocketIOClient!
/**
Observe all the groups
- parameter callback: Called when done
- parameter groups: The updated groups
*/
public static func oberserveAll(callback: @escaping (_ groups: [Group]) -> Void) -> Observation {
if updatingSocket == nil {
updatingSocket = DALIapi.socketManager.socket(forNamespace: "/lights")
updatingSocket.connect()
updatingSocket.on(clientEvent: .connect, callback: { (data, ack) in
guard let updatingSocket = updatingSocket else {
return
}
ServerCommunicator.authenticateSocket(socket: updatingSocket)
})
}
updatingSocket.on("state", callback: { (data, ack) in
guard let dict = data[0] as? [String: Any] else {
return
}
guard let hueDict = dict["hue"] as? [String: Any] else {
return
}
var groups: [Group] = []
var allOn = true
var podsOn = true
var allScene: String?
var noAllScene = false
var allColor: String?
var noAllColor = false
var podsScene: String?
var noPodsScene = false
var podsColor: String?
var noPodsColor = false
for entry in hueDict {
let name = entry.key
if let dict = entry.value as? [String:Any], let isOn = dict["isOn"] as? Bool {
let color = dict["color"] as? String
let scene = dict["scene"] as? String
allOn = allOn && isOn
if name.contains("pod") {
podsOn = isOn
if podsScene == nil {
podsScene = scene
}else if podsScene != scene {
noPodsScene = true
}
if podsColor == nil {
podsColor = color
}else if podsColor != color {
noPodsColor = true
}
}
if allScene == nil {
allScene = scene
}else if allScene != scene {
noAllScene = true
}
if allColor == nil {
allColor = color
}else if allColor != color {
noAllColor = true
}
groups.append(Group(name: name, scene: scene, color: color, isOn: isOn))
}
}
Group.all = Group(name: "all", scene: noAllScene ? nil : allScene, color: noAllColor ? nil : allColor, isOn: allOn)
Group.pods = Group(name: "pods", scene: noPodsScene ? nil : podsScene, color: noPodsColor ? nil : podsColor, isOn: podsOn)
DispatchQueue.main.async {
callback(groups)
}
})
_ = ServerCommunicator.get(url: "\(DALIapi.config.serverURL)/api/lights/scenes").onSuccess { (response) in
guard let dict = response.json?.dictionary else {
return
}
var map = [String:[String]]()
var colorMap = [String:[String:String]]()
for entry in dict {
colorMap[entry.key] = [:]
if let value = entry.value.array {
var array: [String] = []
for scene in value {
if let sceneDict = scene.dictionary, let scene = sceneDict["name"]?.string {
array.append(scene)
colorMap[entry.key]![scene] = sceneDict["averageColor"]?.string
}
}
map[entry.key] = array
}
}
DALILights.scenesAvgColorMap = colorMap
DALILights.scenesMap = map
}
return Observation(stop: {
updatingSocket.disconnect()
updatingSocket = nil
}, id: "lights")
}
}
|
mit
|
0420deea41817a846808b381a0919336
| 26.585616 | 167 | 0.590317 | 3.673051 | false | false | false | false |
the-grid/Portal
|
PortalTests/Networking/Resources/Item/CreateItemSpec.swift
|
1
|
1499
|
import Mockingjay
import MockingjayMatchers
import Nimble
import Portal
import Quick
import Result
class CreateItemSpec: QuickSpec {
override func spec() {
describe("creating an item") {
it("should result in Success") {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses = [MockingjayProtocol.self] as [AnyClass] + configuration.protocolClasses!
let token = "token"
let client = APIClient(token: token, configuration: configuration)
let matcher = api(.POST, "https://api.thegrid.io/item", token: token, body: itemResponseBody)
let builder = http(201)
self.stub(matcher, builder: builder)
let error = NSError(domain: "io.thegrid.PortalTests", code: 0, userInfo: [ NSLocalizedDescriptionKey: "Unexpected request." ])
self.stub(everything, builder: failure(error))
var responseValue: Void?
var responseError: NSError?
client.createItem(itemModel) { result in
responseValue = result.value
responseError = result.error
}
expect(responseValue).toEventually(beVoid())
expect(responseError).toEventually(beNil())
}
}
}
}
|
mit
|
257ead636923b4e96225868dd6db6a98
| 38.447368 | 142 | 0.562375 | 5.832685 | false | true | false | false |
arkye-8th-semester-indiana-tech/dev_mob_apps
|
lessons/4_text_input_and_delegation/WorldTrotter/ConversionViewController.swift
|
1
|
2488
|
//
// ConversionViewController.swift
// WorldTrotter
//
// Created by Maia de Moraes, Jonathan H - 01 on 2/10/16.
// Copyright © 2016 Big Nerd Ranch. All rights reserved.
//
import UIKit
class ConversionViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var celsiusLabel: UILabel!
var fahrenheitValue: Double? {
didSet {
updateCelsiusLabel()
}
}
var celsiusValue: Double? {
if let value = fahrenheitValue {
return (value - 32) * (5/9)
}
else {
return nil
}
}
let numberFormatter: NSNumberFormatter = {
let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
func updateCelsiusLabel() {
if let value = celsiusValue {
celsiusLabel.text = numberFormatter.stringFromNumber(value)
}
else {
celsiusLabel.text = "???"
}
}
@IBOutlet var textField: UITextField!
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool {
var isTextFieldAccepted = false
let existingTextHasDecimalSeparator = textField.text?.rangeOfString(".")
let replacementTextHasDecimalSeparator = string.rangeOfString(".")
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
isTextFieldAccepted = false
}
else {
let replacementTextHasAlphabeticCharacter = string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())
if replacementTextHasAlphabeticCharacter != nil {
isTextFieldAccepted = false
}
else {
isTextFieldAccepted = true
}
}
return isTextFieldAccepted
}
@IBAction func fahrenheitFieldEditingChanged(textField: UITextField) {
if let text = textField.text, value = Double(text) {
fahrenheitValue = value
}
else {
fahrenheitValue = nil
}
}
@IBAction func dismissKeyboard(sender: AnyObject) {
textField.resignFirstResponder()
}
}
|
gpl-3.0
|
4860df4a1b56f04a801a89769914da0a
| 26.955056 | 127 | 0.568959 | 5.824356 | false | false | false | false |
jovito-royeca/Decktracker
|
osx/DataSource/DataSource/ObjectManager.swift
|
1
|
11512
|
//
// ObjectManager.swift
// WTHRM8
//
// Created by Jovit Royeca on 18/04/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import CoreData
class ObjectManager: NSObject {
// MARK: Constants
static let BatchUpdateNotification = "BatchUpdateNotification"
// MARK: Variables
private var privateContext: NSManagedObjectContext {
return CoreDataManager.sharedInstance.privateContext
}
private var mainObjectContext: NSManagedObjectContext {
return CoreDataManager.sharedInstance.mainObjectContext
}
// Mark: Finder methods
func findOrCreateColor(dict: [String: AnyObject]) -> Color {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Color in
return Color(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Color", objectFinder: ["name": dict[Color.Keys.Name]!], initializer: initializer) as! Color
}
func findOrCreateSet(dict: [String: AnyObject]) -> Set {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Set in
return Set(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Set", objectFinder: ["name": dict[Set.Keys.Name]!], initializer: initializer) as! Set
}
func findOrCreateBlock(dict: [String: AnyObject]) -> Block {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Block in
return Block(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Block", objectFinder: ["name": dict[Block.Keys.Name]!], initializer: initializer) as! Block
}
func findOrCreateSetType(dict: [String: AnyObject]) -> SetType {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> SetType in
return SetType(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "SetType", objectFinder: ["name": dict[SetType.Keys.Name]!], initializer: initializer) as! SetType
}
func findOrCreateBorder(dict: [String: AnyObject]) -> Border {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Border in
return Border(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Border", objectFinder: ["name": dict[Border.Keys.Name]!], initializer: initializer) as! Border
}
func findOrCreateCard(dict: [String: AnyObject]) -> Card {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Card in
return Card(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Card", objectFinder: ["cardID": dict[Card.Keys.CardID]!], initializer: initializer) as! Card
}
func findOrCreateLayout(dict: [String: AnyObject]) -> Layout {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Layout in
return Layout(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Layout", objectFinder: ["name": dict[Layout.Keys.Name]!], initializer: initializer) as! Layout
}
func findOrCreateCardType(dict: [String: AnyObject]) -> CardType {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> CardType in
return CardType(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "CardType", objectFinder: ["name": dict[CardType.Keys.Name]!], initializer: initializer) as! CardType
}
func findOrCreateRarity(dict: [String: AnyObject]) -> Rarity {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Rarity in
return Rarity(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Rarity", objectFinder: ["name": dict[Rarity.Keys.Name]!], initializer: initializer) as! Rarity
}
func findOrCreateArtist(dict: [String: AnyObject]) -> Artist {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Artist in
return Artist(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Artist", objectFinder: ["name": dict[Artist.Keys.Name]!], initializer: initializer) as! Artist
}
func findOrCreateWatermark(dict: [String: AnyObject]) -> Watermark {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Watermark in
return Watermark(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Watermark", objectFinder: ["name": dict[Watermark.Keys.Name]!], initializer: initializer) as! Watermark
}
func findOrCreateSource(dict: [String: AnyObject]) -> Source {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Source in
return Source(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Source", objectFinder: ["name": dict[Source.Keys.Name]!], initializer: initializer) as! Source
}
func findOrCreateFormat(dict: [String: AnyObject]) -> Format {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Format in
return Format(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Format", objectFinder: ["name": dict[Format.Keys.Name]!], initializer: initializer) as! Format
}
func findOrCreateLegality(dict: [String: AnyObject]) -> Legality {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Legality in
return Legality(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Legality", objectFinder: ["name": dict[Legality.Keys.Name]!], initializer: initializer) as! Legality
}
func findOrCreateRuling(card: Card, dict: [String: AnyObject]) -> Ruling {
let ruling = Ruling(dictionary: dict, context: privateContext)
ruling.card = card
CoreDataManager.sharedInstance.savePrivateContext()
return ruling
}
func findOrCreateCardLegality(card: Card, dict: [String: AnyObject]) -> CardLegality {
let cardLegality = CardLegality(context: privateContext)
cardLegality.card = card
cardLegality.format = findOrCreateFormat(dict)
cardLegality.legality = findOrCreateLegality(dict)
return cardLegality
}
func findOrCreateLanguage(dict: [String: AnyObject]) -> Language {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> Language in
return Language(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "Language", objectFinder: ["name": dict[Language.Keys.Name]!], initializer: initializer) as! Language
}
func findOrCreateForeignName(card: Card, dict: [String: AnyObject]) -> ForeignName {
let cardForeignName = ForeignName(dictionary: dict, context: privateContext)
cardForeignName.card = card
cardForeignName.language = findOrCreateLanguage(dict)
return cardForeignName
}
func findOrCreateTCGPlayerPricing(card: Card, dict: [String: AnyObject]) -> TCGPlayerPricing {
let initializer = { (dict: [String: AnyObject], context: NSManagedObjectContext) -> TCGPlayerPricing in
return TCGPlayerPricing(dictionary: dict, context: context)
}
return findOrCreateObject(dict, entityName: "TCGPlayerPricing", objectFinder: ["card.cardID": card.cardID!], initializer: initializer) as! TCGPlayerPricing
}
// MARK: Core methods
func findOrCreateObject(dict: [String: AnyObject], entityName: String, objectFinder: [String: AnyObject], initializer: (dict: [String: AnyObject], context: NSManagedObjectContext) -> AnyObject) -> AnyObject {
var object:AnyObject?
var predicate:NSPredicate?
for (key,value) in objectFinder {
if predicate != nil {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate!, NSPredicate(format: "%K == %@", key, value as! NSObject)])
} else {
predicate = NSPredicate(format: "%K == %@", key, value as! NSObject)
}
}
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicate
do {
if let m = try privateContext.executeFetchRequest(fetchRequest).first {
object = m
} else {
object = initializer(dict: dict, context: privateContext)
CoreDataManager.sharedInstance.savePrivateContext()
}
} catch let error as NSError {
print("Error in fetch \(error), \(error.userInfo)")
}
return object!
}
func findObjects(entityName: String, predicate: NSPredicate?, sorters: [NSSortDescriptor]) -> [AnyObject] {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sorters
var objects:[AnyObject]?
do {
objects = try privateContext.executeFetchRequest(fetchRequest)
} catch let error as NSError {
print("Error in fetch \(error), \(error.userInfo)")
}
return objects!
}
func fetchObjects(fetchRequest: NSFetchRequest) -> [AnyObject] {
var objects:[AnyObject]?
do {
objects = try privateContext.executeFetchRequest(fetchRequest)
} catch let error as NSError {
print("Error in fetch \(error), \(error.userInfo)")
}
return objects!
}
func deleteObjects(entityName: String, objectFinder: [String: AnyObject]) {
var predicate:NSPredicate?
for (key,value) in objectFinder {
if predicate != nil {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate!, NSPredicate(format: "%K == %@", key, value as! NSObject)])
} else {
predicate = NSPredicate(format: "%K == %@", key, value as! NSObject)
}
}
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicate
do {
if let m = try privateContext.executeFetchRequest(fetchRequest).first as? NSManagedObject {
privateContext.deleteObject(m)
CoreDataManager.sharedInstance.savePrivateContext()
}
} catch let error as NSError {
print("Error in fetch \(error), \(error.userInfo)")
}
}
// MARK: - Shared Instance
static let sharedInstance = ObjectManager()
}
|
apache-2.0
|
37efff8faeed2847fc9007a6da063133
| 41.791822 | 212 | 0.63157 | 5.017873 | false | false | false | false |
nohirap/ANActionSheet
|
ANActionSheet/Classes/ANHeaderView.swift
|
1
|
1886
|
//
// ANHeaderView.swift
// Pods
//
// Created by nohirap on 2016/06/09.
// Copyright © 2016 nohirap. All rights reserved.
//
import UIKit
internal final class ANHeaderView: UIView {
private let titleHeight: CGFloat = 40.0
private let messageHeight: CGFloat = 60.0
var height: CGFloat = 0.0
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(model: ANHeaderViewModel) {
super.init(frame: CGRectZero)
setupHeaderView(model)
}
private func setupHeaderView(model: ANHeaderViewModel) {
if !model.title.isEmpty {
let titleLabel = ANLabel()
titleLabel.type = .Title
titleLabel.color = model.titleColor
titleLabel.text = model.title
titleLabel.frame = CGRectMake(0, 0, UIScreen.buttonWidth(), titleHeight)
height += titleHeight
self.addSubview(titleLabel)
}
if !model.message.isEmpty {
let messageLabel = ANLabel()
messageLabel.type = .Message
messageLabel.color = model.messageColor
messageLabel.text = model.message
messageLabel.frame = CGRectMake(0, height, UIScreen.buttonWidth(), messageHeight)
height += messageHeight
self.addSubview(messageLabel)
}
if height > 0 {
self.frame = CGRectMake(UIScreen.mergin(), 0, UIScreen.buttonWidth(), height)
let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight], cornerRadii:CGSizeMake(6.0, 6.0))
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
self.layer.mask = maskLayer
self.backgroundColor = model.headerBackgroundColor
}
}
}
|
mit
|
6d44f2b1756d645ed8793c2a3f0a9095
| 33.272727 | 165 | 0.623342 | 4.858247 | false | false | false | false |
SwiftAndroid/swift
|
validation-test/IDE/complete_from_cocoa_2.swift
|
5
|
1611
|
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=T1 | FileCheck %s -check-prefix=T1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=T2 | FileCheck %s -check-prefix=T2
// REQUIRES: objc_interop
// FIXME: iOS has no Cocoa.framework
// REQUIRES: OS=macosx
// A smoketest for code completion in Cocoa.
import Cocoa
func testQualifiedWithDot() {
Cocoa.#^T1^#
// T1: Begin completions
// T1-DAG: Decl[FreeFunction]/OtherModule[CoreFoundation.CFArray]: CFArrayCreate({#(allocator): CFAllocator!#}, {#(values): UnsafeMutablePointer<UnsafePointer<Void>?>!#}, {#(numValues): CFIndex#}, {#(callBacks): UnsafePointer<CFArrayCallBacks>!#})[#CFArray!#]{{; name=.+$}}
// T1-DAG: Decl[FreeFunction]/OtherModule[CoreFoundation.CFArray]: CFArrayGetCount({#(theArray): CFArray!#})[#CFIndex#]{{; name=.+$}}
// T1-DAG: Decl[Class]/OtherModule[ObjectiveC.NSObject]: NSObject[#NSObject#]{{; name=.+$}}
// T1: End completions
}
func testQualifiedWithoutDot() {
Cocoa#^T2^#
// T2: Begin completions
// T2-DAG: Decl[FreeFunction]/OtherModule[CoreFoundation.CFArray]: .CFArrayCreate({#(allocator): CFAllocator!#}, {#(values): UnsafeMutablePointer<UnsafePointer<Void>?>!#}, {#(numValues): CFIndex#}, {#(callBacks): UnsafePointer<CFArrayCallBacks>!#})[#CFArray!#]{{; name=.+$}}
// T2-DAG: Decl[FreeFunction]/OtherModule[CoreFoundation.CFArray]: .CFArrayGetCount({#(theArray): CFArray!#})[#CFIndex#]{{; name=.+$}}
// T2-DAG: Decl[Class]/OtherModule[ObjectiveC.NSObject]: .NSObject[#NSObject#]{{; name=.+$}}
// T2: End completions
}
|
apache-2.0
|
0e2de6ac2847587446a7f6e24d12ccc1
| 54.551724 | 274 | 0.701428 | 3.872596 | false | true | false | false |
ledwards/ios-twitter
|
Twit/NSDate+TimeAgoInWords.swift
|
2
|
5086
|
//
// NSDate+TimeAgoInWords.swift
//
// A Swift port of Rails' time_ago_in_words.
// Created by Ed McManus for Yardsale on 9/30/14.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension NSDate {
class func distanceOfTimeInWords(fromDate:NSDate, toDate:NSDate) -> String {
let MINUTE_IN_SECONDS = 60.0
let HOUR_IN_SECONDS = MINUTE_IN_SECONDS * 60.0
let DAY_IN_SECONDS = HOUR_IN_SECONDS * 24.0
let MONTH_IN_SECONDS = DAY_IN_SECONDS * 30.0
let YEAR_IN_SECONDS = DAY_IN_SECONDS * 365.0
let deltaSeconds = abs(toDate.timeIntervalSinceDate(fromDate))
var timeAgo = ""
switch deltaSeconds {
// 0 <-> 29 secs # => less than a minute
case 0..<30:
timeAgo = "now"
// 30 secs ..< 1 min, 30 secs # => 1 minute
case 30..<90:
timeAgo = "1 min"
// 1 min, 30 secs ..< 44 mins, 30 secs # => [2..44] minutes
case 90..<(44 * MINUTE_IN_SECONDS + 30):
let minutes = Int(round(deltaSeconds / MINUTE_IN_SECONDS))
timeAgo = "\(minutes) min"
// 44 mins, 30 secs ..< 89 mins, 30 secs # => about 1 hour
case (44 * MINUTE_IN_SECONDS + 30)..<(89 * MINUTE_IN_SECONDS + 30):
timeAgo = "1 hr"
// 89 mins, 30 secs ..< 23 hrs, 59 mins, 30 secs # => about [2..24] hours
case (89 * MINUTE_IN_SECONDS + 30)..<(23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30):
let hours = Int(round(deltaSeconds / HOUR_IN_SECONDS))
timeAgo = "\(hours) hrs"
// 23 hrs, 59 mins, 30 secs ..< 41 hrs, 59 mins, 30 secs # => 1 day
case (23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30)..<(41 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30):
timeAgo = "1 day"
// 41 hrs, 59 mins, 30 secs ..< 29 days, 23 hrs, 59 mins, 30 secs # => [2..29] days
case (41 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30)..<(29 * DAY_IN_SECONDS + 23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30):
let days = Int(round(deltaSeconds / DAY_IN_SECONDS))
timeAgo = "\(days) days"
// 29 days, 23 hrs, 59 mins, 30 secs ..< 44 days, 23 hrs, 59 mins, 30 secs # => about 1 month
case (29 * DAY_IN_SECONDS + 23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30)..<(44 * DAY_IN_SECONDS + 23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30):
timeAgo = "1 month"
// 44 days, 23 hrs, 59 mins, 30 secs ..< 59 days, 23 hrs, 59 mins, 30 secs # => about 2 months
case (44 * DAY_IN_SECONDS + 23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30)..<(59 * DAY_IN_SECONDS + 23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30):
timeAgo = "2 months"
// 59 days, 23 hrs, 59 mins, 30 secs ..< 1 yr # => [2..12] months
case (59 * DAY_IN_SECONDS + 23 * HOUR_IN_SECONDS + 59 * MINUTE_IN_SECONDS + 30)..<(1 * YEAR_IN_SECONDS):
let months = Int(round(deltaSeconds / MONTH_IN_SECONDS))
timeAgo = "\(months) months"
// 1 yr ..< 1 yr, 3 months # => about 1 year
case (1 * YEAR_IN_SECONDS)..<(1 * YEAR_IN_SECONDS + 3 * MONTH_IN_SECONDS):
timeAgo = "1 year"
// 1 yr, 3 months ..< 1 yr, 9 months # => over 1 year
case (1 * YEAR_IN_SECONDS + 3 * MONTH_IN_SECONDS)..<(1 * YEAR_IN_SECONDS + 9 * MONTH_IN_SECONDS):
timeAgo = "over 1 year"
// 1 yr, 9 months ..< 2 yr minus # => almost 2 years
case (1 * YEAR_IN_SECONDS + 9 * MONTH_IN_SECONDS)..<(2 * YEAR_IN_SECONDS):
timeAgo = "2 years"
// 2 yrs <-> max time or date # => (same rules as 1 yr)
default:
let years = Int(round(deltaSeconds / YEAR_IN_SECONDS))
timeAgo = "\(years) years"
}
return timeAgo
}
func timeAgoInWords() -> String {
return NSDate.distanceOfTimeInWords(self, toDate: NSDate())
}
}
|
mit
|
5d8b280112135ae91968e0e9584c8c29
| 50.373737 | 165 | 0.492135 | 3.882443 | false | false | false | false |
edmw/Volumio_ios
|
Volumio/BrowseSearchTableViewController.swift
|
1
|
9448
|
//
// BrowseSearchTableViewController.swift
// Volumio
//
// Created by Federico Sintucci on 22/10/16.
// Copyright © 2016 Federico Sintucci. All rights reserved.
//
import UIKit
class BrowseSearchTableViewController: BrowseTableViewController, UISearchBarDelegate {
@IBOutlet weak fileprivate var searchBar: UISearchBar!
var sourcesList: [SearchResultObject] = []
// MARK: - View Callbacks
override func viewDidLoad() {
super.viewDidLoad()
localize()
tableView.tableFooterView = UIView(frame: CGRect.zero)
searchBar.delegate = self
refreshControl?.addTarget(self,
action: #selector(handleRefresh),
for: UIControlEvents.valueChanged
)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerObserver(forName: .browseSearch) { (notification) in
self.clearAllNotice()
guard let sources = notification.object as? [SearchResultObject]
else { return }
self.update(sources: sources)
}
registerObserver(forName: .addedToPlaylist) { (notification) in
guard let object = notification.object
else { return }
self.notice(playlistAdded: object)
}
}
override func viewDidAppear(_ animated: Bool) {
if !VolumioIOManager.shared.isConnected && !VolumioIOManager.shared.isConnecting {
_ = navigationController?.popToRootViewController(animated: animated)
}
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
clearAllNotice()
NotificationCenter.default.removeObserver(self)
}
// MARK: - View Updates
func update(sources: [SearchResultObject]? = nil) {
if let sources = sources {
sourcesList = sources
}
tableView.reloadData()
}
func notice(playlistAdded item: Any, delayed time: Double? = nil) {
notice(localizedAddedItemToPlaylistNotice(name: String(describing: item)), delayed: time)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return sourcesList.count
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
let sections = sourcesList[section]
if let items = sections.items {
return items.count
}
return 0
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let itemList = sourcesList[indexPath.section]
let item = itemList.items![indexPath.row] as LibraryObject
switch item.type {
case _ where item.type.isTrack:
return self.tableView(tableView, cellForTrack: item, forRowAt: indexPath)
case _ where item.type.isSong:
return self.tableView(tableView, cellForTrack: item, forRowAt: indexPath)
case _ where item.type.isRadio:
return self.tableView(tableView, cellForRadio: item, forRowAt: indexPath)
default:
return self.tableView(tableView, cellForFolder: item, forRowAt: indexPath)
}
}
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int
) -> String? {
return sourcesList[section].title
}
override func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath
) {
}
override func tableView(_ tableView: UITableView,
editActionsForRowAt indexPath: IndexPath
) -> [UITableViewRowAction]? {
let itemList = sourcesList[indexPath.section]
let item = itemList.items![indexPath.row] as LibraryObject
let play = UITableViewRowAction(style: .normal, title: localizedPlayTitle) { _ in
guard let uri = item.uri, let title = item.title, let service = item.service
else { return }
VolumioIOManager.shared.addAndPlay(uri: uri, title: title, service: service)
tableView.setEditing(false, animated: true)
}
play.backgroundColor = UIColor.playButtonBackground
let more = UITableViewRowAction(style: .normal, title: localizedMoreTitle) { _ in
self.playlistActions(item: item)
tableView.setEditing(false, animated: true)
}
more.backgroundColor = UIColor.moreButtonBackground
return [more, play]
}
override func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath
) -> CGFloat {
return 54.0
}
func handleRefresh(refreshControl: UIRefreshControl) {
if let text = searchBar.text {
VolumioIOManager.shared.browseSearch(text: text)
}
refreshControl.endRefreshing()
}
func playlistActions(item: LibraryObject) {
guard let itemUri = item.uri,
let itemTitle = item.title,
let itemService = item.service
else { return }
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(
UIAlertAction(title: localizedPlayTitle, style: .default) { _ in
VolumioIOManager.shared.addAndPlay(
uri: itemUri,
title: itemTitle,
service: itemService
)
})
alert.addAction(
UIAlertAction(title: localizedAddToQueueTitle, style: .default) { _ in
VolumioIOManager.shared.addToQueue(
uri: itemUri,
title: itemTitle,
service: itemService
)
})
alert.addAction(
UIAlertAction(title: localizedClearAndPlayTitle, style: .default) { _ in
VolumioIOManager.shared.clearAndPlay(
uri: itemUri,
title: itemTitle,
service: itemService
)
})
alert.addAction(UIAlertAction(title: localizedCancelTitle, style: .cancel))
present(alert, animated: true, completion: nil)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.pleaseWait()
VolumioIOManager.shared.browseSearch(text: searchBar.text!)
searchBar.resignFirstResponder()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "browseFolder" {
guard let destinationController = segue.destination as? BrowseFolderTableViewController
else { fatalError() }
guard let indexPath = tableView.indexPathForSelectedRow else { return }
let itemList = sourcesList[indexPath.section]
let items = itemList.items
if let items = items {
let item = items[indexPath.row] as LibraryObject
switch item.type {
case .folder:
destinationController.serviceType = .folder
case .playlist:
destinationController.serviceType = .playlist
default:
destinationController.serviceType = .generic
}
destinationController.serviceName = item.title
destinationController.serviceUri = item.uri
destinationController.serviceService = item.service
}
}
}
}
// MARK: - Localization
extension BrowseSearchTableViewController {
fileprivate func localize() {
navigationItem.title = NSLocalizedString("BROWSE_SEARCH",
comment: "browse search view title"
)
}
fileprivate var localizedMoreTitle: String {
return NSLocalizedString("MORE", comment: "[trigger] more actions")
}
fileprivate var localizedCancelTitle: String {
return NSLocalizedString("CANCEL", comment: "[trigger] cancel action")
}
fileprivate var localizedPlayTitle: String {
return NSLocalizedString("PLAY", comment: "[trigger] play anything")
}
fileprivate var localizedAddAndPlayTitle: String {
return NSLocalizedString("BROWSE_ADD_TO_QUEUE_AND_PLAY",
comment: "[trigger] add item to queue and start playing"
)
}
fileprivate var localizedAddToQueueTitle: String {
return NSLocalizedString("BROWSE_ADD_TO_QUEUE",
comment: "[trigger] add item to queue"
)
}
fileprivate var localizedClearAndPlayTitle: String {
return NSLocalizedString("BROWSE_CLEAR_AND_ADD_TO_QUEUE_AND_PLAY",
comment: "[trigger] clear queue, add item and start playing"
)
}
fileprivate func localizedAddedItemToPlaylistNotice(name: String) -> String {
return String.localizedStringWithFormat(
localizedAddedItemToPlaylistNotice,
name
)
}
fileprivate var localizedAddedItemToPlaylistNotice: String {
return NSLocalizedString("PLAYLIST_ADDED_ITEM",
comment: "[hint](format) added item(%@) to playlist"
)
}
}
|
gpl-3.0
|
9b6535c9098fddb41375c0c96997d43c
| 31.463918 | 99 | 0.618186 | 5.199229 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Controller/UI/Product/views/SLVProductPhotoViewerCell.swift
|
1
|
1803
|
//
// SLVProductPhotoViewerCell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 9..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
class SLVProductPhotoViewerCell: UICollectionViewCell {
@IBOutlet weak var photo: GesutreImageView! {
didSet {
photo.isPinch = true
photo.isPan = false
photo.isTap = false
photo.delegate = self
}
}
var path: IndexPath?
override open func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
}
public static func photoFrame() -> CGRect {
let bounds = UIScreen.main.bounds
let viewWidth = bounds.size.width
let viewHeight = bounds.size.height
let cellWidth = viewWidth * 0.688
let cellHeight = viewHeight * 0.691
let padding_y = (viewHeight - cellHeight)/2
let padding_x = (viewWidth - cellWidth)/2
let rect = CGRect(x: padding_x, y: padding_y, width: cellWidth, height: cellHeight)
return rect
}
func binding(path: IndexPath) {
self.path = path
}
}
extension SLVProductPhotoViewerCell: GesutreImageViewProtocol {
func didReceivePinchForScale(view:GesutreImageView, scale: CGFloat, state: UIGestureRecognizerState) {
if state == .ended {
} else {//change..
}
}
func didReceivePanFrame(view:GesutreImageView, frame: CGRect) {}
func didReceiveTap(view:GesutreImageView, point: CGPoint, state: UIGestureRecognizerState) {}
func didReceiveLong(view:GesutreImageView, point: CGPoint, state: UIGestureRecognizerState) {}
func didReceiveScroll(view:GesutreImageView, x: CGFloat, y: CGFloat) {}
}
|
mit
|
9b52154e3162e1dd124fb0caa31fa655
| 28.409836 | 106 | 0.645485 | 4.333333 | false | false | false | false |
FienMaandag/spick-and-span
|
spick_and_span/spick_and_span/RoomViewController.swift
|
1
|
9031
|
//
// RoomViewController.swift
// spick_and_span
//
// Created by Fien Maandag on 07-06-17.
// Copyright © 2017 Fien Maandag. All rights reserved.
//
import UIKit
import Firebase
class RoomViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var houseKey = String()
var roomName = String()
var priorityLevel = Int()
var tasks :[Tasks] = []
var ref = Database.database().reference()
let currentUser = Auth.auth().currentUser
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = self.roomName
// Lookup housekey for current user
ref.child("users").child((currentUser?.uid)!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
self.houseKey = value?["houseKey"] as? String ?? ""
self.ref = Database.database().reference().child("houses/\(self.houseKey)")
self.loadTasks()
}) { (error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Set amount rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
// Fill cells of tableview with tasks
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "TasksCell", for: indexPath as IndexPath) as! TaskTableViewCell
// Check if task is already done and set priority level accordingly
if tasks[indexPath.row].taskDone != ""{
calculatePriority(row: indexPath.row)
} else {
self.priorityLevel = 100
}
// Set color for priority level that has been caculated
if 0 ... 25 ~= self.priorityLevel{
cell.priorityTaskLabel.text = "LOW"
cell.priorityTaskLabel.textColor = UIColor.green
}
else if 25 ... 75 ~= self.priorityLevel{
cell.priorityTaskLabel.text = "MEDIUM"
cell.priorityTaskLabel.textColor = UIColor.orange
}
else if 75 ... 100 ~= self.priorityLevel{
cell.priorityTaskLabel.text = "HIGH"
cell.priorityTaskLabel.textColor = UIColor.red
}
else {
cell.priorityTaskLabel.text = "NOW"
cell.priorityTaskLabel.textColor = UIColor.red
}
cell.taskNameLabel.text = tasks[indexPath.row].taskName.uppercased()
return cell
}
// Calculate priority level by comparing date done ande current date
func calculatePriority(row: Int){
let lastDone = tasks[row].taskDone
let lastDoneDouble = TimeInterval(lastDone)
let lastDoneDate = Date(timeIntervalSince1970: lastDoneDouble!)
let currentData = Date()
let sinceDone = DateInterval(start: lastDoneDate, end: currentData).duration
let frequency = tasks[row].taskFrequency
var priority = (Float(sinceDone) / Float(frequency)) * 100
if frequency == 0 {
priority = 0
}
self.priorityLevel = Int(priority)
}
// Load tasks from Firebase
func loadTasks(){
let searchRef = ref.child("rooms/\(roomName)/tasks")
searchRef.observe(.value, with: { snapshot in
var newTasks: [Tasks] = []
for item in snapshot.children {
let task = Tasks(snapshot: item as! DataSnapshot)
newTasks.append(task)
}
self.tasks = newTasks
self.tableView.reloadData()
})
}
// done button
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let done = UITableViewRowAction(style: .normal, title: "Done") { action, index in
// Save variables
let indexPath = editActionsForRowAt
let selectedTask = self.tasks[indexPath.row].taskName
let taskPoints = self.tasks[indexPath.row].taskPoints
let userID = self.currentUser?.uid
let userEmail = self.currentUser?.email
// Save current data as string
let date = Date()
let today = date.timeIntervalSince1970
let stringToday = String(today)
// Name for child
var todayChild = stringToday.components(separatedBy: ".")
// Update history
let historyRef = self.ref.child("history/\(todayChild[0])")
let newHistory = History(
doneBy: userEmail!,
task: selectedTask,
time: stringToday)
historyRef.setValue(newHistory.toAnyObject())
// Update priority task done
let taskRef = self.ref.child("rooms/\(self.roomName)/tasks/\(selectedTask)/taskDone")
taskRef.setValue(stringToday)
// Update total points
let usersRef = self.ref.child("users")
usersRef.child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let points = value?["totalPoints"] as? Int ?? 0
let newTotal = taskPoints + points
usersRef.child("\(userID!)/totalPoints").setValue(newTotal)
}) { (error) in
print(error.localizedDescription)
}
// Congratulate user with points
self.simpleAlert(title: "Points", message: "You've earned \(taskPoints) points!", actionTitle: "Jeeh!")
}
done.backgroundColor = .green
return [done]
}
// Add a new task
@IBAction func addTaskButtonClicked(_ sender: UIBarButtonItem) {
// Open alert to create new task
let alert = UIAlertController(title: "New Task",
message: "Configure a new task",
preferredStyle: .alert)
// Save room for house
let saveAction = UIAlertAction(title: "Save", style: .default) { action in
guard let taskNameField = alert.textFields![0].text, !taskNameField.isEmpty else{
self.simpleAlert(title: "No Input", message: "Please enter a task Name", actionTitle: "ok")
return
}
// Check for user input
guard let taskFrequencyField = alert.textFields![1].text, !taskFrequencyField.isEmpty else{
self.simpleAlert(title: "No Input", message: "Please enter a task frequency", actionTitle: "ok")
return
}
guard let taskPointsField = alert.textFields![2].text, !taskPointsField.isEmpty else{
self.simpleAlert(title: "No Input", message: "Please enter the task points", actionTitle: "ok")
return
}
// Save name, frequency and points
let taskName = taskNameField.capitalized
let taskFrequency = Int(taskFrequencyField)! * 86400
let taskPoints = Int(taskPointsField)
let roomRef = self.ref.child("rooms/\(self.roomName)/tasks/\(String(describing: taskName))")
// add room to firebase
let newTask = Tasks(taskDone: "",
taskFrequency: taskFrequency,
taskName: taskName,
taskPoints: taskPoints!)
roomRef.setValue(newTask.toAnyObject())
}
// Closes alert
let cancelAction = UIAlertAction(title: "Cancel",
style: .default)
alert.addTextField { taskName in
taskName.placeholder = "Task Name"
}
alert.addTextField { taskFrequency in
taskFrequency.placeholder = "Once Every .. Days"
taskFrequency.keyboardType = .numberPad
}
alert.addTextField { taskPoints in
taskPoints.placeholder = "Task Points"
taskPoints.keyboardType = .numberPad
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
}
|
mit
|
eb0e196a509b638d97e8f46dc2901779
| 35.26506 | 133 | 0.560908 | 5.23175 | false | false | false | false |
esttorhe/RxSwift
|
RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaSearchResult.swift
|
1
|
2019
|
//
// WikipediaSearchResult.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
struct WikipediaSearchResult: CustomStringConvertible {
let title: String
let description: String
let URL: NSURL
init(title: String, description: String, URL: NSURL) {
self.title = title
self.description = description
self.URL = URL
}
// tedious parsing part
static func parseJSON(json: [AnyObject]) -> RxResult<[WikipediaSearchResult]> {
let rootArrayTyped = json.map { $0 as? [AnyObject] }
.filter { $0 != nil }
.map { $0! }
if rootArrayTyped.count != 3 {
return failure(WikipediaParseError)
}
let titleAndDescription = Array(Zip2(rootArrayTyped[0], rootArrayTyped[1]))
let titleDescriptionAndUrl: [((AnyObject, AnyObject), AnyObject)] = Array(Zip2(titleAndDescription, rootArrayTyped[2]))
let searchResults: [RxResult<WikipediaSearchResult>] = titleDescriptionAndUrl.map ( { result -> RxResult<WikipediaSearchResult> in
let (first, url) = result
let (title, description) = first
let titleString = title as? String,
descriptionString = description as? String,
urlString = url as? String
if titleString == nil || descriptionString == nil || urlString == nil {
return failure(WikipediaParseError)
}
let URL = NSURL(string: urlString!)
if URL == nil {
return failure(WikipediaParseError)
}
return success(WikipediaSearchResult(title: titleString!, description: descriptionString!, URL: URL!))
})
let values = (searchResults.filter { $0.isSuccess }).map { $0.get() }
return success(values)
}
}
|
mit
|
3701ce59fac419bf682ac02d355b44c5
| 32.65 | 138 | 0.58742 | 4.912409 | false | false | false | false |
mkrisztian95/iOS
|
Tardis/ScheduleViewController.swift
|
1
|
4640
|
//
// ScheduleViewController.swift
// Tardis
//
// Created by Molnar Kristian on 7/25/16.
// Copyright © 2016 Molnar Kristian. All rights reserved.
//
import UIKit
class ScheduleViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var table1 = FirstDayTableViewController()
var table2 = SecondDayTableViewController()
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
var pageImages: [UIImage] = []
var pageViews: [UIImageView?] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrollViewDidScroll(scrollView: UIScrollView!) {
// Load the pages that are now on screen
// let point = CGPointMake(scrollView.contentOffset.x, 0)
// scrollView.setContentOffset(point, animated: false)
loadVisiblePages()
}
override func viewDidAppear(animated: Bool) {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
if appDelegate.table2 != nil {
table2 = appDelegate.table2
} else {
appDelegate.table2 = mainStoryboard.instantiateViewControllerWithIdentifier("SecondDayTableViewController") as! SecondDayTableViewController
table2 = appDelegate.table2
}
if appDelegate.table1 != nil {
table1 = appDelegate.table1
} else {
appDelegate.table1 = mainStoryboard.instantiateViewControllerWithIdentifier("FirstDayTableViewController") as! FirstDayTableViewController
table1 = appDelegate.table1
}
self.setUpFrames()
self.addChildViewController(table1)
self.addChildViewController(table2)
table1.didMoveToParentViewController(self)
table2.didMoveToParentViewController(self)
scrollView.addSubview(table1.tableView)
scrollView.addSubview(table2.tableView)
loadVisiblePages()
scrollView.setContentOffset(CGPointMake(0, 0), animated: false)
}
func setUpFrames() {
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height - 88)
var firstFrame:CGRect = table1.tableView.frame
firstFrame.origin.x = 0
firstFrame.origin.y = 0
firstFrame.size.width = self.scrollView.frame.size.width
firstFrame.size.height = self.scrollView.frame.size.height
table1.tableView.frame = firstFrame
// privateUserSecondScreen = mainStoryboard.instantiateViewControllerWithIdentifier("PrivateProfileSecondScreenTableViewController") as! PrivateProfileSecondScreenTableViewController
var secondFrame:CGRect = table2.tableView.frame
secondFrame.origin.x = self.scrollView.frame.size.width
secondFrame.origin.y = 0
secondFrame.size.width = self.scrollView.frame.size.width
secondFrame.size.height = self.scrollView.frame.size.height
table2.tableView.frame = secondFrame
}
func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 3.0 + pageWidth) / (pageWidth * 3.0)))
if page == 0 {
segmentedControl.selectedSegmentIndex = 0
return
}
if page == 1 {
segmentedControl.selectedSegmentIndex = 1
return
}
}
@IBAction func changedSegmentedControl(sender: AnyObject) {
switch segmentedControl.selectedSegmentIndex {
case 1:
let p = CGPoint(x:self.view.frame.size.width,y:0)
self.scrollView.setContentOffset(p, animated: true)
break
case 0:
let p = CGPoint(x:0,y:0)
scrollView.setContentOffset(p, animated: true)
break
default:
let p = CGPoint(x:0,y:0)
scrollView.setContentOffset(p, animated: true)
}
}
/*
// 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.
}
*/
}
|
apache-2.0
|
821abc99847837a5f27d2fa7a32453a7
| 28.547771 | 205 | 0.690019 | 4.812241 | false | false | false | false |
chenzilu1990/Who
|
who/who/AppDelegate.swift
|
1
|
2973
|
// AppDelegate.swift
//
// Created by chenzilu on 16/7/12.
// Copyright © 2016年 chenzilu. All rights reserved.
//
import UIKit
let APPCache = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
let playerPath = (APPCache)! + "/player.plist"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let players : NSMutableArray = {
let nameArr = NSMutableArray(contentsOfFile: playerPath)
if let players = nameArr {
return players
} else {
return NSMutableArray()
}
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow.init(frame: UIScreen.main.bounds)
let rootVC = SBPlayerListVC()
rootVC.players = players
window?.rootViewController = UINavigationController.init(rootViewController: rootVC)
window?.makeKeyAndVisible()
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) {
players.write(toFile: playerPath, atomically: true)
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
63160f0672b397bbab92e3f2c02219e8
| 38.078947 | 285 | 0.705387 | 5.76699 | false | false | false | false |
charleshkang/Coffee-Mapper
|
Coffee Mapper/HomeViewController.swift
|
1
|
7085
|
//
// CMHomeViewController.swift
// Coffee Mapper
//
// Created by Charles Kang on 4/13/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import MapKit
import UIKit
import RealmSwift
class HomeViewController: UIViewController, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate, MKMapViewDelegate {
// IBOutlets
@IBOutlet var mapView: MKMapView!
@IBOutlet var tableView: UITableView!
// Properties
let distanceSpan: Double = 1000
var locationManager: CLLocationManager?
var lastLocation:CLLocation?
var venues:[Venue]?
// MARK: Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.onVenuesUpdated(_:)), name: API.notifications.venuesUpdated, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let mapView = self.mapView {
mapView.delegate = self
}
if let tableView = self.tableView {
tableView.delegate = self
tableView.dataSource = self
}
navigationController?.navigationBar.hidden = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidAppear(animated: Bool) {
if locationManager == nil {
locationManager = CLLocationManager()
locationManager!.delegate = self
locationManager!.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager!.requestAlwaysAuthorization()
locationManager!.distanceFilter = 50
locationManager!.startUpdatingLocation()
}
}
func onVenuesUpdated(notification: NSNotification) {
refreshVenues(nil)
}
func locationManager(manager: CLLocationManager,
didUpdateToLocation newLocation: CLLocation,
fromLocation oldLocation: CLLocation) {
if let mapView = self.mapView {
let annotationView = MKPinAnnotationView()
annotationView.pinTintColor = UIColor.blueColor()
let region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, distanceSpan, distanceSpan)
mapView.setRegion(region, animated: true)
refreshVenues(newLocation, getDataFromFoursquare: true)
}
}
func refreshVenues(location: CLLocation?, getDataFromFoursquare:Bool = false) {
if location != nil {
lastLocation = location
}
if let location = lastLocation {
if getDataFromFoursquare == true {
FoursquareAPI.sharedInstance.getCoffeeShopsWithLocation(location)
}
let (start, stop) = calculateCoordinatesWithRegion(location)
let predicate = NSPredicate(format: "latitude < %f AND latitude > %f AND longitude > %f AND longitude < %f", start.latitude, stop.latitude, start.longitude, stop.longitude)
let realm = try! Realm()
venues = realm.objects(Venue).filter(predicate).sort {
location.distanceFromLocation($0.coordinate) < location.distanceFromLocation($1.coordinate)
}
for venue in venues! {
let annotation = CoffeeAnnotation(title: venue.name, coordinate: CLLocationCoordinate2D(latitude: Double(venue.latitude), longitude: Double(venue.longitude)))
mapView?.addAnnotation(annotation)
}
tableView?.reloadData()
}
}
func calculateCoordinatesWithRegion(location:CLLocation) -> (CLLocationCoordinate2D, CLLocationCoordinate2D)
{
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, distanceSpan, distanceSpan)
var start:CLLocationCoordinate2D = CLLocationCoordinate2D()
var stop:CLLocationCoordinate2D = CLLocationCoordinate2D()
start.latitude = region.center.latitude + (region.span.latitudeDelta / 2.0)
start.longitude = region.center.longitude - (region.span.longitudeDelta / 2.0)
stop.latitude = region.center.latitude - (region.span.latitudeDelta / 2.0)
stop.longitude = region.center.longitude + (region.span.longitudeDelta / 2.0)
return (start, stop)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
if annotation.isKindOfClass(MKAnnotation) {
return nil
}
var view = mapView.dequeueReusableAnnotationViewWithIdentifier("annotationIdentifier")
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotationIdentifier")
}
view?.canShowCallout = true
return view
}
@IBAction func logoutButtonTapped(sender: AnyObject)
{
DataService.dataService.USER_REF.unauth()
NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "uid")
print("logged out: \(NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "uid"))")
let loginVC = self.storyboard!.instantiateViewControllerWithIdentifier("loginIdentifier") as! LoginViewController
presentViewController(loginVC, animated: true, completion: nil)
}
// MARK: Table View Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return venues?.count ?? 0
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cellIdentifier")
}
if let venue = venues?[indexPath.row] {
cell!.textLabel?.text = venue.name
cell!.detailTextLabel?.text = venue.address
}
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if let venue = venues?[indexPath.row] {
let region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: Double(venue.latitude), longitude: Double(venue.longitude)), distanceSpan, distanceSpan)
mapView?.setRegion(region, animated: true)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
guard let indexPath = tableView?.indexPathForSelectedRow,
venue = venues?[indexPath.row],
detailVC = segue.destinationViewController as? DetailViewController else {
return
}
detailVC.venue = venue
}
}
|
mit
|
a1d66b225e1150f721bc1231de65887e
| 38.138122 | 184 | 0.650903 | 5.699115 | false | false | false | false |
AsyncNinja/AsyncNinja
|
Sources/AsyncNinja/BaseProducer.swift
|
1
|
11946
|
//
// Copyright (c) 2016-2017 Anton Mironov
//
// 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 Dispatch
/// Mutable subclass of channel
/// You can update and complete producer manually
/// **internal use only**
public class BaseProducer<Update, Success>: Channel<Update, Success>, EventDestination {
private let _maxBufferSize: Int
var _bufferedUpdates = Queue<Update>()
private let _releasePool = ReleasePool(locking: PlaceholderLocking())
var _locking = makeLocking()
private var _handlers = QueueOfWeakElements<ProducerHandler<Update, Success>>()
private var _completion: Fallible<Success>?
/// amount of currently stored updates
override public var bufferSize: Int {
_locking.lock()
defer { _locking.unlock() }
return Int(_bufferedUpdates.count)
}
/// maximal amount of updates store
override public var maxBufferSize: Int { return _maxBufferSize }
/// completion of `Producer`. Returns nil if channel is not complete yet
override public var completion: Fallible<Success>? {
_locking.lock()
defer { _locking.unlock() }
return _completion
}
/// designated initializer of Producer. Initializes Producer with specified buffer size
init(bufferSize: Int = AsyncNinjaConstants.defaultChannelBufferSize) {
_maxBufferSize = bufferSize
}
/// **internal use only**
override public func makeHandler(
executor: Executor,
_ block: @escaping (_ event: ChannelEvent<Update, Success>, _ originalExecutor: Executor) -> Void
) -> AnyObject? {
_locking.lock()
defer { _locking.unlock() }
return _makeHandler(executor: executor, block)
}
fileprivate func _makeHandler(
executor: Executor,
_ block: @escaping (_ event: ChannelEvent<Update, Success>, _ originalExecutor: Executor) -> Void
) -> ProducerHandler<Update, Success>? {
let handler = ProducerHandler(
executor: executor,
bufferedUpdates: _bufferedUpdates,
owner: self,
block: block)
if let completion = _completion {
handler.handle(.completion(completion), from: nil)
return nil
} else {
_handlers.push(handler)
}
return handler
}
func _pushUpdateToBuffer(_ update: Update) {
_bufferedUpdates.push(update)
if _bufferedUpdates.count > self.maxBufferSize {
_ = _bufferedUpdates.pop()
}
}
/// Sends specified Update to the Producer
/// Value will not be sent for completed Producer
///
/// - Parameter update: value to update with
/// - Parameter originalExecutor: `Executor` you calling this method on.
/// Specifying this argument will allow to perform syncronous executions
/// on `strictAsync: false` `Executor`s.
/// Use default value or nil if you are not sure about an `Executor`
/// you calling this method on.
public func tryUpdate(
_ update: Update,
from originalExecutor: Executor?
) -> Bool {
// TEST: ChannelTests.testOverUpdate
traceID?._asyncNinja_log("try update \(update)")
_locking.lock()
guard case .none = _completion
else {
_didUpdate(update, from: originalExecutor)
_locking.unlock()
return false
}
if self.maxBufferSize > 0 {
_pushUpdateToBuffer(update)
}
let event = Event.update(update)
var handlersIterator = _handlers.makeIterator()
_didUpdate(update, from: originalExecutor)
_locking.unlock()
while let handler = handlersIterator.next() {
handler?.handle(event, from: originalExecutor)
}
return true
}
func _didUpdate(_ update: Update,
from originalExecutor: Executor?) {
}
/// Sends specified sequence of Update to the Producer
/// Values will not be sent for completed Producer
///
/// - Parameter updates: values to update with
/// - Parameter originalExecutor: `Executor` you calling this method on.
/// Specifying this argument will allow to perform syncronous executions
/// on `strictAsync: false` `Executor`s.
/// Use default value or nil if you are not sure about an `Executor`
/// you calling this method on.
public func update<S: Sequence>(
_ updates: S,
from originalExecutor: Executor? = nil
) where S.Iterator.Element == Update {
// TEST: ChannelTests.testOverUpdateWithSeqence
_locking.lock()
guard case .none = _completion
else {
_locking.unlock()
return
}
if self.maxBufferSize > 0 {
updates.suffix(self.maxBufferSize).forEach(_pushUpdateToBuffer)
}
var handlersIterator = _handlers.makeIterator()
_locking.unlock()
while let handler = handlersIterator.next() {
guard let handler = handler else { continue }
for update in updates {
handler.handle(.update(update), from: originalExecutor)
}
}
}
/// Tries to complete the Producer
///
/// - Parameter completion: value to complete Producer with
/// - Parameter originalExecutor: `Executor` you calling this method on.
/// Specifying this argument will allow to perform syncronous executions
/// on `strictAsync: false` `Executor`s.
/// Use default value or nil if you are not sure about an `Executor`
/// you calling this method on.
/// - Returns: true if Producer was completed with this call,
/// false if it was completed before
@discardableResult
public func tryComplete(
_ completion: Fallible<Success>,
from originalExecutor: Executor? = nil
) -> Bool {
// TEST: ChannelTests.testOverComplete
traceID?._asyncNinja_log("try complete \(completion)")
_locking.lock()
guard case .none = _completion
else {
_locking.unlock()
return false
}
_completion = completion
let handlers = _handlers
_handlers.removeAll()
_locking.unlock()
handlers.forEach { handler in
guard let handler_ = handler else { return }
handler_.handle(.completion(completion), from: originalExecutor)
handler_.releaseOwner()
}
return true
}
/// **internal use only** Inserts releasable to an internal release pool
/// that will be drained on completion
override public func _asyncNinja_retainUntilFinalization(_ releasable: Releasable) {
// assert((releasable as? AnyObject) !== self) // Xcode 8 mistreats this. This code is valid
_locking.lock()
defer { _locking.unlock() }
if case .none = _completion {
_releasePool.insert(releasable)
}
}
/// **internal use only** Inserts releasable to an internal release pool
/// that will be drained on completion
override public func _asyncNinja_notifyFinalization(_ block: @escaping () -> Void) {
_locking.lock()
defer { _locking.unlock() }
if case .none = _completion {
_releasePool.notifyDrain(block)
} else {
block()
}
}
/// **internal use only**
func notifyDrain(_ block: @escaping () -> Void) {
_locking.lock()
defer { _locking.unlock() }
if case .none = _completion {
_releasePool.notifyDrain(block)
}
}
/// Makes an iterator that allows synchronous iteration over update values of the channel
override public func makeIterator() -> Iterator {
_locking.lock()
let channelIteratorImpl = ProducerIteratorImpl<Update, Success>(channel: self, bufferedUpdates: Queue())
_locking.unlock()
return ChannelIterator(impl: channelIteratorImpl)
}
}
// MARK: - Iterators
private class ProducerIteratorImpl<Update, Success>: ChannelIteratorImpl<Update, Success> {
let _sema: DispatchSemaphore
var _locking = makeLocking(isFair: true)
var _bufferedUpdates: Queue<Update>
let _producer: BaseProducer<Update, Success>
var _handler: ProducerHandler<Update, Success>?
override var completion: Fallible<Success>? {
_locking.lock()
defer { _locking.unlock() }
return _completion
}
var _completion: Fallible<Success>?
init(channel: BaseProducer<Update, Success>, bufferedUpdates: Queue<Update>) {
_producer = channel
_bufferedUpdates = bufferedUpdates
_sema = DispatchSemaphore(value: 0)
for _ in 0..<_bufferedUpdates.count {
_sema.signal()
}
super.init()
_handler = channel._makeHandler(
executor: .immediate
) { [weak self] (event, originalExecutor) in
self?.handle(event, from: originalExecutor)
}
}
override public func next() -> Update? {
_sema.wait()
_locking.lock()
let update = _bufferedUpdates.pop()
_locking.unlock()
if let update = update {
return update
} else {
_sema.signal()
return nil
}
}
override func clone() -> ChannelIteratorImpl<Update, Success> {
return ProducerIteratorImpl(channel: _producer, bufferedUpdates: _bufferedUpdates)
}
func handle(_ value: ChannelEvent<Update, Success>,
from originalExecutor: Executor?) {
_locking.lock()
if case .some = _completion {
_locking.unlock()
return
}
switch value {
case let .update(update):
_bufferedUpdates.push(update)
case let .completion(completion):
_completion = completion
}
_locking.unlock()
_sema.signal()
}
}
// MARK: - Handlers
/// **internal use only** Wraps each block submitted to the channel
/// to provide required memory management behavior
final private class ProducerHandler<Update, Success> {
public typealias Event = ChannelEvent<Update, Success>
typealias Block = (_ event: Event, _ on: Executor) -> Void
let executor: Executor
let block: Block
var locking = makeLocking()
var bufferedUpdates: Queue<Update>?
var owner: Channel<Update, Success>?
let ownerTraceID: String?
/// Designated initializer of ProducerHandler
init(executor: Executor,
bufferedUpdates: Queue<Update>,
owner: Channel<Update, Success>,
block: @escaping Block) {
self.executor = executor
self.block = block
self.bufferedUpdates = bufferedUpdates
self.owner = owner
self.ownerTraceID = owner.traceID
executor.execute(from: nil) { (originalExecutor) in
self.handleBufferedUpdatesIfNeeded(from: originalExecutor)
}
}
func handleBufferedUpdatesIfNeeded(from originalExecutor: Executor) {
locking.lock()
let bufferedUpdatesIterator = self.bufferedUpdates?.makeIterator()
self.bufferedUpdates = nil
locking.unlock()
if var bufferedUpdatesIterator = bufferedUpdatesIterator {
while let update = bufferedUpdatesIterator.next() {
handle(.update(update), from: originalExecutor)
}
}
}
func handle(_ value: Event, from originalExecutor: Executor?) {
self.executor.execute(
from: originalExecutor
) { (originalExecutor) in
self.handleBufferedUpdatesIfNeeded(from: originalExecutor)
self.ownerTraceID?._asyncNinja_log("handling event \(value)")
self.block(value, originalExecutor)
}
}
func releaseOwner() {
self.owner = nil
}
}
|
mit
|
3ffac7a467053e777ac1d12ed3b1c44a
| 30.354331 | 108 | 0.680814 | 4.359854 | false | false | false | false |
mikkokut/SHMenu
|
SHMenu/SHMenuViewControllerDataSource.swift
|
1
|
2713
|
//
// SHMenuViewControllerDataSource.swift
// SHMenu
//
// Created by Mikko Kutilainen on 12.1.2016.
// Copyright © 2016 Shingle Oy. All rights reserved.
//
import Foundation
import UIKit
open class SHMenuViewControllerDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
let tableView: UITableView
var sections: [SHMenuSection]
public init(sections: [SHMenuSection], tableView: UITableView) {
self.tableView = tableView
self.sections = sections
super.init()
}
open func numberOfSections(in tableView: UITableView) -> Int {
return self.sections.count
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sections[section].rows.count
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section].header
}
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return self.sections[section].footer
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row]
return row.cell(self.tableView)
}
open func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row]
if let action = row.accessoryAction {
action(indexPath)
}
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row]
if let action = row.action {
action(indexPath)
if row.automaticallyDeselectSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row]
return row.preferredHeight
}
open func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView {
let section = self.sections[section]
view.textLabel?.textAlignment = section.footerTextAlignment ?? .left
}
}
}
|
mit
|
9296fc28bb6a12c7e771eafd6ef01103
| 36.666667 | 112 | 0.666667 | 5.205374 | false | false | false | false |
WalterCreazyBear/Swifter30
|
ViewControllerTransitionDemo/ViewControllerTransitionDemo/ModalTransitionMananger.swift
|
1
|
3450
|
//
// ModalTransitionMananger.swift
// ViewControllerTransitionDemo
//
// Created by Bear on 2017/6/30.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ModalTransitionMananger: NSObject {
fileprivate var presenting = false
}
extension ModalTransitionMananger: UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
//MARK: 这里有个问题:如果from的viewcontroller来自一个navigationController的话,这里得到的fromViewController也是一个
//navigationController. 对navigationController的View操作不当的话,会引起黑屏,即所有的view都不可见
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!)
let vcTwo = !self.presenting ? screens.from : screens.to
let vcOne = !self.presenting ? screens.to : screens.from
let vcTwoView = vcTwo.view
let vcOneView = vcOne.view
//MARK: 原项目里将两个view都加到container里面了,但,container里面默认是有from的view的。
//也就是,我们只用添加to的View到container里就好了。
//再次就是如果不改变view的alpha的话,view会存在遮挡的问题,也就是有的动画是会被盖住的
if presenting
{
container.addSubview(vcTwoView!)
container.bringSubview(toFront: vcTwoView!)
(vcTwo as! ViewControllerTwo).imageView.transform = CGAffineTransform(translationX: 400, y: 0)
vcTwoView?.alpha = 0
}
else
{
container.addSubview(vcOneView!)
container.bringSubview(toFront: vcTwoView!)
}
let duration = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: [], animations: {
if (self.presenting){
(vcTwo as! ViewControllerTwo).imageView.transform = CGAffineTransform.identity
vcTwoView?.alpha = 1.0
}
else {
(vcTwo as! ViewControllerTwo).imageView.transform = CGAffineTransform(translationX: 400, y: 0)
vcTwoView?.alpha = 0.0
}
}, completion: { finished in
transitionContext.completeTransition(true)
UIApplication.shared.keyWindow?.addSubview(screens.to.view)
})
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
}
extension ModalTransitionMananger: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
|
mit
|
3c01b82f742ffde0a45254d1d8da3595
| 37.493976 | 239 | 0.675743 | 5.186688 | false | false | false | false |
tardieu/swift
|
test/SILGen/objc_imported_generic.swift
|
1
|
8452
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | %FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared @_TFCSo12GenericClassCfT5thingGSQx__GSQGS_x__
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil @_TF21objc_imported_generic24genericMethodOnAnyObject
// CHECK: dynamic_method [volatile] {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign : <T where T : AnyObject> (GenericClass<T>) -> () -> T?, $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil @_TF21objc_imported_generic31genericMethodOnAnyObjectChainedFT1oPs9AnyObject_1bSb_GSqPS0___
// CHECK: bb0([[ANY:%.*]] : $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '_TF21objc_imported_generic31genericMethodOnAnyObjectChainedFT1oPs9AnyObject_1bSb_GSqPS0___'
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil @_TF21objc_imported_generic27genericSubscriptOnAnyObjectFT1oPs9AnyObject_1bSb_GSqPS0___
// CHECK: bb0([[ANY:%.*]]
// CHCEK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
// CHECK: } // end sil function '_TF21objc_imported_generic27genericSubscriptOnAnyObjectFT1oPs9AnyObject_1bSb_GSqPS0___'
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil @_TF21objc_imported_generic26genericPropertyOnAnyObjectFT1oPs9AnyObject_1bSb_GSqGSqPS0____
// CHECK: bb0([[ANY:%.*]] : $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '_TF21objc_imported_generic26genericPropertyOnAnyObjectFT1oPs9AnyObject_1bSb_GSqGSqPS0____'
public protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
// TODO: Crashes in IRGen because the type metadata for `T` is not found in
// the witness thunk to satisfy the associated type requirement. This could be
// addressed by teaching IRGen to fulfill erased type parameters from protocol
// witness tables (rdar://problem/26602097).
#if !IRGEN_INTEGRATION_TEST
extension GenericClass: ThingHolder {}
#endif
public protocol Ansible: class {
associatedtype Anser: ThingHolder
}
public func genericBlockBridging<T: Ansible>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil @_TF21objc_imported_generic20genericBlockBridging
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @_TTRGRxs9AnyObjectx21objc_imported_generic7AnsiblerXFdCb_dx_ax_XFo_ox_ox_
// CHECK: partial_apply [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @_TTRgRxs9AnyObjectx21objc_imported_generic7AnsiblerXFo_ox_ox_XFdCb_dx_ax_
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil @_TF21objc_imported_generic20arraysOfGenericParam
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref {{@_TFCSo12GenericClassCfT13arrayOfThings.*}} : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil shared @_TFF21objc_imported_generic11genericFuncuRxs9AnyObjectrFMxT_U_FT_T_ : $@convention(thin) <V where V : AnyObject> () -> () {
// CHECK: [[INIT:%.*]] = function_ref @_TFCSo12GenericClassCfT_GS_x_ : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0>
// CHECK: [[META:%.*]] = metatype $@thick GenericClass<V>.Type
// CHECK: apply [[INIT]]<V>([[META]])
// CHECK: return
func genericFunc<V: AnyObject>(_ v: V.Type) {
let _ = {
var _ = GenericClass<V>()
}
}
// CHECK-LABEL: sil hidden @_TF21objc_imported_generic23configureWithoutOptionsFT_T_ : $@convention(thin) () -> ()
// CHECK: [[NIL_FN:%.*]] = function_ref @_TFSqCfT10nilLiteralT__GSqx_ : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
// CHECK: apply [[NIL_FN]]<[GenericOption : Any]>({{.*}})
// CHECK: return
func configureWithoutOptions() {
_ = GenericClass<NSObject>(options: nil)
}
// foreign to native thunk for init(options:), uses GenericOption : Hashable
// conformance
// CHECK-LABEL: sil shared [thunk] @_TTOFCSo12GenericClasscfT7optionsGSqGVs10DictionaryVSC13GenericOptionP____GSQGS_x__ : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
// CHECK: [[FN:%.*]] = function_ref @_TFE10FoundationVs10Dictionary19_bridgeToObjectiveCfT_CSo12NSDictionary : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: return
// This gets emitted down here for some reason
// CHECK-LABEL: sil shared [thunk] @_TTOFCSo12GenericClasscfT13arrayOfThings
// CHECK: class_method [volatile] {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
// Make sure we emitted the witness table for the above conformance
// CHECK-LABEL: sil_witness_table shared [fragile] GenericOption: Hashable module objc_generics {
// CHECK: method #Hashable.hashValue!getter.1: {{.*}} : @_TTWVSC13GenericOptions8Hashable13objc_genericsFS0_g9hashValueSi
// CHECK: }
|
apache-2.0
|
a6619625b8cbeec6f181741bc23724f5
| 57.86014 | 279 | 0.695854 | 3.498337 | false | false | false | false |
MrDeveloper4/TestProject-GitHubAPI
|
TestProject-GitHubAPI/Pods/RealmSwift/RealmSwift/Realm.swift
|
6
|
25894
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A `Realm` instance (also referred to as "a Realm") represents a Realm database.
Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`).
`Realm` instances are cached internally, and constructing equivalent `Realm` objects (for example, by using the same
path or identifier) produces limited overhead.
If you specifically want to ensure a `Realm` instance is destroyed (for example, if you wish to open a Realm, check
some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an
`autoreleasepool {}` and ensure you have no other strong references to it.
- warning: `Realm` instances are not thread safe and cannot be shared across threads or dispatch queues. You must
construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
run all of its blocks on the same thread.
*/
public final class Realm {
// MARK: Properties
/// The `Schema` used by the Realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/// The `RealmConfiguration` object that was used to create this `Realm` instance.
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
/// Indicates if this Realm contains any objects.
public var isEmpty: Bool { return rlmRealm.isEmpty }
// MARK: Initializers
/**
Obtains an instance of the default Realm.
The default Realm is persisted as default.realm under the Documents directory of your Application on iOS, and in
your application's Application Support directory on OS X.
The default Realm is created using the default `Configuration`, which can be changed by setting a new
`Configuration` object on the `Realm.Configuration.defaultConfiguration` property.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init() throws {
let rlmRealm = try RLMRealm(configuration: RLMRealmConfiguration.defaultConfiguration())
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance with the given configuration.
- parameter configuration: A configuration value to use when creating the Realm.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(configuration: Configuration) throws {
let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
self.init(rlmRealm)
}
/**
Obtains a `Realm` instance persisted at a specified file URL.
- parameter fileURL: The local URL of the file the Realm should be saved at.
- throws: An `NSError` if the Realm could not be initialized.
*/
public convenience init(fileURL: NSURL) throws {
var configuration = Configuration.defaultConfiguration
configuration.fileURL = fileURL
try self.init(configuration: configuration)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transaction.
Write transactions cannot be nested, and trying to execute a write transaction on a Realm which is already
participating in a write transaction will throw an error. Calls to `write` from `Realm` instances in other threads
will block until the current write transaction completes.
Before executing the write transaction, `write` updates the `Realm` instance to the
latest Realm version, as if `refresh()` had been called, and generates notifications
if applicable. This has no effect if the Realm was already up to date.
- parameter block: The block containing actions to perform.
- throws: An `NSError` if the transaction could not be completed successfully.
*/
public func write(@noescape block: (() -> Void)) throws {
try rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction on the Realm.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a Realm which is
already in a write transaction will throw an error. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` instance to the latest Realm version, as if `refresh()` had been called, and
generates notifications if applicable. This has no effect if the Realm
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
Realm in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all write operations in the current write transaction, and ends the transaction.
- warning: This method may only be called during a write transaction.
- throws: An `NSError` if the transaction could not be written.
*/
public func commitWrite() throws {
try rlmRealm.commitWriteTransaction()
}
/**
Reverts all writes made in the current write transaction and ends the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated
object instances. Any `Object`s which were added to the Realm will be
invalidated rather than becoming unmanaged.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
- warning: This method may only be called during a write transaction.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates whether this Realm is currently in a write transaction.
- warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an existing object into the Realm.
Only pass `true` to `update` if the object has a primary key. If no objects exist in
the Realm with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all child relationships referenced by this object will also be added to
the Realm if they are not already in it. If the object or any related
objects are already being managed by a different Realm an error will be thrown. Use one
of the `create` functions to insert a copy of a managed object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be `false`).
- parameter object: The object to be added to this Realm.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates all the objects in a collection into the Realm.
- see: `add(_:update:)`
- warning: This method may only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to the Realm.
- parameter update: If `true`, objects that are already in the Realm will be updated instead of added anew.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Creates or updates a Realm object with a given value, adding it to the Realm and returning it.
Only pass `true` to `update` if the object has a primary key. If no objects exist in
the Realm with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method may only be called during a write transaction.
- parameter type: The type of the object to create.
- parameter value: The value used to populate the object. This can be any key-value coding compliant
object, or an array or dictionary returned from the methods in `NSJSONSerialization`, or
an `Array` containing one element for each persisted property. An error will be
thrown if any required properties are not present and those properties were not defined with
default values.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.
- returns: The newly created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
let className = (type as Object.Type).className()
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object. This can be any key-value coding compliant
object, or a JSON object such as those returned from the methods in `NSJSONSerialization`,
or an `Array` containing one element for each persisted property. An exception will be
thrown if any required properties are not present and those properties were not defined with
default values.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
public func dynamicCreate(className: String, value: AnyObject = [:], update: Bool = false) -> DynamicObject {
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), DynamicObject.self)
}
// MARK: Deleting objects
/**
Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
- warning: This method may only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes one or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable `SequenceType` whose elements are `Object`s.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes one or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A list of objects to delete.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes one or more objects from the Realm.
- warning: This method may only be called during a write transaction.
- parameter objects: A `Results` containing the objects to be deleted.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from the Realm.
- warning: This method may only be called during a write transaction.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type stored in the Realm.
- parameter type: The type of the objects to be returned.
- returns: A `Results` containing the objects.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(className: String) -> Results<DynamicObject> {
return Results<DynamicObject>(RLMGetObjects(rlmRealm, className, nil))
}
/**
Retrieves the single instance of a given object type with the given primary key from the Realm.
This method requires that `primaryKey()` be overridden on the given object class.
- see: `Object.primaryKey()`
- parameter type: The type of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type`, or `nil` if no instance with the given primary key exists.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(), key), Optional<T>.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObjectForPrimaryKey(className: String, key: AnyObject) -> DynamicObject? {
return unsafeBitCast(RLMGetObject(rlmRealm, className, key), Optional<DynamicObject>.self)
}
// MARK: Notifications
/**
Adds a notification handler for changes in this Realm, and returns a notification token.
Notification handlers are called after each write transaction is committed,
independent from the thread or process.
Handler blocks are called on the same thread that they were added on, and may only be added on threads which are
currently within a run loop. Unless you are specifically creating and running a run loop on a background thread,
this will normally only be the main thread.
Notifications can't be delivered as long as the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple
notifications may be coalesced.
You must retain the returned token for as long as you want updates to continue
to be sent to the block. To stop receiving updates, call `stop()` on the token.
- parameter block: A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The Realm for which this notification occurred.
- returns: A token which must be retained for as long as you wish to continue receiving change notifications.
*/
@warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock")
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock { rlmNotification, _ in
if rlmNotification == RLMRealmDidChangeNotification {
block(notification: Notification.DidChange, realm: self)
} else if rlmNotification == RLMRealmRefreshRequiredNotification {
block(notification: Notification.RefreshRequired, realm: self)
}
}
}
// MARK: Autorefresh and Refresh
/**
Set this property to `true` to automatically update this Realm when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call `refresh()` on the Realm to
update it to get the latest data.
Note that by default, background threads do not have an active run loop and you
will need to manually call `refresh()` in order to update to the latest version,
even if `autorefresh` is set to `true`.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
automatic refreshing is enabled.
Disabling `autorefresh` on a `Realm` without any strong references to it will not
have any effect, and `autorefresh` will revert back to `true` the next time the Realm is created. This is normally
irrelevant as it means that there is nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the `Realm` that manages them), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to `true`.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
- returns: Whether there were any updates for the Realm. Note that `true` may be returned even if no data actually
changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidates all `Object`s and `Results` managed by the Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this `Realm` instance on the current thread are
invalidated. `Object`s and `Array`s cannot be used. `Results` will become empty. The Realm itself remains valid,
and a new read transaction is implicitly begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm, is a no-op. This method
may not be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
The destination file cannot already exist.
Note that if this method is called from within a write transaction, the *current* data is written, not the data
from the point when the previous write transaction was committed.
- parameter fileURL: Local URL to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
- throws: An `NSError` if the copy could not be written.
*/
public func writeCopyToURL(fileURL: NSURL, encryptionKey: NSData? = nil) throws {
try rlmRealm.writeCopyToURL(fileURL, encryptionKey: encryptionKey)
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
/// Returns a Boolean indicating whether two `Realm` instances are equal.
public func == (lhs: Realm, rhs: Realm) -> Bool { // swiftlint:disable:this valid_docs
return lhs.rlmRealm == rhs.rlmRealm
}
// MARK: Notifications
/// A notification indicating that changes were made to a Realm.
public enum Notification: String {
/**
This notification is posted when the data in a Realm has changed.
`DidChange` is posted after a Realm has been refreshed to reflect a write transaction, This can happen when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`write(_:)`/`beginWrite()`, or after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
This notification is posted when a write transaction has been committed to a Realm on a different thread for the
same file.
It is not posted if `autorefresh` is enabled, or if the Realm is refreshed before the
notification has a chance to run.
Realms with autorefresh disabled should normally install a handler for this notification which calls `refresh()`
after doing some work. Refreshing the Realm is optional, but not refreshing the Realm may lead to large Realm
files. This is because Realm must keep an extra copy of the data for the stale Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// The type of a block to run for notification purposes when the data in a Realm is modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
|
mit
|
4dfcadf1a35a5c410052eb5a9193a5a0
| 40.831987 | 120 | 0.693095 | 4.977701 | false | false | false | false |
artemkalinovsky/SwiftyPiper
|
SwiftyPiper/Model/Player/Player+AVAssetResourceLoaderDelegate.swift
|
1
|
2485
|
//
// Player+AVAssetResourceLoaderDelegate.swift
// SwiftyPiper
//
// Created by Artem Kalinovsky on 17/02/2016.
// Copyright © 2016 Artem Kalinovsky. All rights reserved.
//
import Foundation
import AVKit
import AVFoundation
extension Player: AVAssetResourceLoaderDelegate {
private enum FileScheme: String {
case Custom = "customscheme";
}
func resourceLoader(resourceLoader: AVAssetResourceLoader,
shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
guard let resourceURL = loadingRequest.request.URL
else {
return false
}
if resourceURL.scheme == FileScheme.Custom.rawValue {
let loader = self.resourceLoaderForRequest(loadingRequest)
if let _ = loader {
} else {
let loader = FilePlayerResourceLoader(resourceURL: resourceURL, request: loadingRequest)
loader.delegate = self
self.resourceLoaders.setObject(loader, forKey: self.keyForResourceLoaderWithURL(resourceURL)!)
}
loader?.addRequest(loadingRequest)
return true
}
return false
}
func resourceLoader(resourceLoader: AVAssetResourceLoader,
didCancelLoadingRequest loadingRequest: AVAssetResourceLoadingRequest) {
let loader = self.resourceLoaderForRequest(loadingRequest)
loader?.removeRequest(loadingRequest)
}
func resourceLoaderForRequest(loadingRequest: AVAssetResourceLoadingRequest) -> FilePlayerResourceLoader? {
guard let interceptedURL = loadingRequest.request.URL
else {
return nil
}
if interceptedURL.scheme == FileScheme.Custom.rawValue {
let requestKey = self.keyForResourceLoaderWithURL(interceptedURL)
if let _ = requestKey {
return self.resourceLoaders.objectForKey(requestKey!) as? FilePlayerResourceLoader
}
}
return nil
}
func keyForResourceLoaderWithURL(requestURL: NSURL) -> NSCopying? {
if requestURL.scheme == FileScheme.Custom.rawValue {
return requestURL.absoluteString
}
return nil
}
}
|
gpl-3.0
|
1e2be82189acecc32f7893994e22539b
| 31.25974 | 114 | 0.601852 | 6.029126 | false | false | false | false |
filestack/filestack-ios
|
Demo/FilestackDemo/AppDelegate.swift
|
1
|
5964
|
//
// AppDelegate.swift
// FilestackDemo
//
// Created by Ruben Nine on 10/19/17.
// Copyright © 2017 Filestack. All rights reserved.
//
import AVFoundation.AVAssetExportSession
import Filestack
import FilestackSDK
import UIKit
// Set your app's URL scheme here.
let callbackURLScheme = "filestackdemo"
// Set your Filestack's API key here.
let filestackAPIKey = "YOUR-FILESTACK-API-KEY"
// Set your Filestack's app secret here.
let filestackAppSecret = "YOUR-FILESTACK-APP-SECRET"
// Filestack Client, nullable
var client: Filestack.Client?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundTaskID: UIBackgroundTaskIdentifier? = nil
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
setupFilestackClient()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
if let client = client, client.sdkClient.isUploading {
beginBackgroundTaskForFilestack()
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
endBackgroundTaskForFilestack()
}
}
private extension AppDelegate {
func setupFilestackClient() {
// Set `UploadService.shared.useBackgroundSession` to true to allow uploads in the background.
FilestackSDK.UploadService.shared.useBackgroundSession = true
// In case your Filestack account has security enabled, you will need to instantiate a `Security` object.
// We can do this by either configuring a `Policy` and instantiating a `Security` object by passing
// the `Policy` and an `appSecret`, or by instantiating a `Security` object directly by passing an already
// encoded policy together with its corresponding signature — in this example, we will use the 1st method.
// Create `Policy` object with an expiry time and call permissions.
let policy = Policy(expiry: .distantFuture,
call: [.pick, .read, .stat, .write, .writeURL, .store, .convert, .remove, .exif])
// Create `Security` object based on our previously created `Policy` object and app secret obtained from
// [Filestack Developer Portal](https://dev.filestack.com/).
guard let security = try? Security(policy: policy, appSecret: filestackAppSecret) else {
fatalError("Unable to instantiate Security object.")
}
// Create `Config` object.
let config = Filestack.Config.builder
// Make sure to assign a valid app scheme URL
.with(callbackURLScheme: callbackURLScheme)
// Video quality for video recording (and sometimes exporting.)
.with(videoQuality: .typeHigh)
// Starting in iOS 11, you can export images in HEIF or JPEG by setting this value to
// `.current` or `.compatible` respectively.
// Here we state we prefer HEIF for image export.
.with(imageURLExportPreset: .current)
// Starting in iOS 11, you can decide what format and quality will be used for exported videos.
// Here we state we want to export HEVC at the highest quality.
.with(videoExportPreset: AVAssetExportPresetHEVCHighestQuality)
// Allow up to 10 files to be picked.
.with(maximumSelectionLimit: 10)
// Enable image editor for files picked from the photo library.
.withEditorEnabled()
// Enable a list of cloud sources.
.with(availableCloudSources: [.dropbox, .googleDrive, .googlePhotos, .unsplash, .customSource])
// Enable a list of local sources.
.with(availableLocalSources: [.camera, .photoLibrary, .documents, customLocalSource()])
// Specify what UTIs are allowed for documents picked from Apple's Document Picker (aka iOS Files.)
.with(documentPickerAllowedUTIs: ["public.item"])
// Specify what UTIs are allowed for files picked from cloud providers.
.with(cloudSourceAllowedUTIs: ["public.item"])
.build()
// Instantiate the Filestack `Client` by passing an API key obtained from https://dev.filestack.com/,
// together with a `Security` and `Config` object.
// If your account does not have security enabled, then you can omit this parameter or set it to `nil`.
client = Filestack.Client(apiKey: filestackAPIKey, security: security, config: config)
}
/// Returns a custom `LocalSource` configured to use an user-provided `SourceProvider`.
func customLocalSource() -> LocalSource {
let customSourceTitle = "Custom Source"
let customProvider = MyCustomSourceProvider()
customProvider.title = customSourceTitle
customProvider.availableURLs = [
Bundle.main.url(forResource: "demo1", withExtension: "jpg")!,
Bundle.main.url(forResource: "demo2", withExtension: "jpg")!,
Bundle.main.url(forResource: "demo3", withExtension: "jpg")!,
Bundle.main.url(forResource: "demo4", withExtension: "jpg")!,
Bundle.main.url(forResource: "demo5", withExtension: "jpg")!
]
let customSource = LocalSource.custom(
description: customSourceTitle,
image: UIImage(named: "icon-custom-source")!,
provider: customProvider
)
return customSource
}
func beginBackgroundTaskForFilestack() {
backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Filestack Background Upload") {
self.endBackgroundTaskForFilestack()
}
}
func endBackgroundTaskForFilestack() {
if let backgroundTaskID = backgroundTaskID {
UIApplication.shared.endBackgroundTask(backgroundTaskID)
self.backgroundTaskID = .invalid
}
}
}
|
mit
|
2234e207df646910e4f2693b944c162c
| 43.155556 | 121 | 0.670861 | 4.83455 | false | true | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxSwift/RxSwift/Observables/Buffer.swift
|
20
|
4518
|
//
// Buffer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html)
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<[Element]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
final private class BufferTimeCount<Element>: Producer<[Element]> {
fileprivate let _timeSpan: RxTimeInterval
fileprivate let _count: Int
fileprivate let _scheduler: SchedulerType
fileprivate let _source: Observable<Element>
init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) {
self._source = source
self._timeSpan = timeSpan
self._count = count
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [Element] {
let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class BufferTimeCountSink<Element, Observer: ObserverType>
: Sink<Observer>
, LockOwnerType
, ObserverType
, SynchronizedOnType where Observer.Element == [Element] {
typealias Parent = BufferTimeCount<Element>
private let _parent: Parent
let _lock = RecursiveLock()
// state
private let _timerD = SerialDisposable()
private var _buffer = [Element]()
private var _windowID = 0
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
self.createTimer(self._windowID)
return Disposables.create(_timerD, _parent._source.subscribe(self))
}
func startNewWindowAndSendCurrentOne() {
self._windowID = self._windowID &+ 1
let windowID = self._windowID
let buffer = self._buffer
self._buffer = []
self.forwardOn(.next(buffer))
self.createTimer(windowID)
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
self._buffer.append(element)
if self._buffer.count == self._parent._count {
self.startNewWindowAndSendCurrentOne()
}
case .error(let error):
self._buffer = []
self.forwardOn(.error(error))
self.dispose()
case .completed:
self.forwardOn(.next(self._buffer))
self.forwardOn(.completed)
self.dispose()
}
}
func createTimer(_ windowID: Int) {
if self._timerD.isDisposed {
return
}
if self._windowID != windowID {
return
}
let nextTimer = SingleAssignmentDisposable()
self._timerD.disposable = nextTimer
let disposable = self._parent._scheduler.scheduleRelative(windowID, dueTime: self._parent._timeSpan) { previousWindowID in
self._lock.performLocked {
if previousWindowID != self._windowID {
return
}
self.startNewWindowAndSendCurrentOne()
}
return Disposables.create()
}
nextTimer.setDisposable(disposable)
}
}
|
mit
|
1da1e6df729fb00a901bb5317249896a
| 31.731884 | 188 | 0.622758 | 4.893824 | false | false | false | false |
mbogh/ProfileKit
|
ProfileKit/Profile.swift
|
1
|
1305
|
//
// Profile.swift
// ProfileKit
//
// Created by Morten Bøgh on 25/01/15.
// Copyright (c) 2015 Morten Bøgh. All rights reserved.
//
import Foundation
public enum ProfileStatus {
case Expired
case OK
var description: String {
switch self {
case .Expired: return "Expired"
case .OK: return "OK"
}
}
}
public struct Profile {
public let filePath: String
public let name: String
public let creationDate: NSDate
public let expirationDate: NSDate
public let teamName: String?
public let teamID: String?
public var status: ProfileStatus {
return (expirationDate.compare(NSDate()) != .OrderedDescending) ? .Expired : .OK
}
/// Designated initializer
public init?(filePath path: String, data: NSDictionary) {
filePath = path
if data["Name"] == nil { return nil }
if data["CreationDate"] == nil { return nil }
if data["ExpirationDate"] == nil { return nil }
name = data["Name"] as String
creationDate = data["CreationDate"] as NSDate
expirationDate = data["ExpirationDate"] as NSDate
teamName = data["TeamName"] as? String
teamID = bind(data["TeamIdentifier"]) { teamIdentifiers in (teamIdentifiers as [String]).first }
}
}
|
mit
|
1b7e1baacb70514184046cfb8e148817
| 24.076923 | 104 | 0.629317 | 4.416949 | false | false | false | false |
softmaxsg/trakt.tv-searcher
|
TraktSearcher/Assembly/MoviesAssembly.swift
|
1
|
1067
|
//
// MoviesAssembly.swift
// TraktSearcher
//
// Copyright © 2016 Vitaly Chupryk. All rights reserved.
//
import UIKit
import TraktSearchAPI
class MoviesAssembly
{
private static let traktApplicationKey = "ad005b8c117cdeee58a1bdb7089ea31386cd489b21e14b19818c91511f12a086"
func createMoviesViewController() -> MainViewController
{
let searchAPI = TraktSearchAPI(queue: NSOperationQueue(), applicationKey: self.dynamicType.traktApplicationKey)
let popularMoviesViewModel = PopularMoviesViewModel(searchAPI: searchAPI)
let searchMoviesViewModel = SearchMoviesViewModel(searchAPI: searchAPI)
let mainController = MainViewController(popularMoviesViewModel: popularMoviesViewModel, searchMoviesViewModel: searchMoviesViewModel)
mainController.popularMoviesDelegate = popularMoviesViewModel
mainController.searchMoviesDelegate = searchMoviesViewModel
popularMoviesViewModel.delegate = mainController
searchMoviesViewModel.delegate = mainController
return mainController
}
}
|
mit
|
c2e94b6527f936cb5dd8da0afba56ff0
| 33.387097 | 141 | 0.783302 | 4.801802 | false | false | false | false |
HongliYu/firefox-ios
|
Client/Frontend/Browser/BrowserViewController/BrowserViewController+WebViewDelegates.swift
|
1
|
20982
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Shared
private let log = Logger.browserLogger
/// List of schemes that are allowed to be opened in new tabs.
private let schemesAllowedToBeOpenedAsPopups = ["http", "https", "javascript", "data", "about"]
extension BrowserViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let parentTab = tabManager[webView] else { return nil }
guard !navigationAction.isInternalUnprivileged, shouldRequestBeOpenedAsPopup(navigationAction.request) else {
print("Denying popup from request: \(navigationAction.request)")
return nil
}
if let currentTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(currentTab)
}
// If the page uses `window.open()` or `[target="_blank"]`, open the page in a new tab.
// IMPORTANT!!: WebKit will perform the `URLRequest` automatically!! Attempting to do
// the request here manually leads to incorrect results!!
let newTab = tabManager.addPopupForParentTab(parentTab, configuration: configuration)
return newTab.webView
}
fileprivate func shouldRequestBeOpenedAsPopup(_ request: URLRequest) -> Bool {
// Treat `window.open("")` the same as `window.open("about:blank")`.
if request.url?.absoluteString.isEmpty ?? false {
return true
}
if let scheme = request.url?.scheme?.lowercased(), schemesAllowedToBeOpenedAsPopups.contains(scheme) {
return true
}
return false
}
fileprivate func shouldDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool {
// Only display a JS Alert if we are selected and there isn't anything being shown
return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil)
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler)
if shouldDisplayJSAlertForWebView(webView) {
present(messageAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(messageAlert)
} else {
// This should never happen since an alert needs to come from a web view but just in case call the handler
// since not calling it will result in a runtime exception.
completionHandler()
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler)
if shouldDisplayJSAlertForWebView(webView) {
present(confirmAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(confirmAlert)
} else {
completionHandler(false)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText)
if shouldDisplayJSAlertForWebView(webView) {
present(textInputAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(textInputAlert)
} else {
completionHandler(nil)
}
}
func webViewDidClose(_ webView: WKWebView) {
if let tab = tabManager[webView] {
// Need to wait here in case we're waiting for a pending `window.open()`.
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
self.tabManager.removeTabAndUpdateSelectedIndex(tab)
}
}
}
}
extension WKNavigationAction {
/// Allow local requests only if the request is privileged.
var isInternalUnprivileged: Bool {
guard let url = request.url else {
return true
}
if let url = InternalURL(url) {
return !url.isAuthorized
} else {
return false
}
}
}
extension BrowserViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if tabManager.selectedTab?.webView !== webView {
return
}
updateFindInPageVisibility(visible: false)
// If we are going to navigate to a new page, hide the reader mode button. Unless we
// are going to a about:reader page. Then we keep it on screen: it will change status
// (orange color) as soon as the page has loaded.
if let url = webView.url {
if !url.isReaderModeURL {
urlBar.updateReaderModeState(ReaderModeState.unavailable)
hideReaderModeBar(animated: false)
}
}
}
// Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise
// it could just be a visit to a regular page on maps.apple.com.
fileprivate func isAppleMapsURL(_ url: URL) -> Bool {
if url.scheme == "http" || url.scheme == "https" {
if url.host == "maps.apple.com" && url.query != nil {
return true
}
}
return false
}
// Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com
// used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case
// them then iOS will actually first open Safari, which then redirects to the app store. This works but it will
// leave a 'Back to Safari' button in the status bar, which we do not want.
fileprivate func isStoreURL(_ url: URL) -> Bool {
if url.scheme == "http" || url.scheme == "https" || url.scheme == "itms-apps" {
if url.host == "itunes.apple.com" {
return true
}
}
return false
}
// This is the place where we decide what to do with a new navigation action. There are a number of special schemes
// and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate
// method.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return
}
if InternalURL.isValid(url: url) {
if navigationAction.navigationType != .backForward, navigationAction.isInternalUnprivileged {
log.warning("Denying unprivileged request: \(navigationAction.request)")
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
return
}
// First special case are some schemes that are about Calling. We prompt the user to confirm this action. This
// gives us the exact same behaviour as Safari.
if url.scheme == "tel" || url.scheme == "facetime" || url.scheme == "facetime-audio" {
UIApplication.shared.open(url, options: [:])
decisionHandler(.cancel)
return
}
if url.scheme == "about" {
decisionHandler(.allow)
return
}
if url.scheme == "javascript", navigationAction.request.isPrivileged {
decisionHandler(.cancel)
if let javaScriptString = url.absoluteString.replaceFirstOccurrence(of: "javascript:", with: "").removingPercentEncoding {
webView.evaluateJavaScript(javaScriptString)
}
return
}
// Second special case are a set of URLs that look like regular http links, but should be handed over to iOS
// instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because
// iOS will always say yes. TODO Is this the same as isWhitelisted?
if isAppleMapsURL(url) {
UIApplication.shared.open(url, options: [:])
decisionHandler(.cancel)
return
}
if let tab = tabManager.selectedTab, isStoreURL(url) {
decisionHandler(.cancel)
let alreadyShowingSnackbarOnThisTab = tab.bars.count > 0
if !alreadyShowingSnackbarOnThisTab {
TimerSnackBar.showAppStoreConfirmationBar(forTab: tab, appStoreURL: url)
}
return
}
// Handles custom mailto URL schemes.
if url.scheme == "mailto" {
if let mailToMetadata = url.mailToMetadata(), let mailScheme = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), mailScheme != "mailto" {
self.mailtoLinkHandler.launchMailClientForScheme(mailScheme, metadata: mailToMetadata, defaultMailtoURL: url)
} else {
UIApplication.shared.open(url, options: [:])
}
LeanPlumClient.shared.track(event: .openedMailtoLink)
decisionHandler(.cancel)
return
}
// This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We
// always allow this. Additionally, data URIs are also handled just like normal web pages.
if ["http", "https", "data", "blob", "file"].contains(url.scheme) {
if navigationAction.navigationType == .linkActivated {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
} else if navigationAction.navigationType == .backForward {
restoreSpoofedUserAgentIfRequired(webView, newRequest: navigationAction.request)
}
pendingRequests[url.absoluteString] = navigationAction.request
decisionHandler(.allow)
return
}
if !(url.scheme?.contains("firefox") ?? true) {
UIApplication.shared.open(url, options: [:]) { openedURL in
// Do not show error message for JS navigated links or redirect as it's not the result of a user action.
if !openedURL, navigationAction.navigationType == .linkActivated {
let alert = UIAlertController(title: Strings.UnableToOpenURLErrorTitle, message: Strings.UnableToOpenURLError, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.OKString, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
decisionHandler(.cancel)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let response = navigationResponse.response
let responseURL = response.url
var request: URLRequest?
if let url = responseURL {
request = pendingRequests.removeValue(forKey: url.absoluteString)
}
// We can only show this content in the web view if this web view is not pending
// download via the context menu.
let canShowInWebView = navigationResponse.canShowMIMEType && (webView != pendingDownloadWebView)
let forceDownload = webView == pendingDownloadWebView
// Check if this response should be handed off to Passbook.
if let passbookHelper = OpenPassBookHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) {
// Clear the network activity indicator since our helper is handling the request.
UIApplication.shared.isNetworkActivityIndicatorVisible = false
// Open our helper and cancel this response from the webview.
passbookHelper.open()
decisionHandler(.cancel)
return
}
if #available(iOS 12.0, *) {
// Check if this response should be displayed in a QuickLook for USDZ files.
if let previewHelper = OpenQLPreviewHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) {
// Certain files are too large to download before the preview presents, block and use a temporary document instead
if let tab = tabManager[webView] {
if navigationResponse.isForMainFrame, response.mimeType != MIMEType.HTML, let request = request {
tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request)
previewHelper.url = tab.temporaryDocument!.getURL().value as NSURL
// Open our helper and cancel this response from the webview.
previewHelper.open()
decisionHandler(.cancel)
return
} else {
tab.temporaryDocument = nil
}
}
// We don't have a temporary document, fallthrough
}
}
// Check if this response should be downloaded.
if let downloadHelper = DownloadHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) {
// Clear the network activity indicator since our helper is handling the request.
UIApplication.shared.isNetworkActivityIndicatorVisible = false
// Clear the pending download web view so that subsequent navigations from the same
// web view don't invoke another download.
pendingDownloadWebView = nil
// Open our helper and cancel this response from the webview.
downloadHelper.open()
decisionHandler(.cancel)
return
}
// If the content type is not HTML, create a temporary document so it can be downloaded and
// shared to external applications later. Otherwise, clear the old temporary document.
// NOTE: This should only happen if the request/response came from the main frame, otherwise
// we may end up overriding the "Share Page With..." action to share a temp file that is not
// representative of the contents of the web view.
if navigationResponse.isForMainFrame, let tab = tabManager[webView] {
if response.mimeType != MIMEType.HTML, let request = request {
tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request)
} else {
tab.temporaryDocument = nil
}
tab.mimeType = response.mimeType
}
// If none of our helpers are responsible for handling this response,
// just let the webview handle it as normal.
decisionHandler(.allow)
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
let error = error as NSError
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) {
return
}
if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
if let tab = tabManager[webView], tab === tabManager.selectedTab {
urlBar.currentURL = tab.url?.displayURL
}
return
}
if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL {
ErrorPageHelper(certStore: profile.certStore).loadPage(error, forUrl: url, inWebView: webView)
}
}
fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool {
if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
print("WebContent process has crashed. Trying to reload to restart it.")
webView.reload()
return true
}
return false
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// If this is a certificate challenge, see if the certificate has previously been
// accepted by the user.
let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)"
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust,
let cert = SecTrustGetCertificateAtIndex(trust, 0), profile.certStore.containsCertificate(cert, forOrigin: origin) {
completionHandler(.useCredential, URLCredential(trust: trust))
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM,
let tab = tabManager[webView] else {
completionHandler(.performDefaultHandling, nil)
return
}
// If this is a request to our local web server, use our private credentials.
if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) {
completionHandler(.useCredential, WebServer.sharedInstance.credentials)
return
}
// The challenge may come from a background tab, so ensure it's the one visible.
tabManager.selectTab(tab)
let loginsHelper = tab.getContentScript(name: LoginsHelper.name()) as? LoginsHelper
Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(.main) { res in
if let credentials = res.successValue {
completionHandler(.useCredential, credentials.credentials)
} else {
completionHandler(.rejectProtectionSpace, nil)
}
}
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
guard let tab = tabManager[webView] else { return }
tab.url = webView.url
self.scrollController.resetZoomState()
if tabManager.selectedTab === tab {
updateUIForReaderHomeStateForTab(tab)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let tab = tabManager[webView] {
navigateInTab(tab: tab, to: navigation)
// If this tab had previously crashed, wait 5 seconds before resetting
// the consecutive crash counter. This allows a successful webpage load
// without a crash to reset the consecutive crash counter in the event
// that the tab begins crashing again in the future.
if tab.consecutiveCrashes > 0 {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
if tab.consecutiveCrashes > 0 {
tab.consecutiveCrashes = 0
}
}
}
}
}
}
|
mpl-2.0
|
20a8291db0652dab22d44838910249d5
| 45.939597 | 201 | 0.648127 | 5.45412 | false | false | false | false |
gecko655/Swifter
|
Sources/Int++.swift
|
2
|
935
|
//
// Int+OAuthSwift.swift
// OAuthSwift
//
// Created by Dongri Jin on 1/28/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
extension Int {
public func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
func arrayOfBytes<T>(_ value:T, length: Int? = nil) -> [UInt8] {
let totalBytes = length ?? (MemoryLayout<T>.size * 8)
let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
valuePointer.pointee = value
let bytesPointer = valuePointer.withMemoryRebound(to: UInt8.self, capacity: 1) { $0 }
var bytes = [UInt8](repeating: 0, count: totalBytes)
for j in 0..<min(MemoryLayout<T>.size,totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
}
valuePointer.deinitialize()
valuePointer.deallocate(capacity: 1)
return bytes
}
|
mit
|
ea96d95ae17439fbb9124cb9917e5ef5
| 26.5 | 89 | 0.650267 | 3.800813 | false | false | false | false |
jamgzj/resourceObject
|
Swift/SwiftStudy/Pods/Popover/Classes/Popover.swift
|
1
|
14437
|
//
// Popover.swift
// Popover
//
// Created by corin8823 on 8/16/15.
// Copyright (c) 2015 corin8823. All rights reserved.
//
import Foundation
import UIKit
public enum PopoverOption {
case arrowSize(CGSize)
case animationIn(TimeInterval)
case animationOut(TimeInterval)
case cornerRadius(CGFloat)
case sideEdge(CGFloat)
case blackOverlayColor(UIColor)
case overlayBlur(UIBlurEffectStyle)
case type(PopoverType)
case color(UIColor)
case dismissOnBlackOverlayTap(Bool)
case showBlackOverlay(Bool)
}
@objc public enum PopoverType: Int {
case up
case down
}
open class Popover: UIView {
// custom property
open var arrowSize: CGSize = CGSize(width: 16.0, height: 10.0)
open var animationIn: TimeInterval = 0.6
open var animationOut: TimeInterval = 0.3
open var cornerRadius: CGFloat = 6.0
open var sideEdge: CGFloat = 20.0
open var popoverType: PopoverType = .down
open var blackOverlayColor: UIColor = UIColor(white: 0.0, alpha: 0.2)
open var overlayBlur: UIBlurEffect?
open var popoverColor: UIColor = UIColor.white
open var dismissOnBlackOverlayTap: Bool = true
open var showBlackOverlay: Bool = true
open var highlightFromView: Bool = false
open var highlightCornerRadius: CGFloat = 0
// custom closure
open var willShowHandler: (() -> ())?
open var willDismissHandler: (() -> ())?
open var didShowHandler: (() -> ())?
open var didDismissHandler: (() -> ())?
fileprivate var blackOverlay: UIControl = UIControl()
fileprivate var containerView: UIView!
fileprivate var contentView: UIView!
fileprivate var contentViewFrame: CGRect!
fileprivate var arrowShowPoint: CGPoint!
public init() {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.clear
self.accessibilityViewIsModal = true
}
public init(showHandler: (() -> ())?, dismissHandler: (() -> ())?) {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.clear
self.didShowHandler = showHandler
self.didDismissHandler = dismissHandler
self.accessibilityViewIsModal = true
}
public init(options: [PopoverOption]?, showHandler: (() -> ())? = nil, dismissHandler: (() -> ())? = nil) {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.clear
self.setOptions(options)
self.didShowHandler = showHandler
self.didDismissHandler = dismissHandler
self.accessibilityViewIsModal = true
}
fileprivate func setOptions(_ options: [PopoverOption]?){
if let options = options {
for option in options {
switch option {
case let .arrowSize(value):
self.arrowSize = value
case let .animationIn(value):
self.animationIn = value
case let .animationOut(value):
self.animationOut = value
case let .cornerRadius(value):
self.cornerRadius = value
case let .sideEdge(value):
self.sideEdge = value
case let .blackOverlayColor(value):
self.blackOverlayColor = value
case let .overlayBlur(style):
self.overlayBlur = UIBlurEffect(style: style)
case let .type(value):
self.popoverType = value
case let .color(value):
self.popoverColor = value
case let .dismissOnBlackOverlayTap(value):
self.dismissOnBlackOverlayTap = value
case let .showBlackOverlay(value):
self.showBlackOverlay = value
}
}
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func create() {
var frame = self.contentView.frame
frame.origin.x = self.arrowShowPoint.x - frame.size.width * 0.5
var sideEdge: CGFloat = 0.0
if frame.size.width < self.containerView.frame.size.width {
sideEdge = self.sideEdge
}
let outerSideEdge = frame.maxX - self.containerView.bounds.size.width
if outerSideEdge > 0 {
frame.origin.x -= (outerSideEdge + sideEdge)
} else {
if frame.minX < 0 {
frame.origin.x += abs(frame.minX) + sideEdge
}
}
self.frame = frame
let arrowPoint = self.containerView.convert(self.arrowShowPoint, to: self)
var anchorPoint: CGPoint
switch self.popoverType {
case .up:
frame.origin.y = self.arrowShowPoint.y - frame.height - self.arrowSize.height
anchorPoint = CGPoint(x: arrowPoint.x / frame.size.width, y: 1)
case .down:
frame.origin.y = self.arrowShowPoint.y
anchorPoint = CGPoint(x: arrowPoint.x / frame.size.width, y: 0)
}
if self.arrowSize == .zero {
anchorPoint = CGPoint(x: 0.5, y: 0.5)
}
let lastAnchor = self.layer.anchorPoint
self.layer.anchorPoint = anchorPoint
let x = self.layer.position.x + (anchorPoint.x - lastAnchor.x) * self.layer.bounds.size.width
let y = self.layer.position.y + (anchorPoint.y - lastAnchor.y) * self.layer.bounds.size.height
self.layer.position = CGPoint(x: x, y: y)
frame.size.height += self.arrowSize.height
self.frame = frame
}
fileprivate func createHighlightLayer(fromView: UIView, inView: UIView) {
let path = UIBezierPath(rect: inView.bounds)
let highlightRect = inView.convert(fromView.frame, from: fromView.superview)
let highlightPath = UIBezierPath(roundedRect: highlightRect, cornerRadius: self.highlightCornerRadius)
path.append(highlightPath)
path.usesEvenOddFillRule = true
let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = self.blackOverlayColor.cgColor
self.blackOverlay.layer.addSublayer(fillLayer)
}
open func showAsDialog(_ contentView: UIView) {
self.showAsDialog(contentView, inView: UIApplication.shared.keyWindow!)
}
open func showAsDialog(_ contentView: UIView, inView: UIView) {
self.arrowSize = .zero
let point = CGPoint(x: inView.center.x,
y: inView.center.y - contentView.frame.height / 2)
self.show(contentView, point: point, inView: inView)
}
open func show(_ contentView: UIView, fromView: UIView) {
self.show(contentView, fromView: fromView, inView: UIApplication.shared.keyWindow!)
}
open func show(_ contentView: UIView, fromView: UIView, inView: UIView) {
let point: CGPoint
switch self.popoverType {
case .up:
point = inView.convert(CGPoint(x: fromView.frame.origin.x + (fromView.frame.size.width / 2), y: fromView.frame.origin.y), from: fromView.superview)
case .down:
point = inView.convert(CGPoint(x: fromView.frame.origin.x + (fromView.frame.size.width / 2), y: fromView.frame.origin.y + fromView.frame.size.height), from: fromView.superview)
}
if self.highlightFromView {
self.createHighlightLayer(fromView: fromView, inView: inView)
}
self.show(contentView, point: point, inView: inView)
}
open func show(_ contentView: UIView, point: CGPoint) {
self.show(contentView, point: point, inView: UIApplication.shared.keyWindow!)
}
open func show(_ contentView: UIView, point: CGPoint, inView: UIView) {
if showBlackOverlay {
self.blackOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.blackOverlay.frame = inView.bounds
if let overlayBlur = self.overlayBlur {
let effectView = UIVisualEffectView(effect: overlayBlur)
effectView.frame = self.blackOverlay.bounds
effectView.isUserInteractionEnabled = false
self.blackOverlay.addSubview(effectView)
} else {
if !self.highlightFromView {
self.blackOverlay.backgroundColor = self.blackOverlayColor
}
self.blackOverlay.alpha = 0
}
inView.addSubview(self.blackOverlay)
if self.dismissOnBlackOverlayTap {
self.blackOverlay.addTarget(self, action: #selector(Popover.dismiss), for: .touchUpInside)
}
}
self.containerView = inView
self.contentView = contentView
self.contentView.backgroundColor = UIColor.clear
self.contentView.layer.cornerRadius = self.cornerRadius
self.contentView.layer.masksToBounds = true
self.arrowShowPoint = point
self.show()
}
fileprivate func show() {
self.setNeedsDisplay()
switch self.popoverType {
case .up:
self.contentView.frame.origin.y = 0.0
case .down:
self.contentView.frame.origin.y = self.arrowSize.height
}
self.addSubview(self.contentView)
self.containerView.addSubview(self)
self.create()
self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
self.willShowHandler?()
UIView.animate(withDuration: self.animationIn, delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 3,
options: UIViewAnimationOptions(),
animations: {
self.transform = CGAffineTransform.identity
}){ _ in
self.didShowHandler?()
}
UIView.animate(withDuration: self.animationIn / 3,
delay: 0,
options: .curveLinear,
animations: { _ in
self.blackOverlay.alpha = 1
}, completion: { _ in
})
}
open override func accessibilityPerformEscape() -> Bool {
self.dismiss()
return true
}
open func dismiss() {
if self.superview != nil {
self.willDismissHandler?()
UIView.animate(withDuration: self.animationOut, delay: 0,
options: UIViewAnimationOptions(),
animations: {
self.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
self.blackOverlay.alpha = 0
}){ _ in
self.contentView.removeFromSuperview()
self.blackOverlay.removeFromSuperview()
self.removeFromSuperview()
self.transform = CGAffineTransform.identity
self.didDismissHandler?()
}
}
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
let arrow = UIBezierPath()
let color = self.popoverColor
let arrowPoint = self.containerView.convert(self.arrowShowPoint, to: self)
switch self.popoverType {
case .up:
arrow.move(to: CGPoint(x: arrowPoint.x, y: self.bounds.height))
arrow.addLine(
to: CGPoint(
x: arrowPoint.x - self.arrowSize.width * 0.5,
y: isCornerLeftArrow() ? self.arrowSize.height : self.bounds.height - self.arrowSize.height
)
)
arrow.addLine(to: CGPoint(x: self.cornerRadius, y: self.bounds.height - self.arrowSize.height))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.bounds.height - self.arrowSize.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(90),
endAngle: self.radians(180),
clockwise: true)
arrow.addLine(to: CGPoint(x: 0, y: self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(180),
endAngle: self.radians(270),
clockwise: true)
arrow.addLine(to: CGPoint(x: self.bounds.width - self.cornerRadius, y: 0))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(270),
endAngle: self.radians(0),
clockwise: true)
arrow.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - self.arrowSize.height - self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.bounds.height - self.arrowSize.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(0),
endAngle: self.radians(90),
clockwise: true)
arrow.addLine(to: CGPoint(x: arrowPoint.x + self.arrowSize.width * 0.5,
y: isCornerRightArrow() ? self.arrowSize.height : self.bounds.height - self.arrowSize.height))
case .down:
arrow.move(to: CGPoint(x: arrowPoint.x, y: 0))
arrow.addLine(
to: CGPoint(
x: arrowPoint.x + self.arrowSize.width * 0.5,
y: isCornerRightArrow() ? self.arrowSize.height + self.bounds.height : self.arrowSize.height
))
arrow.addLine(to: CGPoint(x: self.bounds.width - self.cornerRadius, y: self.arrowSize.height))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.arrowSize.height + self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(270.0),
endAngle: self.radians(0),
clockwise: true)
arrow.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.bounds.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(0),
endAngle: self.radians(90),
clockwise: true)
arrow.addLine(to: CGPoint(x: 0, y: self.bounds.height))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.bounds.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(90),
endAngle: self.radians(180),
clockwise: true)
arrow.addLine(to: CGPoint(x: 0, y: self.arrowSize.height + self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(x: self.cornerRadius,
y: self.arrowSize.height + self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(180),
endAngle: self.radians(270),
clockwise: true)
arrow.addLine(to: CGPoint(x: arrowPoint.x - self.arrowSize.width * 0.5,
y: isCornerLeftArrow() ? self.arrowSize.height + self.bounds.height : self.arrowSize.height))
}
color.setFill()
arrow.fill()
}
fileprivate func isCornerLeftArrow() -> Bool {
return self.arrowShowPoint.x == self.frame.origin.x
}
fileprivate func isCornerRightArrow() -> Bool {
return self.arrowShowPoint.x == self.frame.origin.x + self.bounds.width
}
fileprivate func radians(_ degrees: CGFloat) -> CGFloat {
return (CGFloat(M_PI) * degrees / 180)
}
}
|
apache-2.0
|
1012e271400942c91f236aeb30f7bbc0
| 32.49652 | 184 | 0.656785 | 4.080554 | false | false | false | false |
JustOneLastDance/testRepo
|
GitTest/GitTest/ViewController.swift
|
1
|
942
|
//
// ViewController.swift
// GitTest
//
// Created by JustinChou on 31/07/2017.
// Copyright © 2017 JustinChou. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.lightGray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("click me!!!")
changeColor()
}
}
extension ViewController {
func changeColor() {
if view.backgroundColor == UIColor.purple {
view.backgroundColor = UIColor.blue
} else {
view.backgroundColor = UIColor.purple
}
}
}
|
mit
|
b1ca5e35ab85f53f41e0b2501a930fbb
| 21.95122 | 80 | 0.628055 | 4.77665 | false | false | false | false |
dfsilva/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthLogInViewController.swift
|
3
|
5085
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
open class AAAuthLogInViewController: AAAuthViewController {
let scrollView = UIScrollView()
let welcomeLabel = UILabel()
let field = UITextField()
let fieldLine = UIView()
var isFirstAppear = true
public override init() {
super.init(nibName: nil, bundle: nil)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: .plain, target: self, action: #selector(AAViewController.dismissController))
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewDidLoad() {
view.backgroundColor = UIColor.white
scrollView.keyboardDismissMode = .onDrag
scrollView.isScrollEnabled = true
scrollView.alwaysBounceVertical = true
welcomeLabel.font = UIFont.lightSystemFontOfSize(23)
welcomeLabel.text = AALocalized("AuthLoginTitle").replace("{app_name}", dest: ActorSDK.sharedActor().appName)
welcomeLabel.textColor = ActorSDK.sharedActor().style.authTitleColor
welcomeLabel.textAlignment = .center
if ActorSDK.sharedActor().authStrategy == .phoneOnly {
field.placeholder = AALocalized("AuthLoginPhone")
field.keyboardType = .phonePad
} else if ActorSDK.sharedActor().authStrategy == .emailOnly {
field.placeholder = AALocalized("AuthLoginEmail")
field.keyboardType = .emailAddress
} else if ActorSDK.sharedActor().authStrategy == .phoneEmail {
field.placeholder = AALocalized("AuthLoginPhoneEmail")
field.keyboardType = .default
}
field.autocapitalizationType = .none
field.autocorrectionType = .no
fieldLine.backgroundColor = ActorSDK.sharedActor().style.authSeparatorColor
fieldLine.isOpaque = false
scrollView.addSubview(welcomeLabel)
scrollView.addSubview(field)
scrollView.addSubview(fieldLine)
view.addSubview(scrollView)
super.viewDidLoad()
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
welcomeLabel.frame = CGRect(x: 15, y: 90 - 66, width: view.width - 30, height: 28)
fieldLine.frame = CGRect(x: 10, y: 200 - 66, width: view.width - 20, height: 0.5)
field.frame = CGRect(x: 20, y: 156 - 66, width: view.width - 40, height: 44)
scrollView.frame = view.bounds
scrollView.contentSize = CGSize(width: view.width, height: 240 - 66)
}
open override func nextDidTap() {
let value = field.text!.trim()
if value.length == 0 {
shakeView(field, originalX: 20)
shakeView(fieldLine, originalX: 10)
return
}
if ActorSDK.sharedActor().authStrategy == .emailOnly || ActorSDK.sharedActor().authStrategy == .phoneEmail {
if (AATools.isValidEmail(value)) {
Actor.doStartAuth(withEmail: value).startUserAction().then { (res: ACAuthStartRes!) -> () in
if res.authMode.toNSEnum() == .OTP {
self.navigateNext(AAAuthOTPViewController(email: value, transactionHash: res.transactionHash))
} else {
self.alertUser(AALocalized("AuthUnsupported").replace("{app_name}", dest: ActorSDK.sharedActor().appName))
}
}
return
}
}
if ActorSDK.sharedActor().authStrategy == .phoneOnly || ActorSDK.sharedActor().authStrategy == .phoneEmail {
let numbersSet = CharacterSet(charactersIn: "0123456789").inverted
let stripped = value.strip(numbersSet)
if let parsed = Int64(stripped) {
Actor.doStartAuth(withPhone: jlong(parsed)).startUserAction().then { (res: ACAuthStartRes!) -> () in
if res.authMode.toNSEnum() == .OTP {
let formatted = RMPhoneFormat().format("\(parsed)")!
self.navigateNext(AAAuthOTPViewController(phone: formatted, transactionHash: res.transactionHash))
} else {
self.alertUser(AALocalized("AuthUnsupported").replace("{app_name}", dest: ActorSDK.sharedActor().appName))
}
}
return
}
}
shakeView(field, originalX: 20)
shakeView(fieldLine, originalX: 10)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
field.resignFirstResponder()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isFirstAppear {
isFirstAppear = false
field.becomeFirstResponder()
}
}
}
|
agpl-3.0
|
26eccab4d6ec580a2705384388bf92fc
| 37.816794 | 182 | 0.599803 | 5.064741 | false | false | false | false |
Mark-SS/LayerPlayer
|
LayerPlayer/TilingViewForImage.swift
|
2
|
1733
|
//
// TilingViewForImage.swift
// LayerPlayer
//
// Created by Scott Gardner on 7/27/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
import UIKit
let sideLength: CGFloat = 640.0
let fileName = "windingRoad"
class TilingViewForImage: UIView {
let sideLength = CGFloat(640.0)
let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as! String
override class func layerClass() -> AnyClass {
return TiledLayer.self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let layer = self.layer as! TiledLayer
layer.contentsScale = UIScreen.mainScreen().scale
layer.tileSize = CGSize(width: sideLength, height: sideLength)
}
override func drawRect(rect: CGRect) {
let firstColumn = Int(CGRectGetMinX(rect) / sideLength)
let lastColumn = Int(CGRectGetMaxX(rect) / sideLength)
let firstRow = Int(CGRectGetMinY(rect) / sideLength)
let lastRow = Int(CGRectGetMaxY(rect) / sideLength)
for row in firstRow...lastRow {
for column in firstColumn...lastColumn {
if let tile = imageForTileAtColumn(column, row: row) {
let x = sideLength * CGFloat(column)
let y = sideLength * CGFloat(row)
let point = CGPoint(x: x, y: y)
let size = CGSize(width: sideLength, height: sideLength)
var tileRect = CGRect(origin: point, size: size)
tileRect = CGRectIntersection(bounds, tileRect)
tile.drawInRect(tileRect)
}
}
}
}
func imageForTileAtColumn(column: Int, row: Int) -> UIImage? {
let filePath = "\(cachesPath)/\(fileName)_\(column)_\(row)"
return UIImage(contentsOfFile: filePath)
}
}
|
mit
|
1c500bdf9724c06cbab5a8ee4db005b7
| 29.946429 | 109 | 0.668782 | 4.068075 | false | false | false | false |
lannik/SSImageBrowser
|
Source/SSZoomingScrollView.swift
|
1
|
10356
|
//
// SSZoomingScrollView.swift
// Pods
//
// Created by LawLincoln on 15/7/11.
//
//
import UIKit
import DACircularProgress
public class SSZoomingScrollView : UIScrollView {
public var photo: SSPhoto!
public var captionView: SSCaptionView!
public var photoImageView: SSTapDetectingImageView!
public var tapView: SSTapDetectingView!
private var progressView : DACircularProgressView!
private weak var photoBrowser: SSImageBrowser!
convenience init(aPhotoBrowser: SSImageBrowser) {
self.init(frame: CGRectZero)
photoBrowser = aPhotoBrowser
// Tap view for background
tapView = SSTapDetectingView(frame:self.bounds)
tapView.tapDelegate = self
tapView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
tapView.backgroundColor = UIColor.clearColor()
self.addSubview(tapView)
// Image view
photoImageView = SSTapDetectingImageView(frame:CGRectZero)
photoImageView.tapDelegate = self
photoImageView.backgroundColor = UIColor.clearColor()
self.addSubview(photoImageView)
let screenBound = UIScreen.mainScreen().bounds
var screenWidth = screenBound.size.width
var screenHeight = screenBound.size.height
let orientation = UIDevice.currentDevice().orientation
if orientation == UIDeviceOrientation.LandscapeLeft ||
orientation == UIDeviceOrientation.LandscapeRight {
screenWidth = screenBound.size.height
screenHeight = screenBound.size.width
}
// Progress view
progressView = DACircularProgressView(frame:CGRectMake((screenWidth-35)/2, (screenHeight-35)/2, 35.0, 35.0))
progressView.progress = 0
progressView.tag = 101
progressView.thicknessRatio = 0.1
progressView.roundedCorners = 0
progressView.trackTintColor = (aPhotoBrowser.trackTintColor != nil) ? photoBrowser.trackTintColor : UIColor(white:0.2, alpha:1)
progressView.progressTintColor = aPhotoBrowser.progressTintColor != nil ? photoBrowser.progressTintColor : UIColor(white:1.0, alpha:1)
self.addSubview(progressView)
// Setup
self.backgroundColor = UIColor.clearColor()
self.delegate = self
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.decelerationRate = UIScrollViewDecelerationRateFast
self.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
public func prepareForReuse() {
photo = nil
captionView?.removeFromSuperview()
captionView = nil
self.tag = 0
}
public func setAPhoto(aPhoto: SSPhoto) {
photoImageView.image = nil // Release image
if aPhoto != photo {
photo = aPhoto
}
displayImage()
}
public func setProgress(progress: CGFloat, forPhoto aPhoto: SSPhoto!){
if let url = photo?.photoURL?.absoluteString {
if aPhoto.photoURL.absoluteString == url {
if progressView.progress < progress {
progressView.setProgress(progress, animated: true)
}
}
} else if aPhoto.asset.identifier == photo?.asset?.identifier {
if progressView.progress < progress {
progressView.setProgress(progress, animated: true)
}
}
}
public func displayImage() {
if let p = photo {
// Reset
self.maximumZoomScale = 1
self.minimumZoomScale = 1
self.zoomScale = 1
self.contentSize = CGSizeMake(0, 0)
// Get image from browser as it handles ordering of fetching
if let img = photoBrowser.imageForPhoto(p) {
// Hide ProgressView
// progressView.alpha = 0.0f
progressView.removeFromSuperview()
// Set image
photoImageView.image = img
photoImageView.hidden = false
// Setup photo frame
var photoImageViewFrame = CGRectZero
photoImageViewFrame.origin = CGPointZero
photoImageViewFrame.size = img.size
photoImageView.frame = photoImageViewFrame
self.contentSize = photoImageViewFrame.size
// Set zoom to minimum zoom
setMaxMinZoomScalesForCurrentBounds()
} else {
// Hide image view
photoImageView.hidden = true
progressView.alpha = 1.0
}
self.setNeedsLayout()
}
}
public func displayImageFailure() {
progressView.removeFromSuperview()
}
public func setMaxMinZoomScalesForCurrentBounds() {
// Reset
self.maximumZoomScale = 1
self.minimumZoomScale = 1
self.zoomScale = 1
// fail
if photoImageView.image == nil {
return
}
// Sizes
let boundsSize = self.bounds.size
let imageSize = photoImageView.frame.size
// Calculate Min
let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise
let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise
let minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible
// If image is smaller than the screen then ensure we show it at
// min scale of 1
if xScale > 1 && yScale > 1 {
//minScale = 1.0
}
// Calculate Max
var maxScale:CGFloat = 4.0 // Allow double scale
// on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the
// maximum zoom scale to 0.5.
maxScale = maxScale / UIScreen.mainScreen().scale
if (maxScale < minScale) {
maxScale = minScale * 2
}
// Set
self.maximumZoomScale = maxScale
self.minimumZoomScale = minScale
self.zoomScale = minScale
// Reset position
photoImageView.frame = CGRectMake(0, 0, photoImageView.frame.size.width, photoImageView.frame.size.height)
self.setNeedsLayout()
}
public override func layoutSubviews() {
// Update tap view frame
tapView.frame = self.bounds
// Super
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen
let boundsSize = self.bounds.size
var frameToCenter = photoImageView.frame
// Horizontally
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2.0)
} else {
frameToCenter.origin.x = 0
}
// Vertically
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2.0)
} else {
frameToCenter.origin.y = 0
}
// Center
if !CGRectEqualToRect(photoImageView.frame, frameToCenter) {
photoImageView.frame = frameToCenter
}
}
}
// MARK: - UIScrollViewDelegate
extension SSZoomingScrollView: UIScrollViewDelegate {
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return photoImageView
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
photoBrowser.cancelControlHiding()
}
public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
photoBrowser.cancelControlHiding()
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
photoBrowser.hideControlsAfterDelay()
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
extension SSZoomingScrollView: SSTapDetectingViewDelegate, SSTapDetectingImageViewDelegate {
private func handleSingleTap(touchPoint: CGPoint) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
self.photoBrowser.toggleControls()
}
}
private func handleDoubleTap(touchPoint: CGPoint) {
// Cancel any single tap handling
NSObject.cancelPreviousPerformRequestsWithTarget(photoBrowser)
// Zoom
if self.zoomScale == self.maximumZoomScale {
self.setZoomScale(self.minimumZoomScale, animated: true)
} else {
self.zoomToRect(CGRectMake(touchPoint.x, touchPoint.y, 1, 1), animated: true)
}
// Delay controls
photoBrowser.hideControlsAfterDelay()
}
public func imageView(imageView: UIImageView, singleTapDetected touch: UITouch) {
handleSingleTap(touch.locationInView(imageView))
}
public func imageView(imageView: UIImageView, doubleTapDetected touch: UITouch) {
handleDoubleTap(touch.locationInView(imageView))
}
public func imageView(imageView: UIImageView, tripleTapDetected touch: UITouch) {
}
public func view(view: UIView, singleTapDetected touch: UITouch) {
handleSingleTap(touch.locationInView(view))
}
public func view(view: UIView, doubleTapDetected touch: UITouch) {
handleDoubleTap(touch.locationInView(view))
}
public func view(view: UIView, tripleTapDetected touch: UITouch) {
}
}
|
mit
|
50038eccb45b0bf662e0396b8233d521
| 33.408638 | 145 | 0.611336 | 5.66211 | false | false | false | false |
wj2061/ios7ptl-swift3.0
|
ch20-Transition/InteractiveTransition/CustomTransitionsDemo/SCAnimation.swift
|
1
|
1562
|
//
// SCAnimation.swift
// InteractiveCustomTransitionsDemo
//
// Created by wj on 15/11/21.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class SCAnimation: NSObject, UIViewControllerAnimatedTransitioning {
var dismissal = false
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
print("an")
let src = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let dest = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
var f = src.view.frame
let originalSourceRect = f
f.origin.y = f.size.height
UIView.animate(withDuration: 0.5, animations: { () -> Void in
src.view.frame = f
}, completion: { (_) -> Void in
src.view.alpha = 0
dest.view.alpha = 0
dest.view.frame = f
transitionContext.containerView.addSubview(dest.view)
UIView.animate(withDuration: 0.5, animations: { () -> Void in
dest.view.alpha = 1
dest.view.frame = originalSourceRect
}, completion: { (_ ) -> Void in
src.view.alpha = 1
transitionContext.completeTransition(true)
})
})
}
}
|
mit
|
792f4c61f037b525b4b1eeeaaab14660
| 32.891304 | 109 | 0.586273 | 5.320819 | false | false | false | false |
PureSwift/SDL
|
Sources/SDL/BitMaskOption.swift
|
1
|
4451
|
//
// BitMaskOption.swift
// SDL
//
// Created by Alsey Coleman Miller on 6/6/17.
//
/// Enum that represents a bit mask flag / option.
///
/// Basically `Swift.OptionSet` for enums.
public protocol BitMaskOption: RawRepresentable, Hashable, CaseIterable where RawValue: FixedWidthInteger { }
public extension Sequence where Element: BitMaskOption {
/// Convert Swift enums for bit mask options into their raw values OR'd.
var rawValue: Element.RawValue {
@inline(__always)
get { return reduce(0, { $0 | $1.rawValue }) }
}
}
public extension BitMaskOption {
/// Whether the enum case is present in the raw value.
@inline(__always)
func isContained(in rawValue: RawValue) -> Bool {
return (self.rawValue & rawValue) != 0
}
@inline(__always)
static func from(rawValue: RawValue) -> [Self] {
return Self.allCases.filter { $0.isContained(in: rawValue) }
}
}
// MARK: - BitMaskOptionSet
/// Integer-backed array type for `BitMaskOption`.
///
/// The elements are packed in the integer with bitwise math and stored on the stack.
public struct BitMaskOptionSet <Element: BitMaskOption>: RawRepresentable {
public typealias RawValue = Element.RawValue
public private(set) var rawValue: RawValue
@inline(__always)
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
@inline(__always)
public init() {
self.rawValue = 0
}
public static var all: BitMaskOptionSet<Element> {
return BitMaskOptionSet<Element>(rawValue: Element.allCases.rawValue)
}
@inline(__always)
public mutating func insert(_ element: Element) {
rawValue = rawValue | element.rawValue
}
@discardableResult
public mutating func remove(_ element: Element) -> Bool {
guard contains(element) else { return false }
rawValue = rawValue & ~element.rawValue
return true
}
@inline(__always)
public mutating func removeAll() {
self.rawValue = 0
}
@inline(__always)
public func contains(_ element: Element) -> Bool {
return element.isContained(in: rawValue)
}
public func contains <S: Sequence> (_ other: S) -> Bool where S.Iterator.Element == Element {
for element in other {
guard element.isContained(in: rawValue)
else { return false }
}
return true
}
public var count: Int {
return Element.allCases.reduce(0, { $0 + ($1.isContained(in: rawValue) ? 1 : 0) })
}
public var isEmpty: Bool {
return rawValue == 0
}
}
// MARK: - Sequence Conversion
public extension BitMaskOptionSet {
init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element {
self.rawValue = sequence.rawValue
}
}
// MARK: - Equatable
extension BitMaskOptionSet: Equatable {
public static func == (lhs: BitMaskOptionSet, rhs: BitMaskOptionSet) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
// MARK: - CustomStringConvertible
extension BitMaskOptionSet: CustomStringConvertible {
public var description: String {
return Element.from(rawValue: rawValue)
.sorted(by: { $0.rawValue < $1.rawValue })
.description
}
}
// MARK: - Hashable
extension BitMaskOptionSet: Hashable {
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
rawValue.hash(into: &hasher)
}
#else
public var hashValue: Int {
return rawValue.hashValue
}
#endif
}
// MARK: - ExpressibleByArrayLiteral
extension BitMaskOptionSet: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
// MARK: - ExpressibleByIntegerLiteral
extension BitMaskOptionSet: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt64) {
self.init(rawValue: numericCast(value))
}
}
// MARK: - Sequence
extension BitMaskOptionSet: Sequence {
public func makeIterator() -> IndexingIterator<[Element]> {
return Element.from(rawValue: rawValue).makeIterator()
}
}
|
mit
|
605d4b482b694cc775cc4547146254ce
| 21.825641 | 109 | 0.602786 | 4.705074 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/ContextCommandRowItem.swift
|
1
|
4172
|
//
// ContextCommandRowItem.swift
// TelegramMac
//
// Created by keepcoder on 29/12/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import Postbox
import TelegramCore
import SwiftSignalKit
class ContextCommandRowItem: TableRowItem {
fileprivate let _stableId:Int64
fileprivate let account: Account
let command:PeerCommand
private let title:TextViewLayout
private let desc:TextViewLayout
private let titleSelected:TextViewLayout
private let descSelected:TextViewLayout
override var stableId: AnyHashable {
return _stableId
}
init(_ initialSize:NSSize, _ account:Account, _ command:PeerCommand, _ index:Int64) {
_stableId = index
self.command = command
self.account = account
title = TextViewLayout(.initialize(string: "/" + command.command.text, color: theme.colors.text, font: .medium(.text)), maximumNumberOfLines: 1, truncationType: .end)
desc = TextViewLayout(.initialize(string: command.command.description, color: theme.colors.grayText, font: .normal(.text)), maximumNumberOfLines: 1, truncationType: .end)
titleSelected = TextViewLayout(.initialize(string: "/" + command.command.text, color: theme.colors.underSelectedColor, font: .medium(.text)), maximumNumberOfLines: 1, truncationType: .end)
descSelected = TextViewLayout(.initialize(string: command.command.description, color: theme.colors.underSelectedColor, font: .normal(.text)), maximumNumberOfLines: 1, truncationType: .end)
super.init(initialSize)
_ = makeSize(initialSize.width, oldWidth: initialSize.width)
}
override var height: CGFloat {
return 40
}
override func viewClass() -> AnyClass {
return ContextCommandRowView.self
}
override func makeSize(_ width: CGFloat, oldWidth:CGFloat) -> Bool {
let success = super.makeSize(width, oldWidth: oldWidth)
title.measure(width: width - 60)
desc.measure(width: width - 60)
titleSelected.measure(width: width - 60)
descSelected.measure(width: width - 60)
return success
}
var ctxTitle:TextViewLayout {
return isSelected ? titleSelected : title
}
var ctxDesc:TextViewLayout {
return isSelected ? descSelected : desc
}
}
class ContextCommandRowView : TableRowView {
private let textView:TextView = TextView()
private let descView:TextView = TextView()
private let photoView:AvatarControl = AvatarControl(font: .avatar(.title))
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
layerContentsRedrawPolicy = .onSetNeedsDisplay
textView.userInteractionEnabled = false
descView.userInteractionEnabled = false
photoView.userInteractionEnabled = false
addSubview(textView)
addSubview(descView)
addSubview(photoView)
photoView.frame = NSMakeRect(10, 5, 30, 30)
}
override func layout() {
super.layout()
if let item = item as? ContextCommandRowItem {
textView.update(item.ctxTitle, origin:NSMakePoint(50, floorToScreenPixels(backingScaleFactor, frame.height / 2 - item.ctxTitle.layoutSize.height)))
descView.update(item.ctxDesc, origin:NSMakePoint(50, floorToScreenPixels(backingScaleFactor, frame.height / 2)))
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var backdorColor: NSColor {
if let item = item {
return item.isSelected ? theme.colors.accentSelect : theme.colors.background
} else {
return theme.colors.background
}
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item, animated:animated)
if let item = item as? ContextCommandRowItem {
photoView.setPeer(account: item.account, peer: item.command.peer)
}
textView.background = backdorColor
descView.background = backdorColor
needsLayout = true
}
}
|
gpl-2.0
|
d3c135879ca7699f2e4c4dfaaccb9288
| 34.05042 | 196 | 0.67298 | 4.729025 | false | false | false | false |
yanqingsmile/RNAi
|
RNAi/Constants.swift
|
1
|
1205
|
//
// Constants.swift
// RNAi
//
// Created by Vivian Liu on 1/19/17.
// Copyright © 2017 Vivian Liu. All rights reserved.
//
import Foundation
struct CellIdentifier {
static let masterGeneCellIdentifier = "GeneCellIdentifier"
static let masterHeaderCellIdentifier = "MasterHeaderCellIdentifier"
static let detailCellIdentifier = "siRNADetailIdentifier"
static let detailHeaderCellIdentifier = "DetailHeaderCellIdentifier"
static let savedCellIdentifier = "SavedCellIdentifier"
static let savedHeaderIdentifier = "SavedHeaderCellIdentifier"
}
struct TextLabel {
static let headerCellTextLabel = "Gene Name"
static let headerCellDetailTextLabel = "Accession Number"
}
struct SegueIdentifier {
static let showDetailFromMasterToDetail = "ShowDetailFromMaster"
static let showDetailFromSavedToDetail = "showDetailFromSaved"
}
struct ConstantString {
static let userDefaultsKey = "savedGeneNames"
static let geneNCBIUrlPrefix = "https://www.ncbi.nlm.nih.gov/gene/?term="
static let genomeRNAiURLPrefix = "http://genomernai.dkfz.de/v16/reagentdetails/"
static let unSavedImageName = "emptyHeart"
static let savedImageName = "filledHeart"
}
|
mit
|
e4cc0812f31c117a9380a3bb738367a8
| 31.540541 | 84 | 0.766611 | 4.040268 | false | false | false | false |
studyYF/SingleSugar
|
SingleSugar/SingleSugar/AppDelegate.swift
|
1
|
2523
|
//
// AppDelegate.swift
// SingleSugar
//
// Created by YangFan on 2017/4/14.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window?.rootViewController = YFTabBarController()
//设置导航栏和标签栏初始化值
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = kMainColor
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
UITabBar.appearance().tintColor = kMainColor
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:.
}
}
|
apache-2.0
|
b3242b09b4d3b4dd9f07d94c541d9d1a
| 45.185185 | 285 | 0.742983 | 5.759815 | false | false | false | false |
JoergFiedler/Spotify4Me
|
Spotify/DataSupporter.swift
|
1
|
2216
|
//
// DataSupporter.swift
// Spotify
//
// Created by Lucas Backert on 02.11.14.
// Copyright (c) 2014 Lucas Backert. All rights reserved.
//
import Foundation
struct SpotifyApi {
static let osaStart = "tell application \"Spotify\" to"
static func getState() ->String{
return executeScript("player state")
}
static func getTitle() -> String{
return executeScript("name of current track")
}
static func getAlbum() -> String{
return executeScript("album of current track")
}
static func getArtist() -> String{
return executeScript("artist of current track")
}
static func getCover() -> NSData{
var result: NSData = NSData()
let script = NSAppleScript(source: "\(osaStart) artwork of current track")
var errorInfo: NSDictionary?
var descriptor = script?.executeAndReturnError(&errorInfo)
if(descriptor != nil){
result = descriptor!.data
}
return result
}
static func getVolume() -> String{
return executeScript("sound volume")
}
static func setVolume(level: Int){
executeScript("set sound volume to \(level)")
}
static func toNextTrack(){
executeScript("next track")
}
static func toPreviousTrack(){
executeScript("previous track")
}
static func toPlayPause(){
executeScript("playpause")
}
static func executeScript(phrase: String) -> String{
var output = ""
let script = NSAppleScript(source: "\(osaStart) \(phrase)" )
var errorInfo: NSDictionary?
var descriptor = script?.executeAndReturnError(&errorInfo)
//println("err: getState \(errorInfo?.description))")
if(descriptor?.stringValue != nil){
output = descriptor!.stringValue!
//println("descriptor: \(descriptor!))")
}
return output
}
// NOT USED AT THE MOMENT
static func getDuration() -> String{
return executeScript("duration of current track")
}
static func getPosition() -> String{
return executeScript("position of current track")
}
}
|
mit
|
45338554685488c9b42e11990068f458
| 26.358025 | 82 | 0.602437 | 4.838428 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie
|
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Me-我/Controller/XMGWebViewController.swift
|
1
|
1859
|
//
// XMGWebViewController.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/3.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
import NJKWebViewProgress
class XMGWebViewController: UIViewController {
/** 链接 */
var url: String?
/** 进度代理对象 */
var progress: NJKWebViewProgress?
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var goBackItem: UIBarButtonItem!
@IBOutlet weak var goForwardItem: UIBarButtonItem!
@IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
self.progress = NJKWebViewProgress()
self.webView.delegate = self.progress;
weak var weakSelf = self
self.progress!.progressBlock = {(progress) in
if let weakSelf = weakSelf {
weakSelf.progressView.progress = progress;
weakSelf.progressView.hidden = (progress == 1.0);
}
}
self.progress!.webViewProxyDelegate = self;
self.webView.loadRequest(NSURLRequest(URL: NSURL(string: self.url!)!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func refresh(sender: AnyObject) {
self.webView.reload()
}
@IBAction func goBack(sender: AnyObject) {
self.webView.goBack()
}
@IBAction func goForward(sender: AnyObject) {
self.webView.goForward()
}
}
extension XMGWebViewController :UIWebViewDelegate{
func webViewDidFinishLoad(webView: UIWebView) {
self.goBackItem.enabled = webView.canGoBack;
self.goForwardItem.enabled = webView.canGoForward;
}
}
|
apache-2.0
|
216b795eeb92452b323237c1cbfa63ed
| 22.792208 | 78 | 0.619541 | 4.87234 | false | false | false | false |
ra1028/RAReorderableLayout
|
RAReorderableLayout/RAReorderableLayout.swift
|
1
|
23511
|
//
// RAReorderableLayout.swift
// RAReorderableLayout
//
// Created by Ryo Aoyama on 10/12/14.
// Copyright (c) 2014 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol RAReorderableLayoutDelegate: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, at: IndexPath, willMoveTo toIndexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, at: IndexPath, didMoveTo toIndexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, allowMoveAt indexPath: IndexPath) -> Bool
func collectionView(_ collectionView: UICollectionView, at: IndexPath, canMoveTo: IndexPath) -> Bool
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, willBeginDraggingItemAt indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, didBeginDraggingItemAt indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, willEndDraggingItemTo indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, didEndDraggingItemTo indexPath: IndexPath)
}
public protocol RAReorderableLayoutDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
func collectionView(_ collectionView: UICollectionView, reorderingItemAlphaInSection section: Int) -> CGFloat
func scrollTrigerEdgeInsetsInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets
func scrollTrigerPaddingInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets
func scrollSpeedValueInCollectionView(_ collectionView: UICollectionView) -> CGFloat
}
public extension RAReorderableLayoutDataSource {
func collectionView(_ collectionView: UICollectionView, reorderingItemAlphaInSection section: Int) -> CGFloat {
return 0
}
func scrollTrigerEdgeInsetsInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets {
return .init(top: 100, left: 100, bottom: 100, right: 100)
}
func scrollTrigerPaddingInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets {
return .zero
}
func scrollSpeedValueInCollectionView(_ collectionView: UICollectionView) -> CGFloat {
return 10
}
}
public extension RAReorderableLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, at: IndexPath, willMoveTo toIndexPath: IndexPath) {}
func collectionView(_ collectionView: UICollectionView, at: IndexPath, didMoveTo toIndexPath: IndexPath) {}
func collectionView(_ collectionView: UICollectionView, allowMoveAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, at: IndexPath, canMoveTo: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, willBeginDraggingItemAt indexPath: IndexPath) {}
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, didBeginDraggingItemAt indexPath: IndexPath) {}
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, willEndDraggingItemTo indexPath: IndexPath) {}
func collectionView(_ collectionView: UICollectionView, collectionView layout: RAReorderableLayout, didEndDraggingItemTo indexPath: IndexPath) {}
}
open class RAReorderableLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate {
fileprivate enum direction {
case toTop
case toEnd
case stay
fileprivate func scrollValue(_ speedValue: CGFloat, percentage: CGFloat) -> CGFloat {
var value: CGFloat = 0.0
switch self {
case .toTop:
value = -speedValue
case .toEnd:
value = speedValue
case .stay:
return 0
}
let proofedPercentage: CGFloat = max(min(1.0, percentage), 0)
return value * proofedPercentage
}
}
public weak var delegate: RAReorderableLayoutDelegate? {
get { return collectionView?.delegate as? RAReorderableLayoutDelegate }
set { collectionView?.delegate = delegate }
}
public weak var dataSource: RAReorderableLayoutDataSource? {
set { collectionView?.dataSource = dataSource }
get { return collectionView?.dataSource as? RAReorderableLayoutDataSource }
}
fileprivate var displayLink: CADisplayLink?
fileprivate var longPress: UILongPressGestureRecognizer?
fileprivate var panGesture: UIPanGestureRecognizer?
fileprivate var continuousScrollDirection: direction = .stay
fileprivate var cellFakeView: RACellFakeView?
fileprivate var panTranslation: CGPoint?
fileprivate var fakeCellCenter: CGPoint?
fileprivate var trigerInsets = UIEdgeInsetsMake(100.0, 100.0, 100.0, 100.0)
fileprivate var trigerPadding = UIEdgeInsets.zero
fileprivate var scrollSpeedValue: CGFloat = 10.0
fileprivate var offsetFromTop: CGFloat {
let contentOffset = collectionView!.contentOffset
return scrollDirection == .vertical ? contentOffset.y : contentOffset.x
}
fileprivate var insetsTop: CGFloat {
let contentInsets = collectionView!.contentInset
return scrollDirection == .vertical ? contentInsets.top : contentInsets.left
}
fileprivate var insetsEnd: CGFloat {
let contentInsets = collectionView!.contentInset
return scrollDirection == .vertical ? contentInsets.bottom : contentInsets.right
}
fileprivate var contentLength: CGFloat {
let contentSize = collectionView!.contentSize
return scrollDirection == .vertical ? contentSize.height : contentSize.width
}
fileprivate var collectionViewLength: CGFloat {
let collectionViewSize = collectionView!.bounds.size
return scrollDirection == .vertical ? collectionViewSize.height : collectionViewSize.width
}
fileprivate var fakeCellTopEdge: CGFloat? {
if let fakeCell = cellFakeView {
return scrollDirection == .vertical ? fakeCell.frame.minY : fakeCell.frame.minX
}
return nil
}
fileprivate var fakeCellEndEdge: CGFloat? {
if let fakeCell = cellFakeView {
return scrollDirection == .vertical ? fakeCell.frame.maxY : fakeCell.frame.maxX
}
return nil
}
fileprivate var triggerInsetTop: CGFloat {
return scrollDirection == .vertical ? trigerInsets.top : trigerInsets.left
}
fileprivate var triggerInsetEnd: CGFloat {
return scrollDirection == .vertical ? trigerInsets.top : trigerInsets.left
}
fileprivate var triggerPaddingTop: CGFloat {
return scrollDirection == .vertical ? trigerPadding.top : trigerPadding.left
}
fileprivate var triggerPaddingEnd: CGFloat {
return scrollDirection == .vertical ? trigerPadding.bottom : trigerPadding.right
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureObserver()
}
public override init() {
super.init()
configureObserver()
}
deinit {
removeObserver(self, forKeyPath: "collectionView")
}
override open func prepare() {
super.prepare()
// scroll trigger insets
if let insets = dataSource?.scrollTrigerEdgeInsetsInCollectionView(self.collectionView!) {
trigerInsets = insets
}
// scroll trier padding
if let padding = dataSource?.scrollTrigerPaddingInCollectionView(self.collectionView!) {
trigerPadding = padding
}
// scroll speed value
if let speed = dataSource?.scrollSpeedValueInCollectionView(collectionView!) {
scrollSpeedValue = speed
}
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesArray = super.layoutAttributesForElements(in: rect) else { return nil }
attributesArray.filter {
$0.representedElementCategory == .cell
}.filter {
$0.indexPath == (cellFakeView?.indexPath)
}.forEach {
// reordering cell alpha
$0.alpha = dataSource?.collectionView(self.collectionView!, reorderingItemAlphaInSection: $0.indexPath.section) ?? 0
}
return attributesArray
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "collectionView" {
setUpGestureRecognizers()
}else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
fileprivate func configureObserver() {
addObserver(self, forKeyPath: "collectionView", options: [], context: nil)
}
fileprivate func setUpDisplayLink() {
guard displayLink == nil else {
return
}
displayLink = CADisplayLink(target: self, selector: #selector(RAReorderableLayout.continuousScroll))
displayLink!.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
fileprivate func invalidateDisplayLink() {
continuousScrollDirection = .stay
displayLink?.invalidate()
displayLink = nil
}
// begein scroll
fileprivate func beginScrollIfNeeded() {
if cellFakeView == nil { return }
if fakeCellTopEdge! <= offsetFromTop + triggerPaddingTop + triggerInsetTop {
continuousScrollDirection = .toTop
setUpDisplayLink()
} else if fakeCellEndEdge! >= offsetFromTop + collectionViewLength - triggerPaddingEnd - triggerInsetEnd {
continuousScrollDirection = .toEnd
setUpDisplayLink()
} else {
invalidateDisplayLink()
}
}
// move item
fileprivate func moveItemIfNeeded() {
guard let fakeCell = cellFakeView,
let atIndexPath = fakeCell.indexPath,
let toIndexPath = collectionView!.indexPathForItem(at: fakeCell.center) else {
return
}
guard atIndexPath != toIndexPath else { return }
// can move item
if let canMove = delegate?.collectionView(collectionView!, at: atIndexPath, canMoveTo: toIndexPath) , !canMove {
return
}
// will move item
delegate?.collectionView(collectionView!, at: atIndexPath, willMoveTo: toIndexPath)
let attribute = self.layoutAttributesForItem(at: toIndexPath)!
collectionView!.performBatchUpdates({
fakeCell.indexPath = toIndexPath
fakeCell.cellFrame = attribute.frame
fakeCell.changeBoundsIfNeeded(attribute.bounds)
self.collectionView!.deleteItems(at: [atIndexPath])
self.collectionView!.insertItems(at: [toIndexPath])
// did move item
self.delegate?.collectionView(self.collectionView!, at: atIndexPath, didMoveTo: toIndexPath)
}, completion:nil)
}
internal func continuousScroll() {
guard let fakeCell = cellFakeView else { return }
let percentage = calcTriggerPercentage()
var scrollRate = continuousScrollDirection.scrollValue(self.scrollSpeedValue, percentage: percentage)
let offset = offsetFromTop
let length = collectionViewLength
if contentLength + insetsTop + insetsEnd <= length {
return
}
if offset + scrollRate <= -insetsTop {
scrollRate = -insetsTop - offset
} else if offset + scrollRate >= contentLength + insetsEnd - length {
scrollRate = contentLength + insetsEnd - length - offset
}
collectionView!.performBatchUpdates({
if self.scrollDirection == .vertical {
self.fakeCellCenter?.y += scrollRate
fakeCell.center.y = self.fakeCellCenter!.y + self.panTranslation!.y
self.collectionView?.contentOffset.y += scrollRate
} else {
self.fakeCellCenter?.x += scrollRate
fakeCell.center.x = self.fakeCellCenter!.x + self.panTranslation!.x
self.collectionView?.contentOffset.x += scrollRate
}
}, completion: nil)
moveItemIfNeeded()
}
fileprivate func calcTriggerPercentage() -> CGFloat {
guard cellFakeView != nil else { return 0 }
let offset = offsetFromTop
let offsetEnd = offsetFromTop + collectionViewLength
let paddingEnd = triggerPaddingEnd
var percentage: CGFloat = 0
if self.continuousScrollDirection == .toTop {
if let fakeCellEdge = fakeCellTopEdge {
percentage = 1.0 - ((fakeCellEdge - (offset + triggerPaddingTop)) / triggerInsetTop)
}
}else if continuousScrollDirection == .toEnd {
if let fakeCellEdge = fakeCellEndEdge {
percentage = 1.0 - (((insetsTop + offsetEnd - paddingEnd) - (fakeCellEdge + insetsTop)) / triggerInsetEnd)
}
}
percentage = min(1.0, percentage)
percentage = max(0, percentage)
return percentage
}
// gesture recognizers
fileprivate func setUpGestureRecognizers() {
guard let collectionView = collectionView else { return }
guard longPress == nil && panGesture == nil else {return }
longPress = UILongPressGestureRecognizer(target: self, action: #selector(RAReorderableLayout.handleLongPress(_:)))
panGesture = UIPanGestureRecognizer(target: self, action: #selector(RAReorderableLayout.handlePanGesture(_:)))
longPress?.delegate = self
panGesture?.delegate = self
panGesture?.maximumNumberOfTouches = 1
let gestures: NSArray! = collectionView.gestureRecognizers as NSArray!
gestures.enumerateObjects(options: []) { gestureRecognizer, index, finish in
if gestureRecognizer is UILongPressGestureRecognizer {
(gestureRecognizer as AnyObject).require(toFail: self.longPress!)
}
collectionView.addGestureRecognizer(self.longPress!)
collectionView.addGestureRecognizer(self.panGesture!)
}
}
open func cancelDrag() {
cancelDrag(nil)
}
fileprivate func cancelDrag(_ toIndexPath: IndexPath!) {
guard cellFakeView != nil else { return }
// will end drag item
self.delegate?.collectionView(self.collectionView!, collectionView: self, willEndDraggingItemTo: toIndexPath)
collectionView?.scrollsToTop = true
fakeCellCenter = nil
invalidateDisplayLink()
cellFakeView!.pushBackView {
self.cellFakeView!.removeFromSuperview()
self.cellFakeView = nil
self.invalidateLayout()
// did end drag item
self.delegate?.collectionView(self.collectionView!, collectionView: self, didEndDraggingItemTo: toIndexPath)
}
}
// long press gesture
internal func handleLongPress(_ longPress: UILongPressGestureRecognizer!) {
let location = longPress.location(in: collectionView)
var indexPath: IndexPath? = collectionView?.indexPathForItem(at: location)
if let cellFakeView = cellFakeView {
indexPath = cellFakeView.indexPath
}
if indexPath == nil { return }
switch longPress.state {
case .began:
// will begin drag item
delegate?.collectionView(self.collectionView!, collectionView: self, willBeginDraggingItemAt: indexPath!)
collectionView?.scrollsToTop = false
let currentCell = collectionView?.cellForItem(at: indexPath!)
cellFakeView = RACellFakeView(cell: currentCell!)
cellFakeView!.indexPath = indexPath
cellFakeView!.originalCenter = currentCell?.center
cellFakeView!.cellFrame = layoutAttributesForItem(at: indexPath!)!.frame
collectionView?.addSubview(cellFakeView!)
fakeCellCenter = cellFakeView!.center
invalidateLayout()
cellFakeView?.pushFowardView()
// did begin drag item
delegate?.collectionView(self.collectionView!, collectionView: self, didBeginDraggingItemAt: indexPath!)
case .cancelled, .ended:
cancelDrag(indexPath)
default:
break
}
}
// pan gesture
func handlePanGesture(_ pan: UIPanGestureRecognizer!) {
panTranslation = pan.translation(in: collectionView!)
if let cellFakeView = cellFakeView,
let fakeCellCenter = fakeCellCenter,
let panTranslation = panTranslation {
switch pan.state {
case .changed:
cellFakeView.center.x = fakeCellCenter.x + panTranslation.x
cellFakeView.center.y = fakeCellCenter.y + panTranslation.y
beginScrollIfNeeded()
moveItemIfNeeded()
case .cancelled, .ended:
invalidateDisplayLink()
default:
break
}
}
}
// gesture recognize delegate
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// allow move item
let location = gestureRecognizer.location(in: collectionView)
if let indexPath = collectionView?.indexPathForItem(at: location) ,
delegate?.collectionView(self.collectionView!, allowMoveAt: indexPath) == false {
return false
}
switch gestureRecognizer {
case longPress:
return !(collectionView!.panGestureRecognizer.state != .possible && collectionView!.panGestureRecognizer.state != .failed)
case panGesture:
return !(longPress!.state == .possible || longPress!.state == .failed)
default:
return true
}
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
switch gestureRecognizer {
case panGesture:
return otherGestureRecognizer == longPress
case collectionView?.panGestureRecognizer:
return (longPress!.state != .possible || longPress!.state != .failed)
default:
return true
}
}
}
private class RACellFakeView: UIView {
weak var cell: UICollectionViewCell?
var cellFakeImageView: UIImageView?
var cellFakeHightedView: UIImageView?
fileprivate var indexPath: IndexPath?
fileprivate var originalCenter: CGPoint?
fileprivate var cellFrame: CGRect?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(cell: UICollectionViewCell) {
super.init(frame: cell.frame)
self.cell = cell
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowOpacity = 0
layer.shadowRadius = 5.0
layer.shouldRasterize = false
cellFakeImageView = UIImageView(frame: self.bounds)
cellFakeImageView?.contentMode = UIViewContentMode.scaleAspectFill
cellFakeImageView?.autoresizingMask = [.flexibleWidth , .flexibleHeight]
cellFakeHightedView = UIImageView(frame: self.bounds)
cellFakeHightedView?.contentMode = UIViewContentMode.scaleAspectFill
cellFakeHightedView?.autoresizingMask = [.flexibleWidth , .flexibleHeight]
cell.isHighlighted = true
cellFakeHightedView?.image = getCellImage()
cell.isHighlighted = false
cellFakeImageView?.image = getCellImage()
addSubview(cellFakeImageView!)
addSubview(cellFakeHightedView!)
}
func changeBoundsIfNeeded(_ bounds: CGRect) {
if self.bounds.equalTo(bounds) { return }
UIView.animate(
withDuration: 0.3,
delay: 0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: {
self.bounds = bounds
},
completion: nil
)
}
func pushFowardView() {
UIView.animate(
withDuration: 0.3,
delay: 0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: {
self.center = self.originalCenter!
self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
self.cellFakeHightedView!.alpha = 0;
let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
shadowAnimation.fromValue = 0
shadowAnimation.toValue = 0.7
shadowAnimation.isRemovedOnCompletion = false
shadowAnimation.fillMode = kCAFillModeForwards
self.layer.add(shadowAnimation, forKey: "applyShadow")
},
completion: { _ in
self.cellFakeHightedView?.removeFromSuperview()
}
)
}
func pushBackView(_ completion: (()->Void)?) {
UIView.animate(
withDuration: 0.3,
delay: 0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: {
self.transform = CGAffineTransform.identity
self.frame = self.cellFrame!
let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
shadowAnimation.fromValue = 0.7
shadowAnimation.toValue = 0
shadowAnimation.isRemovedOnCompletion = false
shadowAnimation.fillMode = kCAFillModeForwards
self.layer.add(shadowAnimation, forKey: "removeShadow")
},
completion: { _ in
completion?()
}
)
}
fileprivate func getCellImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(cell!.bounds.size, false, UIScreen.main.scale * 2)
defer { UIGraphicsEndImageContext() }
cell!.drawHierarchy(in: cell!.bounds, afterScreenUpdates: true)
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
// Convenience method
private func ~= (obj:NSObjectProtocol?, r:UIGestureRecognizer) -> Bool {
return r.isEqual(obj)
}
|
mit
|
7323ada4b186d7fea8eb30dcefc1e9ca
| 37.733114 | 162 | 0.643486 | 5.714876 | false | false | false | false |
arevaloarboled/Moviles
|
Proyecto/iOS/Messages/Pods/Restofire/Sources/Authenticable.swift
|
2
|
1368
|
//
// Authenticable.swift
// Restofire
//
// Created by Rahul Katariya on 23/04/16.
// Copyright © 2016 AarKay. All rights reserved.
//
import Foundation
/// Represents an `Authentication` that is associated with `Configurable`.
/// `configuration.authentication` by default.
///
/// ### Create custom authenticable
/// ```swift
/// protocol HTTPBinAuthenticable: Authenticable { }
///
/// extension HTTPBinAuthenticable {
///
/// var configuration: Configuration {
/// var authentication = Authentication()
/// authentication.credential = NSURLCredential(user: "user", password: "password", persistence: .ForSession)
/// return authentication
/// }
///
/// }
/// ```
///
/// ### Using the above authenticable
/// ```swift
/// class HTTPBinStringGETService: Requestable, HTTPBinAuthenticable {
///
/// let path: String = "get"
/// let encoding: ParameterEncoding = .URLEncodedInURL
/// var parameters: AnyObject?
///
/// init(parameters: AnyObject?) {
/// self.parameters = parameters
/// }
///
/// }
/// ```
public protocol Authenticable {
/// The `Authentication`.
var authentication: Authentication { get }
}
extension Authenticable where Self: Configurable {
/// `configuration.authentication`
public var authentication: Authentication {
return configuration.authentication
}
}
|
mit
|
875df1cc2fe603371c599454b3158ac4
| 22.982456 | 113 | 0.660571 | 4.339683 | false | true | false | false |
anthrgrnwrld/shootSpeed
|
RendaTests/RendaTests.swift
|
1
|
3811
|
//
// RendaTests.swift
// RendaTests
//
// Created by Masaki Horimoto on 2015/07/30.
// Copyright (c) 2015年 Masaki Horimoto. All rights reserved.
//
import UIKit
import XCTest
class RendaTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
func testEditCount1() {
let testViewController: ViewController = ViewController() //ViewControllerクラスをインスタンス化
let result = testViewController.editCount(9999, digitNum: 4) //テストしたいメソッドを呼び出し
XCTAssertNotNil(result) //テスト結果がnilでないか
XCTAssertEqual(result, [9,9,9,9], "result is [9,9,9,9]") //テスト結果(第1引数)が期待値(第2引数)と等しいか
}
func testEditCount2() {
let testViewController: ViewController = ViewController()
let result = testViewController.editCount(10001, digitNum: 4)
XCTAssertNotNil(result)
XCTAssertEqual(result, [0,0,0,1], "result is [0,0,0,1]")
}
func testEditCount3() {
let testViewController: ViewController = ViewController()
let result = testViewController.editCount(10001, digitNum: 10)
XCTAssertNotNil(result)
XCTAssertEqual(result, [0,0,0,0,0,1,0,0,0,1], "result is [0,0,0,0,0,1,0,0,0,1]")
}
func testEditCount4() {
let testViewController: ViewController = ViewController()
let result = testViewController.editCount(255, digitNum: 4)
XCTAssertNotNil(result)
XCTAssertEqual(result, [0,2,5,5], "result is [0,2,5,5]")
}
func testEditCount5() {
let testViewController: ViewController = ViewController()
let result = testViewController.editCount(0, digitNum: 4)
XCTAssertNotNil(result)
XCTAssertEqual(result, [0,0,0,0], "result is [0,0,0,0]")
}
func testEditCount6() {
let testViewController: ViewController = ViewController()
let result = testViewController.editCount(100, digitNum: 4)
XCTAssertNotNil(result)
XCTAssertEqual(result, [0,1,0,0], "result is [0,1,0,0]")
}
func testEditTimerCount1() {
let testViewController: ViewController = ViewController()
let result = testViewController.editTimerCount(0)
XCTAssertNotNil(result)
XCTAssertEqual(result, 10, "result is 0")
}
func testEditTimerCount2() {
let testViewController: ViewController = ViewController()
let result = testViewController.editTimerCount(6)
XCTAssertNotNil(result)
XCTAssertEqual(result, 4, "result is 4")
}
func testEditTimerCount3() {
let testViewController: ViewController = ViewController()
let result = testViewController.editTimerCount(10)
XCTAssertNotNil(result)
XCTAssertEqual(result, 0, "result is 0")
}
func testEditTimerCount4() {
let testViewController: ViewController = ViewController()
let result = testViewController.editTimerCount(100)
XCTAssertNotNil(result)
XCTAssertEqual(result, 0, "result is 0")
}
}
|
mit
|
70d69b6f351b9f70284273c6d3cb2e21
| 33.551402 | 111 | 0.632946 | 4.283893 | false | true | false | false |
Qminder/swift-api
|
Sources/Models/EmptyState.swift
|
1
|
1079
|
//
// EmptyState.swift
// Pods
//
// Created by Kristaps Grinbergs on 27/07/2017.
//
//
import Foundation
/// Empty state layout
public enum EmptyStateLayout: String, Codable, CaseIterable {
/// TV connected
case connected
/// Good morning
case goodMorning
/// Sign-in with iPad
case signIniPad
/// Closed
case closed
/// Sign-in without iPad
case signIn
/// On break
case onBreak
/// Other (not specified)
case other
public init?(rawValue: String) {
switch rawValue.lowercased() {
case "connected":
self = .connected
case "goodmorning":
self = .goodMorning
case "signinipad":
self = .signIniPad
case "signin":
self = .signIn
case "closed":
self = .closed
case "onbreak":
self = .onBreak
default:
self = .other
}
}
}
/// Empty state object
public struct EmptyState: Responsable {
public let statusCode: Int?
/// Empty state layout
public let layout: EmptyStateLayout
/// Empty state message
public let message: String
}
|
mit
|
9f5a3fa2d7098b77a9b7c8ac2ab24853
| 15.6 | 61 | 0.620945 | 4.118321 | false | false | false | false |
sjtu-meow/iOS
|
Meow/HomeViewController.swift
|
1
|
8874
|
//
// HomeViewController.swift
// Meow
//
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import UIKit
import RxSwift
import Rswift
class HomeViewController: UITableViewController {
let bannerViewIdentifier = "bannerViewCell"
let disposeBag = DisposeBag()
var banners = [Banner]()
var currentPage = 0
var moments = [Moment]()
let searchBar = NoCancelButtonSearchBar()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.tableFooterView = UIView(frame: CGRect.zero)
loadData()
searchBar.delegate = self
self.navigationItem.titleView = searchBar
//let vc = R.storyboard.main.searchViewController()
//present(vc!, animated: true, completion: nil)
//self.navigationController?.pushViewController(vc!, animated: true)
//let vc = R.storyboard.articlePage.articleDetailViewController()
// let vc = R.storyboard.loginSignupPage.loginViewController()
//present(vc!, animated: true, completion: nil)
// let vc = R.storyboard.articlePage.articleDetailViewController()
// let vc = R.storyboard.loginSignupPage.loginViewController()
// present(vc!, animated: true, completion: nil)
//logger.log("hello world")
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
tableView.register(R.nib.bannerViewCell)
tableView.register(R.nib.momentHomePageTableViewCell)
tableView.register(R.nib.answerHomePageTableViewCell)
tableView.register(R.nib.questionHomePageTableViewCell)
tableView.register(R.nib.articleHomePageTableViewCell)
}
func loadData() {
MeowAPIProvider.shared.request(.banners)
.mapTo(arrayOf: Banner.self)
.subscribe(onNext: {
[weak self] (banners) in
self?.banners = banners
})
.addDisposableTo(disposeBag)
loadMore()
MeowAPIProvider.shared.request(.moments) // FIXME: need to support other item types
.mapTo(arrayOf: Moment.self)
.subscribe(onNext: {
[weak self]
(items) in
self?.moments = items
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1 /* banners */ + 1 /* items */
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 /* banners: one cell */ {
return 1
}
/* item sections: one cell for each item */
return self.moments.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
/* banners */
if indexPath.section == 0 {
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.bannerViewCell)!
view.configure(banners: self.banners)
view.onTapBanner = {
[weak self] banner in
self?.onTapBanner(banner!)
}
return view
}
/* items */
let item = self.moments[indexPath.row ]
// FIXME: check whether it is a comment cell
switch(item.type!) {
case .moment:
let view = R.nib.momentHomePageTableViewCell.firstView(owner: nil)!
// let view = tableView.dequeueReusableCell(withIdentifier: R.nib.momentHomePageTableViewCell)!
view.configure(model: item as! Moment)
view.delegate = self
return view
case .answer:
let view = tableView.dequeueReusableCell(withIdentifier: R.nib.answerHomePageTableViewCell.identifier)!
(view as! AnswerHomePageTableViewCell).configure(model: item as! AnswerSummary)
return view
case .article:
let view = tableView.dequeueReusableCell(withIdentifier: R.nib.articleHomePageTableViewCell.identifier)!
(view as! ArticleHomePageTableViewCell).configure(model: item as! ArticleSummary)
return view
case .question:
let view = tableView.dequeueReusableCell(withIdentifier: R.nib.questionHomePageTableViewCell.identifier)!
(view as! QuestionHomePageTableViewCell).configure(model: item as! Question)
return view
}
}
override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
guard section == 1 else { return }
loadMore()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let moment = moments[indexPath.row]
MomentDetailViewController.show(moment, from: self)
}
func loadMore() {
MeowAPIProvider.shared.request(.moments) // FIXME: need to support other item types
.mapTo(arrayOf: Moment.self)
.subscribe(onNext: {
[weak self] (items) in
self?.moments = items // FIXME
self?.tableView.reloadData()
self?.currentPage += 1
})
.addDisposableTo(disposeBag)
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let moment = moments[indexPath.row]
MomentDetailViewController.show(moment, from: self)
}
@IBAction func showPostTypePicker(_ sender: Any) {
PostTypeViewController.show(from: self)
}
func onTapBanner(_ banner: Banner) {
let type = banner.itemType!
switch type {
case .moment:
MeowAPIProvider.shared.request(.moment(id: banner.itemId)).mapTo(type: Moment.self).subscribe(onNext: {
[weak self] moment in
if let self_ = self {
MomentDetailViewController.show(moment, from: self_)
}
}).addDisposableTo(disposeBag)
case .article:
MeowAPIProvider.shared.request(.article(id: banner.itemId)).mapTo(type: Article.self).subscribe (onNext: {
[weak self] article in
if let self_ = self {
ArticleDetailViewController.show(article, from: self_)
}
}).addDisposableTo(disposeBag)
case .answer:
MeowAPIProvider.shared.request(.answer(id: banner.itemId)).mapTo(type: Answer.self).subscribe (onNext: {
[weak self] answer in
if let self_ = self {
ArticleDetailViewController.show(answer, from: self_)
}
}).addDisposableTo(disposeBag)
case .question:
let vc = R.storyboard.questionAnswerPage.questionDetailViewController()!
vc.configure(questionId: banner.itemId)
navigationController?.pushViewController(vc, animated: true)
default: break
}
}
}
extension HomeViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
DispatchQueue.main.async {
let vc = R.storyboard.main.searchViewController()
self.navigationController?.pushViewController(vc!, animated: true)
}
return false
}
}
extension HomeViewController: MomentCellDelegate {
func didTapAvatar(profile: Profile) {
if let userId = UserManager.shared.currentUser?.userId, userId == profile.userId {
MeViewController.show(from: navigationController!)
} else {
UserProfileViewController.show(profile, from: self)
}
}
func didToggleLike(id: Int, isLiked: Bool) -> Bool {
var liked = isLiked
let request = isLiked ? MeowAPI.unlikeMoment(id: id) : MeowAPI.likeMoment(id: id)
MeowAPIProvider.shared.request(request)
.subscribe(onNext: {
_ in
liked = !isLiked
})
.addDisposableTo(disposeBag)
return liked
}
func didPostComment(moment: Moment, content: String, from cell: MomentHomePageTableViewCell) {
MeowAPIProvider.shared.request(.postComment(item: moment, content: content))
.subscribe(onNext:{
[weak self]
_ in
cell.clearComment()
cell.model!.commentCount! += 1
cell.updateCommentCountLabel()
self?.loadData()
})
}
}
|
apache-2.0
|
93a2d3fb33a7a09d337da25f1082f48c
| 34.294821 | 118 | 0.596568 | 5.217314 | false | false | false | false |
cocoaheadsru/server
|
Tests/AppTests/Common/Helpers/Controllers/Registration/RegFormHelper.swift
|
1
|
1642
|
import Vapor
@testable import App
typealias EventId = Identifier
//swiftlint:disable superfluous_disable_command
//swiftlint:disable force_try
final class RegFormHelper {
static func assertRegFromHasExpectedFields(_ regForm: JSON) throws -> Bool {
return
regForm["id"]?.int != nil &&
regForm["form_name"]?.string != nil &&
regForm["description"]?.string != nil &&
regForm["reg_fields"]?.makeJSON() != nil
}
@discardableResult
static func store(for events: [App.Event] = []) throws -> [RegForm]? {
var regForms: [RegForm] = []
if events.isEmpty {
var cityIds: [Identifier] = []
var placeIds: [Identifier] = []
var eventIds: [Identifier] = []
let randomRange = 1...Int.random(min: 10, max: 20)
for _ in randomRange {
let city = City()
try city.save()
cityIds.append(city.id!)
}
for _ in randomRange {
let place = Place(true, cityId: cityIds.randomValue)
try place.save()
placeIds.append(place.id!)
}
for _ in randomRange {
let event = Event(placeId: placeIds.randomValue)
try! event.save()
eventIds.append(event.id!)
}
let shuflleEventId = eventIds.shuffled()
for i in randomRange {
let regForm = RegForm(eventId: shuflleEventId[i-1])
try regForm.save()
regForms.append(regForm)
}
} else {
for event in events {
let regForm = RegForm(eventId: event.id!)
try regForm.save()
regForms.append(regForm)
}
}
return regForms
}
}
|
mit
|
d73cc794ead0facba2caf57e7093427e
| 25.063492 | 78 | 0.58039 | 3.890995 | false | false | false | false |
Rilu-Ril/AUCADriver
|
AUCADriver/Controllers/DriverLoginVC.swift
|
1
|
2114
|
//
// DriverLoginVC.swift
// AUCADriver
//
// Created by Sanira on 6/27/17.
// Copyright © 2017 iCoder. All rights reserved.
//
import UIKit
class DriverLoginVC: UIViewController {
private var DRIVER_SIGNUP_ID = "DriverSignUpToFillData"
private var DRIVER_LOGIN_ID = "DriverLogin"
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtPassowrd: UITextField!
var verificationHandle: (()->())?
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.standard.set("driver", forKey: "role")
}
@IBAction func login() {
if txtEmail.text != "" && txtPassowrd.text != "" {
if !isValid(txtEmail.text!) {
return
}
AuthManager.shared.login(email: txtEmail.text!, password: txtPassowrd.text!, loginHandler: { (message) in
if message != nil {
self.showErrorAlert(message!)
} else {
self.performSegue(withIdentifier: self.DRIVER_LOGIN_ID, sender: nil)
}
})
} else {
showErrorAlert(Constants.LOGIN_EMPTY_FIELDS_ERROR)
}
}
@IBAction func signUp() {
if txtEmail.text != "" && txtPassowrd.text != "" {
if !isValid(txtEmail.text!) {
return
}
AuthManager.shared.signUp(with: txtEmail.text!, password: txtPassowrd.text!, loginHandler: { (message) in
if message != nil {
self.showErrorAlert(Constants.LOGIN_CREATE_USER_ERROR)
} else {
self.showAlert("Verification", message: Constants.LOGIN_VERIFICATION_SENT)
}
})
} else {
showErrorAlert(Constants.LOGIN_EMPTY_FIELDS_ERROR)
}
}
func isValid(_ email: String) -> Bool {
let (isValid, msg) = AuthManager.shared.check(email: txtEmail.text!)
if !isValid {
self.showErrorAlert(msg)
return false
}
return true
}
}
|
mit
|
4540d8c359e82780aede894781e83011
| 29.623188 | 117 | 0.539991 | 4.402083 | false | false | false | false |
BENMESSAOUD/yousign
|
YouSign/YouSign/Actions/SignedFiles.swift
|
1
|
2907
|
//
// SignedFiles.swift
// YouSign
//
// Created by Mahmoud Ben Messaoud on 06/06/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import Foundation
import SwiftyXMLParser
@objc public class SignedFiles: Action, Requestable {
public typealias ReturnType = [File]
var signature: Signature
var idFile: String?
var signer: Signer?
@objc public init(environement: Environement, signature: Signature) {
self.signature = signature
super.init(environnement: environement)
}
override public var name: String{
return XMLRequestKeys.signedFile.rawValue
}
override public var values: [String : String]? {
var result = [SignatureResponseKeys.idDemand.rawValue : signature.id]
if let file = idFile {
result[SignatureResponseKeys.idFile.rawValue] = file
}
if let signer = signer {
let signerToken = signature.getToken(forSigner: signer)
result[SignatureResponseKeys.token.rawValue] = signerToken.token
}
return result
}
override public var childs: [Node]?{
return nil
}
override public var apiScheme: String {
return ApiScheme.signature.rawValue
}
public func send(onSuccess: @escaping ([File]) -> Void, onFail: @escaping Requestable.OnFail) {
sendRequest { (data, statusCode, err) in
if let error = err {
onFail(error, statusCode)
}
else if let data = data, statusCode == StatusCode.ok.rawValue {
let xml = XML.parse(data)
let result = xml[XMLResponseKeys.envelope.rawValue, XMLResponseKeys.body.rawValue, XMLResponseKeys.signedFile.rawValue]
let files = self.getFiles(parser: result)
if files.count > 0 {
onSuccess(files)
}
else {
onFail(ConnectorError.server, StatusCode.serverError.rawValue)
}
}
else {
onFail(ConnectorError.server, StatusCode.serverError.rawValue)
}
}
}
private func getFiles(parser: XML.Accessor) -> [File] {
var result = [File]()
if let allElements = parser.element?.childElements {
for element in allElements {
let xmlItem = XML.Accessor(element)
if let fileName = xmlItem[SignedFileResponseKeys.filename.rawValue].text,
let base64String = xmlItem[SignedFileResponseKeys.file.rawValue].text,
let content = Data(base64Encoded: base64String, options: Data.Base64DecodingOptions.ignoreUnknownCharacters) {
let file = File.init(name: fileName, content: content)
result.append(file)
}
}
}
return result
}
}
|
apache-2.0
|
12239e9410371aafafd7faba25e7cfe8
| 33.188235 | 136 | 0.598073 | 4.702265 | false | false | false | false |
tjw/swift
|
test/SILGen/partial_apply_protocol.swift
|
1
|
14646
|
// RUN: %target-swift-frontend -module-name partial_apply_protocol -enable-sil-ownership -emit-silgen -primary-file %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name partial_apply_protocol -enable-sil-ownership -emit-ir -primary-file %s
protocol Clonable {
func clone() -> Self
func maybeClone() -> Self?
func cloneMetatype() -> Self.Type
func getCloneFn() -> () -> Self
func genericClone<T>(t: T) -> Self
func genericGetCloneFn<T>(t: T) -> () -> Self
}
//===----------------------------------------------------------------------===//
// Partial apply of methods returning Self-derived types
//===----------------------------------------------------------------------===//
// CHECK-LABEL: sil hidden @$S22partial_apply_protocol12testClonable1cyAA0E0_p_tF : $@convention(thin) (@in_guaranteed Clonable) -> ()
func testClonable(c: Clonable) {
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}})
let _: () -> Clonable = c.clone
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxSgIegr_22partial_apply_protocol8Clonable_pSgIegr_AbCRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}})
let _: () -> Clonable? = c.maybeClone
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxXMTIegd_22partial_apply_protocol8Clonable_pXmTIegd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @thick τ_0_0.Type) -> @thick Clonable.Type
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @thick τ_0_0.Type) -> @thick Clonable.Type
let _: () -> Clonable.Type = c.cloneMetatype
// CHECK: [[METHOD_FN:%.*]] = witness_method $@opened("{{.*}}") Clonable, #Clonable.getCloneFn!1 : {{.*}}, {{.*}} : $*@opened("{{.*}}") Clonable : $@convention(witness_method: Clonable) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[METHOD_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(witness_method: Clonable) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_0_0
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>([[RESULT]])
let _: () -> Clonable = c.getCloneFn()
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_Iego_22partial_apply_protocol8Clonable_pIegr_Iego_AaBRzlTR
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}})
let _: () -> () -> Clonable = c.getCloneFn
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SxIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
// CHECK: bb0(%0 : @trivial $*Clonable, %1 : @guaranteed $@callee_guaranteed () -> @out τ_0_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: apply %1([[INNER_RESULT]])
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[INNER_RESULT]]
// CHECK-NEXT: return [[EMPTY]]
// FIXME: This is horribly inefficient, too much alloc_stack / copy_addr!
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SxSgIegr_22partial_apply_protocol8Clonable_pSgIegr_AbCRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: bb0(%0 : @trivial $*Optional<Clonable>, %1 : @guaranteed $@callee_guaranteed () -> @out Optional<τ_0_0>):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $Optional<τ_0_0>
// CHECK-NEXT: apply %1([[INNER_RESULT]])
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = alloc_stack $Optional<Clonable>
// CHECK-NEXT: switch_enum_addr [[INNER_RESULT]] : $*Optional<{{.*}}>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]],
// CHECK: [[SOME_BB]]:
// CHECK-NEXT: [[INNER_RESULT_ADDR:%.*]] = unchecked_take_enum_data_addr [[INNER_RESULT]]
// CHECK-NEXT: [[SOME_PAYLOAD:%.*]] = alloc_stack $Clonable
// CHECK-NEXT: [[SOME_PAYLOAD_ADDR:%.*]] = init_existential_addr [[SOME_PAYLOAD]]
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT_ADDR]] to [initialization] [[SOME_PAYLOAD_ADDR]]
// CHECK-NEXT: [[OUTER_RESULT_ADDR:%.*]] = init_enum_data_addr [[OUTER_RESULT]]
// CHECK-NEXT: copy_addr [take] [[SOME_PAYLOAD]] to [initialization] [[OUTER_RESULT_ADDR]]
// CHECK-NEXT: inject_enum_addr [[OUTER_RESULT]]
// CHECK-NEXT: dealloc_stack [[SOME_PAYLOAD]]
// CHECK-NEXT: br bb3
// CHECK: bb2:
// CHECK-NEXT: inject_enum_addr [[OUTER_RESULT]]
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK-NEXT: copy_addr [take] [[OUTER_RESULT]] to [initialization] %0
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[OUTER_RESULT]]
// CHECK-NEXT: dealloc_stack [[INNER_RESULT]]
// CHECK-NEXT: return [[EMPTY]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SxXMTIegd_22partial_apply_protocol8Clonable_pXmTIegd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @thick τ_0_0.Type) -> @thick Clonable.Type
// CHECK: bb0(%0 : @guaranteed $@callee_guaranteed () -> @thick τ_0_0.Type):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = apply %0()
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_metatype [[INNER_RESULT]]
// CHECK-NEXT: return [[OUTER_RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SxIegr_Iego_22partial_apply_protocol8Clonable_pIegr_Iego_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @owned @callee_guaranteed () -> @out τ_0_0) -> @owned @callee_guaranteed () -> @out Clonable
// CHECK: bb0(%0 : @guaranteed $@callee_guaranteed () -> @owned @callee_guaranteed () -> @out τ_0_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = apply %0()
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<τ_0_0>([[INNER_RESULT]])
// CHECK-NEXT: return [[OUTER_RESULT]]
//===----------------------------------------------------------------------===//
// Partial apply of methods returning Self-derived types from generic context
//
// Make sure the thunk only has the context generic parameters if needed!
//===----------------------------------------------------------------------===//
// CHECK-LABEL: sil hidden @$S22partial_apply_protocol28testClonableInGenericContext1c1tyAA0E0_p_xtlF : $@convention(thin) <T> (@in_guaranteed Clonable, @in_guaranteed T) -> ()
func testClonableInGenericContext<T>(c: Clonable, t: T) {
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}})
let _: () -> Clonable = c.clone
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxSgIegr_22partial_apply_protocol8Clonable_pSgIegr_AbCRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out Optional<τ_0_0>) -> @out Optional<Clonable>
let _: () -> Clonable? = c.maybeClone
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxXMTIegd_22partial_apply_protocol8Clonable_pXmTIegd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @thick τ_0_0.Type) -> @thick Clonable.Type
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @thick τ_0_0.Type) -> @thick Clonable.Type
let _: () -> Clonable.Type = c.cloneMetatype
// CHECK: [[METHOD_FN:%.*]] = witness_method $@opened("{{.*}}") Clonable, #Clonable.getCloneFn!1 : {{.*}}, {{.*}} : $*@opened("{{.*}}") Clonable : $@convention(witness_method: Clonable) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[METHOD_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(witness_method: Clonable) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_0_0
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>([[RESULT]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
let _: () -> Clonable = c.getCloneFn()
// CHECK: [[THUNK_FN:%.*]] = function_ref @$SxIegr_Iego_22partial_apply_protocol8Clonable_pIegr_Iego_AaBRzlTR
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @owned @callee_guaranteed () -> @out τ_0_0) -> @owned @callee_guaranteed () -> @out Clonable
let _: () -> () -> Clonable = c.getCloneFn
// CHECK: [[THUNK_FN:%.*]] = function_ref @$Sxqd__Iegnr_x22partial_apply_protocol8Clonable_pIegnr_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in_guaranteed τ_0_0) -> @out τ_1_0) -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T, @opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in_guaranteed τ_0_0) -> @out τ_1_0) -> @out Clonable
let _: (T) -> Clonable = c.genericClone
// CHECK: [[THUNK_FN:%.*]] = function_ref @$Sxqd__Iegr_Iegno_x22partial_apply_protocol8Clonable_pIegr_Iegno_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_1_0) -> @owned @callee_guaranteed () -> @out Clonable
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T, @opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_1_0) -> @owned @callee_guaranteed () -> @out Clonable
let _: (T) -> () -> Clonable = c.genericGetCloneFn
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$Sxqd__Iegnr_x22partial_apply_protocol8Clonable_pIegnr_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in_guaranteed τ_0_0) -> @out τ_1_0) -> @out Clonable
// CHECK: bb0(%0 : @trivial $*Clonable, %1 : @trivial $*τ_0_0, %2 : @guaranteed $@callee_guaranteed (@in_guaranteed τ_0_0) -> @out τ_1_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_1_0
// CHECK-NEXT: apply %2([[INNER_RESULT]], %1)
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[INNER_RESULT]]
// CHECK-NEXT: return [[EMPTY]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$Sxqd__Iegr_Iegno_x22partial_apply_protocol8Clonable_pIegr_Iegno_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_1_0) -> @owned @callee_guaranteed () -> @out Clonable
// CHECK: bb0(%0 : @trivial $*τ_0_0, %1 : @guaranteed $@callee_guaranteed (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed () -> @out τ_1_0):
// CHECK-NEXT: [[RES:%.*]] = apply %1(%0)
// CHECK: [[THUNK_FN:%.*]] = function_ref @$Sqd__Iegr_22partial_apply_protocol8Clonable_pIegr_AaBRd__r__lTR
// CHECK-NEXT: [[RESULT:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<τ_0_0, τ_1_0>([[RES]])
// CHECK-NEXT: return [[RESULT]]
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$Sqd__Iegr_22partial_apply_protocol8Clonable_pIegr_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_1_0) -> @out Clonable {
// CHECK: bb0(%0 : @trivial $*Clonable, %1 : @guaranteed $@callee_guaranteed () -> @out τ_1_0):
// CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_1_0
// CHECK-NEXT: apply %1([[INNER_RESULT]])
// CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0
// CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]]
// CHECK-NEXT: [[EMPTY:%.*]] = tuple ()
// CHECK-NEXT: dealloc_stack [[INNER_RESULT:%.*]]
// CHECK-NEXT: return [[EMPTY]]
|
apache-2.0
|
995cdc1722478a2e383e083d18e2d884
| 90.327044 | 389 | 0.620412 | 3.250728 | false | false | false | false |
SwiftORM/MySQL-StORM
|
Sources/MySQLStORM/MySQLStORM.swift
|
1
|
12587
|
//
// MySQLStORM.swift
// MySQLStORM
//
// Created by Jonathan Guthrie on 2016-10-03.
//
//
import StORM
import PerfectMySQL
import PerfectLogger
/// MySQLConnector sets the connection parameters for the PostgreSQL Server access
/// Usage:
/// MySQLConnector.host = "XXXXXX"
/// MySQLConnector.username = "XXXXXX"
/// MySQLConnector.password = "XXXXXX"
/// MySQLConnector.port = 3306
public struct MySQLConnector {
public static var host: String = ""
public static var username: String = ""
public static var password: String = ""
public static var database: String = ""
public static var port: Int = 3306
public static var charset: String = "utf8mb4"
public static var method: StORMConnectionMethod = .network
public static var quiet: Bool = false
private init(){}
}
/// SuperClass that inherits from the foundation "StORM" class.
/// Provides MySQLL-specific ORM functionality to child classes
open class MySQLStORM: StORM, StORMProtocol {
/// Holds the last statement executed
public var lastStatement: MySQLStmt?
/// Table that the child object relates to in the database.
/// Defined as "open" as it is meant to be overridden by the child class.
open func table() -> String {
let m = Mirror(reflecting: self)
return ("\(m.subjectType)").lowercased()
}
/// Public init
override public init() {
super.init()
}
/// This method can be overriden in MySQLStORM subclass to provide a different database configuration
open func configuration() -> MySQLConnect {
let conf = MySQLConnect(host: MySQLConnector.host,
username: MySQLConnector.username,
password: MySQLConnector.password,
database: MySQLConnector.database,
port: MySQLConnector.port,
charset: MySQLConnector.charset,
method: MySQLConnector.method)
return conf
}
private func printDebug(_ statement: String, _ params: [String]) {
if StORMdebug { LogFile.debug("StORM Debug: \(statement) : \(params.joined(separator: ", "))", logFile: "./StORMlog.txt") }
}
// Internal function which executes statements, with parameter binding
// Returns raw result
@discardableResult
func exec(_ statement: String) throws -> MySQL.Results {
let conf = self.configuration()
let thisConnection = MySQLConnect(
host: conf.credentials.host,
username: conf.credentials.username,
password: conf.credentials.password,
database: conf.database,
port: conf.credentials.port,
charset: conf.charset,
method: conf.credentials.method
)
thisConnection.open()
thisConnection.statement = statement
printDebug(statement, [])
let querySuccess = thisConnection.server.query(statement: statement)
guard querySuccess else {
throw StORMError.error(thisConnection.server.errorMessage())
}
let result = thisConnection.server.storeResults()!
thisConnection.server.close()
return result
}
private func fieldNamesToStringArray(_ arr: [Int:String]) -> [String] {
var out = [String]()
for i in 0..<arr.count {
out.append(arr[i]!)
}
return out
}
// @discardableResult
func exec(_ statement: String, params: [String], isInsert: Bool = false) throws {
let conf = self.configuration()
let thisConnection = MySQLConnect(
host: conf.credentials.host,
username: conf.credentials.username,
password: conf.credentials.password,
database: conf.database,
port: conf.credentials.port,
charset: conf.charset,
method: conf.credentials.method
)
thisConnection.open()
thisConnection.statement = statement
lastStatement = MySQLStmt(thisConnection.server)
defer { lastStatement?.close() }
var res = lastStatement?.prepare(statement: statement)
guard res! else {
throw StORMError.error(thisConnection.server.errorMessage())
}
for p in params {
lastStatement?.bindParam(p)
}
res = lastStatement?.execute()
guard res! else {
if !MySQLConnector.quiet {
print(thisConnection.server.errorMessage())
print(thisConnection.server.errorCode())
}
throw StORMError.error(thisConnection.server.errorMessage())
}
let result = lastStatement?.results()
results.foundSetCount = (result?.numRows)!
if isInsert {
results.insertedID = Int((lastStatement?.insertId())!)
}
thisConnection.server.close()
}
// Internal function which executes statements, with parameter binding
// Returns a processed row set
@discardableResult
func execRows(_ statement: String, params: [String]) throws -> [StORMRow] {
let conf = self.configuration()
let thisConnection = MySQLConnect(
host: conf.credentials.host,
username: conf.credentials.username,
password: conf.credentials.password,
database: conf.database,
port: conf.credentials.port,
charset: conf.charset,
method: conf.credentials.method
)
thisConnection.open()
thisConnection.statement = statement
printDebug(statement, params)
lastStatement = MySQLStmt(thisConnection.server)
var res = lastStatement?.prepare(statement: statement)
guard res! else {
throw StORMError.error(thisConnection.server.errorMessage())
}
for p in params {
lastStatement?.bindParam(p)
}
res = lastStatement?.execute()
for index in 0..<Int((lastStatement?.fieldCount())!) {
let this = lastStatement?.fieldInfo(index: index)!
results.fieldInfo[this!.name] = String(describing: this!.type)
}
guard res! else {
throw StORMError.error(thisConnection.server.errorMessage())
}
let result = lastStatement?.results()
results.foundSetCount = (result?.numRows)!
results.fieldNames = fieldNamesToStringArray((lastStatement?.fieldNames())!)
let resultRows = parseRows(result!, resultSet: results)
thisConnection.server.close()
return resultRows
}
/// Generic "to" function
/// Defined as "open" as it is meant to be overridden by the child class.
///
/// Sample usage:
/// id = this.data["id"] as? Int ?? 0
/// firstname = this.data["firstname"] as? String ?? ""
/// lastname = this.data["lastname"] as? String ?? ""
/// email = this.data["email"] as? String ?? ""
open func to(_ this: StORMRow) {
}
/// Generic "makeRow" function
/// Defined as "open" as it is meant to be overridden by the child class.
open func makeRow() {
self.to(self.results.rows[0])
}
/// Standard "Save" function.
/// Designed as "open" so it can be overriden and customized.
/// If an ID has been defined, save() will perform an updae, otherwise a new document is created.
/// On error can throw a StORMError error.
open func save() throws {
do {
if keyIsEmpty() {
try insert(asData(1))
} else {
let (idname, idval) = firstAsKey()
try update(data: asData(1), idName: idname, idValue: idval)
}
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
throw StORMError.error("\(error)")
}
}
/// Alternate "Save" function.
/// This save method will use the supplied "set" to assign or otherwise process the returned id.
/// Designed as "open" so it can be overriden and customized.
/// If an ID has been defined, save() will perform an updae, otherwise a new document is created.
/// On error can throw a StORMError error.
open func save(set: (_ id: Any)->Void) throws {
do {
if keyIsEmpty() {
let setId = try insert(asData(1))
set(setId)
} else {
let (idname, idval) = firstAsKey()
try update(data: asData(1), idName: idname, idValue: idval)
}
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
throw StORMError.error("\(error)")
}
}
/// Unlike the save() methods, create() mandates the addition of a new document, regardless of whether an ID has been set or specified.
override open func create() throws {
do {
try insert(asData())
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
throw StORMError.error("\(error)")
}
}
/// Table Creation (alias for setup)
open func setupTable(_ str: String = "") throws {
try setup(str)
}
//
open subscript(key: String) -> MySQLDataType {
get {
return .notDefined
}
}
/// Table Creation
/// Requires the connection to be configured, as well as a valid "table" property to have been set in the class
/// - Parameter str: create statement
/// - Parameter defaultTypes: by default it is true so MySQLStORM decides for the type conversion. To be able to provide your own, you need to override the `subscript(key: String) -> String`
open func setup(_ str: String = "", _ useDefaults: Bool? = true) throws {
LogFile.info("Running setup: \(table())", logFile: "./StORMlog.txt")
var createStatement = str
if str.count == 0 {
var opt = [String]()
var keyName = ""
for child in Mirror(reflecting: self).children {
guard let key = child.label else {
continue
}
var verbage = ""
if !key.hasPrefix("internal_") && !key.hasPrefix("_") {
verbage = "`\(key)` "
if let defaultTypes = useDefaults, defaultTypes == false {
let field: MySQLDataType = self[key]
verbage += field.fieldType()
} else {
if child.value is Int && opt.count == 0 {
verbage += "int"
} else if child.value is Int {
verbage += "int"
} else if child.value is Bool {
verbage += "int" // MySQL has no bool type
} else if child.value is Double {
verbage += "float"
} else if child.value is UInt || child.value is UInt8 || child.value is UInt16 || child.value is UInt32 || child.value is UInt64 {
verbage += "blob"
} else {
verbage += "text"
}
}
if opt.count == 0 {
if child.value is Int {
verbage = "`\(key)` int NOT NULL AUTO_INCREMENT"
} else {
verbage = "`\(key)` varchar(255) NOT NULL"
}
keyName = key
}
opt.append(verbage)
}
}
let keyComponent = ", PRIMARY KEY (`\(keyName)`)"
createStatement = "CREATE TABLE IF NOT EXISTS \(table()) (\(opt.joined(separator: ", "))\(keyComponent));"
if StORMdebug { LogFile.info("createStatement: \(createStatement)", logFile: "./StORMlog.txt") }
}
do {
try sql(createStatement, params: [])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
throw StORMError.error("\(error)")
}
}
}
|
apache-2.0
|
7954cf04c2c3d459a21b1d4b17655a56
| 36.239645 | 194 | 0.549297 | 4.802366 | false | false | false | false |
slightair/SwiftGraphics
|
Playgrounds/Matrix.playground/contents.swift
|
6
|
324
|
// Playground - noun: a place where people can play
import SwiftGraphics
var m1 = Matrix(values: [1,2,3,4,5,6], columns: 3, rows: 2)
var m2 = Matrix(values: [7,8,9,10,11,12], columns: 2, rows: 3)
let m3 = m1 * m2
m1[(0,0)]
m3.description
let m4 = Matrix(values: [58.0, 64.0, 139.0, 154.0], columns: 2, rows: 2)
m3 == m4
|
bsd-2-clause
|
c2400358ece24d1e5fb1b154ad45ee40
| 23.923077 | 72 | 0.635802 | 2.28169 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/SharedNotes/Code/Misc.swift
|
1
|
12640
|
//
// Misc.swift
// US
//
// Created by Christopher Prince on 5/30/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
import SMCoreLib
class Misc {
class func showAlert(fromParentViewController parentViewController:UIViewController, title:String, message:String?=nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.popoverPresentationController?.sourceView = parentViewController.view
alert.addAction(UIAlertAction(title: SMUIMessages.session().OkMsg(), style: .Default) {alert in
})
parentViewController.presentViewController(alert, animated: true, completion: nil)
}
// I'll call whichever of c1 and c2 have more elements as `primary`-- maintaining, with priority, the position of the primary's elements. This prioritizes additions to contents over deletions to contents.
class func mergeImageViewContents(c1:[SMImageTextView.ImageTextViewElement], c2:[SMImageTextView.ImageTextViewElement]) -> [SMImageTextView.ImageTextViewElement] {
typealias element = SMImageTextView.ImageTextViewElement
var result = [element]()
var primary:[PrimaryElement]
var secondary:[SecondaryElement]
class SecondaryElement {
var element:SMImageTextView.ImageTextViewElement
var removed = false
// Identical elements across primary and secondary.
var linked:PrimaryElement?
init(element:SMImageTextView.ImageTextViewElement) {
self.element = element
}
}
class PrimaryElement {
var element:SMImageTextView.ImageTextViewElement
var linked:SecondaryElement?
init(element:SMImageTextView.ImageTextViewElement) {
self.element = element
}
}
func createPrimary(elements:[SMImageTextView.ImageTextViewElement]) -> [PrimaryElement] {
var result = [PrimaryElement]()
for elem in elements {
result.append(PrimaryElement(element: elem))
}
return result
}
func createSecondaryLinked(elements:[SMImageTextView.ImageTextViewElement]) -> [SecondaryElement] {
var result = [SecondaryElement]()
for elem in elements {
result.append(SecondaryElement(element: elem))
}
return result
}
func secondaryElementsRemaining(elements:[SecondaryElement]) -> Int {
var result = 0
for elem in elements {
if !elem.removed {
result += 1
}
}
return result
}
let newlyInsertedLocation = -1
func insertElementInPrimary(secondaryElement:SecondaryElement, withRange range:NSRange?=nil, secondaryIndex:Int?=nil, afterPrimary:PrimaryElement?=nil) {
Assert.If(secondaryIndex != nil && afterPrimary != nil, thenPrintThisString: "You gave both a secondaryIndex and an afterPrimary")
var primaryIndex = 0
var insertionIndex:Int?
// Is there an identical element immediately above in the secondary that we can use for orientation?
var after:PrimaryElement? = afterPrimary
if secondaryIndex != nil && secondaryIndex! > 0 {
after = secondary[secondaryIndex! - 1].linked
}
// Similarly, for immediately below
var before:PrimaryElement?
if secondaryIndex != nil && secondaryIndex! < secondary.count - 1 {
before = secondary[secondaryIndex! + 1].linked
}
while primaryIndex < primary.count {
// Giving priority to element reference positioning
if after != nil && after! === primary[primaryIndex] {
insertionIndex = primaryIndex + 1
}
else if before != nil && before! === primary[primaryIndex] {
insertionIndex = primaryIndex
}
else {
// Just using the range.
var primaryRange:NSRange
switch primary[primaryIndex].element {
case .Image(_, _, let range):
primaryRange = range
case .Text(_, let range):
primaryRange = range
}
if primaryRange.location != newlyInsertedLocation
&& range!.location <= primaryRange.location {
insertionIndex = primaryIndex
} else if primaryIndex == primary.count - 1 {
insertionIndex = primaryIndex + 1
}
}
if insertionIndex != nil {
break
}
primaryIndex += 1
}
var newElement:SMImageTextView.ImageTextViewElement
switch secondaryElement.element {
case .Image(let image, let uuid, let range):
newElement = .Image(image, uuid, NSMakeRange(newlyInsertedLocation, range.length))
case .Text(let string, let range):
newElement = .Text(string, NSMakeRange(newlyInsertedLocation, range.length))
}
let newPrimaryElement = PrimaryElement(element: newElement)
secondaryElement.linked = newPrimaryElement
newPrimaryElement.linked = secondaryElement
primary.insert(newPrimaryElement, atIndex: insertionIndex!)
}
func findBestMatchingTextInPrimary(secondaryText:String) -> (PrimaryElement?, Float?) {
var currPrimaryElement:PrimaryElement?
var currBestSimilarity:Float?
let dmp = DiffMatchPatch()
for elemP in primary {
let text = elemP.element.text
if elemP.linked == nil && text != nil {
let similarity = dmp.similarity(firstString: secondaryText, secondString: text!)
if currBestSimilarity == nil || similarity < currBestSimilarity! {
currPrimaryElement = elemP
currBestSimilarity = similarity
}
}
}
return (currPrimaryElement, currBestSimilarity)
}
// Incorporates any new elements into primary by adjusting locations.
func adjustedPrimary() -> [SMImageTextView.ImageTextViewElement] {
var result = [element]()
var currLocation = 0
for elemP in primary {
switch elemP.element {
case .Image(let image, let uuid, let range):
result.append(.Image(image, uuid, NSMakeRange(currLocation, range.length)))
currLocation += range.length
case .Text(let string, let range):
result.append(.Text(string, NSMakeRange(currLocation, range.length)))
currLocation += range.length
}
}
//#if DEBUG
Log.special("adjustedPrimary")
for elem in result {
Log.msg("\(elem)")
}
//#endif
return result
}
if c1.count >= c2.count {
primary = createPrimary(c1)
secondary = createSecondaryLinked(c2)
} else {
primary = createPrimary(c2)
secondary = createSecondaryLinked(c1)
}
// 1) let's see if any elements of primary are identical to those in secondary.
for elemP in primary {
for elemS in secondary {
if !elemS.removed && elemP.element == elemS.element {
elemS.removed = true
elemS.linked = elemP
// It's possible there are multiple identical matches. Just pick the first, top to bottom
break
}
}
}
if secondaryElementsRemaining(secondary) == 0 {
return adjustedPrimary()
}
// 2) See if there are any image elements in the secondary not in the primary. If so, put them into the primary at a reasonable location.
var secondaryIndex = 0
while secondaryIndex < secondary.count {
let elemS = secondary[secondaryIndex]
if !elemS.removed && elemS.linked == nil {
switch elemS.element {
case .Image(_, _, let range):
insertElementInPrimary(elemS, withRange: range, secondaryIndex: secondaryIndex)
elemS.removed = true
case .Text(_, _):
break
}
}
secondaryIndex += 1
}
if secondaryElementsRemaining(secondary) == 0 {
return adjustedPrimary()
}
let shortTextElementLength = 40
let similarityThreshold:Float = 0.2
// We have only non-identical text elements remaining.
// 3) We may be talking about either (a) newly inserted text elements or (b) text elements that were modified. (We are *not* talking about image elements). I'm going to handle this in two ways. (i) if the text element is short, just add it in, and (ii) if the text element is long, see if I can find a matching element in the primary, to do a diff.
secondaryIndex = 0
let dmp = DiffMatchPatch()
while secondaryIndex < secondary.count {
let elemS = secondary[secondaryIndex]
if !elemS.removed {
switch elemS.element {
case .Image:
Assert.badMojo(alwaysPrintThisString: "Should not get here")
case .Text(let string, let textRange):
// Find best matching text within unaccounted for primary .Text elements
let (primaryElement, similarity) = findBestMatchingTextInPrimary(string)
Log.special("similarity: \(similarity)")
if string.characters.count <= shortTextElementLength {
// Shorter text elements: add them in.
if similarity != nil && similarity! <= similarityThreshold {
let newRange = NSMakeRange(newlyInsertedLocation, textRange.length + 3)
let secondaryElement = SecondaryElement(element: .Text(">> " + string, newRange))
insertElementInPrimary(secondaryElement, withRange:newRange, afterPrimary:primaryElement)
}
else {
insertElementInPrimary(elemS, withRange: textRange, secondaryIndex: secondaryIndex)
}
}
else {
// Longer text element: Replace with merged or add if sufficiently different.
if similarity != nil && similarity! <= similarityThreshold {
// Replace with merged
let mergedResult = dmp.diff_simpleMerge(firstString: primaryElement!.element.text!, secondString: string)
primaryElement!.element = .Text(mergedResult, NSMakeRange(newlyInsertedLocation, mergedResult.characters.count))
}
else {
insertElementInPrimary(elemS, withRange: textRange, secondaryIndex: secondaryIndex)
}
}
elemS.removed = true
}
}
secondaryIndex += 1
}
Assert.If(secondaryElementsRemaining(secondary) != 0, thenPrintThisString: "Remaining elements!")
return adjustedPrimary()
}
}
|
gpl-3.0
|
59b5f7661ff76a9928c7e45ece882fe0
| 40.712871 | 356 | 0.532954 | 5.734574 | false | false | false | false |
padawan/smartphone-app
|
MT_iOS/MT_iOS/Classes/App/AppDelegate.swift
|
1
|
8094
|
//
// AppDelegate.swift
// Movable Type for iOS
//
// Created by CHEEBOW on 2015/05/18.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import SVProgressHUD
import SwiftyJSON
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var authInfo = AuthInfo()
var currentUser: User?
private func initAppearance() {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
UINavigationBar.self.appearance().translucent = false
UINavigationBar.self.appearance().barTintColor = Color.navBar
UINavigationBar.self.appearance().tintColor = Color.navBarTint
UINavigationBar.self.appearance().titleTextAttributes = [NSForegroundColorAttributeName: Color.navBarTitle];
SVProgressHUD.setBackgroundColor(UIColor.blackColor())
SVProgressHUD.setForegroundColor(UIColor.whiteColor())
SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.initAppearance()
let api = DataAPI.sharedInstance
api.clientID = "MTiOS"
authInfo.load()
if authInfo.username.isEmpty || authInfo.password.isEmpty || count(authInfo.endpoint) < 8 {
self.goLoginView()
} else {
if Utils.hasConnectivity() {
Utils.performAfterDelay(
{
self.signIn(self.authInfo, showHud: false)
},
delayTime: 0.2
)
} else {
self.goLoginView()
SVProgressHUD.showErrorWithStatus(NSLocalizedString("You can not connect to the network.", comment: "You can not connect to the network."))
}
}
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:.
}
//MARK: -
private func goLoginView() {
let storyboard: UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
let vc = storyboard.instantiateInitialViewController() as! UIViewController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
private func goBlogList() {
let storyboard: UIStoryboard = UIStoryboard(name: "BlogList", bundle: nil)
let vc = storyboard.instantiateInitialViewController() as! UIViewController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
func signIn(auth: AuthInfo, showHud: Bool) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
if showHud {
SVProgressHUD.showWithStatus(NSLocalizedString("Sign In...", comment: "Sign In..."))
}
let api = DataAPI.sharedInstance
api.APIBaseURL = auth.endpoint
api.basicAuth.username = auth.basicAuthUsername
api.basicAuth.password = auth.basicAuthPassword
self.authInfo = auth
self.authInfo.save()
var failure: (JSON!-> Void) = {
(error: JSON!)-> Void in
LOG("failure:\(error.description)")
if showHud {
SVProgressHUD.showErrorWithStatus(error["message"].stringValue)
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
Utils.performAfterDelay(
{
self.goLoginView()
},
delayTime: 2.0
)
}
api.authentication(auth.username, password: auth.password, remember: true,
success:{_ in
api.getUser("me",
success: {(user: JSON!)-> Void in
LOG("\(user)")
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if showHud {
SVProgressHUD.dismiss()
}
self.currentUser = User(json: user)
self.goBlogList()
},
failure: failure
)
},
failure: failure
)
}
private func postLogout() {
let api = DataAPI.sharedInstance
api.resetAuth()
let app: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let authInfo = app.authInfo
authInfo.logout()
self.goLoginView()
}
func logout() {
let api = DataAPI.sharedInstance
if api.sessionID.isEmpty {
self.goLoginView()
return
}
SVProgressHUD.showWithStatus(NSLocalizedString("Logout...", comment: "Logout..."))
api.revokeAuthentication(
{_ in
SVProgressHUD.dismiss()
self.postLogout()
},
failure: {(error: JSON!)-> Void in
SVProgressHUD.dismiss()
self.postLogout()
}
)
}
func createEntry(blog: Blog, controller: UIViewController) {
let vc = EntryDetailTableViewController()
vc.object = Entry(json: ["id":"", "status":"Draft"])
vc.object.date = NSDate()
vc.blog = blog
let nav = UINavigationController(rootViewController: vc)
controller.presentViewController(nav, animated: true, completion:
{_ in
vc.title = NSLocalizedString("Create entry", comment: "Create entry")
}
)
}
func createPage(blog: Blog, controller: UIViewController) {
let vc = PageDetailTableViewController()
vc.object = Page(json: ["id":"", "status":"Draft"])
vc.object.date = NSDate()
vc.blog = blog
let nav = UINavigationController(rootViewController: vc)
vc.title = NSLocalizedString("Create page", comment: "Create page")
controller.presentViewController(nav, animated: true, completion:
{_ in
vc.title = NSLocalizedString("Create page", comment: "Create page")
}
)
}
}
|
mit
|
e65ae9c5de7388e764431d7d38044164
| 37.533333 | 285 | 0.606649 | 5.755334 | false | false | false | false |
exercising/tasker
|
tasker/MasterViewController.swift
|
1
|
3344
|
//
// MasterViewController.swift
// tasker
//
// Created by Dvid Silva on 9/7/14.
// Copyright (c) 2014 hackership. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
// let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
// self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if segue!.identifier == "showDetails" {
let navigationController = segue!.destinationViewController as UINavigationController
let cda = navigationController.viewControllers[0] as DetailViewController
let indexPath = self.tableView.indexPathForSelectedRow()
let task : Task = TaskStore.sharedInstance.get(indexPath!.row)
cda.detailItem = task
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TaskStore.sharedInstance.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let task = TaskStore.sharedInstance.get(indexPath.row)
cell.textLabel?.text = task.title
cell.detailTextLabel?.text = task.notes
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
TaskStore.sharedInstance.removeTaskAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
|
unlicense
|
6587e1fae710b624a0b0519ac72ebe28
| 34.574468 | 157 | 0.682117 | 5.610738 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/Wallet/Types/WalletInfo.swift
|
1
|
2515
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
import TrustKeystore
import TrustCore
import BigInt
struct WalletInfo {
let type: WalletType
let info: WalletObject
var address: Address {
switch type {
case .privateKey, .hd:
return currentAccount.address
case .address(_, let address):
return address
}
}
var coin: Coin? {
switch type {
case .privateKey, .hd:
guard let account = currentAccount,
let coin = Coin(rawValue: account.derivationPath.coinType) else {
return .none
}
return coin
case .address(let coin, _):
return coin
}
}
var multiWallet: Bool {
return accounts.count > 1
}
var mainWallet: Bool {
return info.mainWallet
}
var accounts: [Account] {
switch type {
case .privateKey(let account), .hd(let account):
return account.accounts
case .address(let coin, let address):
return [
Account(wallet: .none, address: address, derivationPath: coin.derivationPath(at: 0)),
]
}
}
var currentAccount: Account! {
switch type {
case .privateKey, .hd:
return accounts.first //.filter { $0.description == info.selectedAccount }.first ?? accounts.first!
case .address(let coin, let address):
return Account(wallet: .none, address: address, derivationPath: coin.derivationPath(at: 0))
}
}
var currentWallet: Wallet? {
switch type {
case .privateKey(let wallet), .hd(let wallet):
return wallet
case .address:
return .none
}
}
var isWatch: Bool {
switch type {
case .privateKey, .hd:
return false
case .address:
return true
}
}
init(
type: WalletType,
info: WalletObject? = .none
) {
self.type = type
self.info = info ?? WalletObject.from(type)
}
var description: String {
return type.description
}
}
extension WalletInfo: Equatable {
static func == (lhs: WalletInfo, rhs: WalletInfo) -> Bool {
return lhs.type.description == rhs.type.description
}
}
extension WalletInfo {
static func format(value: String, server: RPCServer) -> String {
return "\(value) \(server.symbol)"
}
}
|
gpl-3.0
|
2b312ffbabf86f0019118667d799c236
| 23.417476 | 111 | 0.55825 | 4.564428 | false | false | false | false |
nathawes/swift
|
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5conformance-1distinct_use.swift
|
2
|
3135
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type
// CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECk-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0)
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1QAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1RAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1SAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1TAAWP", i32 0, i32 0),
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
protocol P {}
protocol Q {}
protocol R {}
protocol S {}
protocol T {}
extension Int : P {}
extension Int : Q {}
extension Int : R {}
extension Int : S {}
extension Int : T {}
struct Value<First : P & Q & R & S & T> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i8**, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, i8** %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_ARGUMENT_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* [[ERASED_ARGUMENT_BUFFER]], %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
|
apache-2.0
|
02646f6c8cf82796b943d48133ee69d9
| 43.15493 | 362 | 0.601595 | 2.9492 | false | false | false | false |
gurenupet/hah-auth-ios-swift
|
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/WebSocketWrapper.swift
|
2
|
11578
|
//
// WebSocketWrapper.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/25/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
import UIKit
enum MessageType: String {
case bindingRequest = "event_binding_request"
case bindingResponse = "event_binding_response"
case deviceInfoRequest = "device_info_request"
case deviceInfoResponse = "device_info_response"
case disconnect = "disconnect"
case snapshotRequest = "snapshot_request"
case snapshotResponse = "snapshot_response"
case changeRequest = "change_request"
case changeResponse = "change_response"
case tweakRequest = "tweak_request"
case tweakResponse = "tweak_response"
case clearRequest = "clear_request"
case clearResponse = "clear_response"
}
class WebSocketWrapper: WebSocketDelegate {
static let sessionVariantKey = "session_variant"
static let startLoadingAnimationKey = "connectivityBarLoading"
static let finishLoadingAnimationKey = "connectivtyBarFinished"
static var retries = 0
var open: Bool
var connected: Bool
let url: URL
var session: [String: Any]
let webSocket: WebSocket
let commandQueue: OperationQueue
var recordingView: UIView? = nil
var indeterminateLayer: CALayer? = nil
var connectivityIndiciatorWindow: UIWindow? = nil
let connectCallback: (() -> Void)?
let disconnectCallback: (() -> Void)?
init(url: URL, keepTrying: Bool, connectCallback: (() -> Void)?, disconnectCallback: (() -> Void)?) {
open = false
connected = false
session = [String: Any]()
self.url = url
self.connectCallback = connectCallback
self.disconnectCallback = disconnectCallback
commandQueue = OperationQueue()
commandQueue.maxConcurrentOperationCount = 1
commandQueue.isSuspended = true
webSocket = WebSocket(url: url)
webSocket.delegate = self
if keepTrying {
open(initiate: true, maxInterval: 30, maxRetries: 40)
} else {
open(initiate: true)
}
}
func setSessionObjectSynchronized(with value: Any, for key: String) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
session[key] = value
}
func getSessionObjectSynchronized(for key: String) -> Any? {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
return session[key]
}
func open(initiate: Bool, maxInterval: Int = 0, maxRetries: Int = 0) {
Logger.debug(message: "In opening connection. Initiate: \(initiate), "
+ "retries: \(WebSocketWrapper.retries), maxRetries: \(maxRetries), "
+ "maxInterval: \(maxInterval), connected: \(connected)")
if connected || WebSocketWrapper.retries > maxRetries {
// exit retry loop if any of the conditions are met
WebSocketWrapper.retries = 0
} else if initiate || WebSocketWrapper.retries > 0 {
if !open {
Logger.debug(message: "Attempting to open WebSocket to \(url), try \(WebSocketWrapper.retries) out of \(maxRetries)")
open = true
webSocket.connect()
}
}
if WebSocketWrapper.retries < maxRetries {
DispatchQueue.main.asyncAfter(deadline: .now() + min(pow(1.4, Double(WebSocketWrapper.retries)), Double(maxInterval))) {
self.open(initiate: false, maxInterval: maxInterval, maxRetries: maxRetries)
}
WebSocketWrapper.retries += 1
}
}
func close() {
webSocket.disconnect()
for value in session.values {
if let value = value as? CodelessBindingCollection {
value.cleanup()
}
}
}
deinit {
webSocket.delegate = nil
close()
}
func send(message: BaseWebSocketMessage?) {
if connected {
Logger.debug(message: "Sending message: \(message.debugDescription)")
if let data = message?.JSONData(), let jsonString = String(data: data, encoding: String.Encoding.utf8) {
webSocket.write(string: jsonString)
}
}
}
class func getMessageType(for message: Data) -> BaseWebSocketMessage? {
Logger.info(message: "raw message \(message)")
var webSocketMessage: BaseWebSocketMessage? = nil
do {
let jsonObject = try JSONSerialization.jsonObject(with: message, options: [])
if let messageDict = jsonObject as? [String: Any] {
guard let type = messageDict["type"] as? String,
let typeEnum = MessageType.init(rawValue: type) else {
return nil
}
let payload = messageDict["payload"] as? [String: AnyObject]
switch typeEnum {
case .snapshotRequest:
webSocketMessage = SnapshotRequest(payload: payload)
case .deviceInfoRequest:
webSocketMessage = DeviceInfoRequest()
case .disconnect:
webSocketMessage = DisconnectMessage()
case .bindingRequest:
webSocketMessage = BindingRequest(payload: payload)
case .changeRequest:
webSocketMessage = ChangeRequest(payload: payload)
case .tweakRequest:
webSocketMessage = TweakRequest(payload: payload)
case .clearRequest:
webSocketMessage = ClearRequest(payload: payload)
default:
Logger.debug(message: "the type that was not parsed: \(type)")
break
}
} else {
Logger.warn(message: "Badly formed socket message, expected JSON dictionary.")
}
} catch {
Logger.warn(message: "Badly formed socket message, can't serialize object.")
}
return webSocketMessage
}
func showConnectedView(loading: Bool) {
if connectivityIndiciatorWindow == nil {
guard let mainWindow = UIApplication.shared.delegate?.window, let window = mainWindow else {
return
}
connectivityIndiciatorWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: window.frame.size.width, height: 4))
connectivityIndiciatorWindow?.backgroundColor = UIColor.clear
connectivityIndiciatorWindow?.windowLevel = UIWindowLevelAlert
connectivityIndiciatorWindow?.alpha = 0
connectivityIndiciatorWindow?.isHidden = false
recordingView = UIView(frame: connectivityIndiciatorWindow!.frame)
recordingView?.backgroundColor = UIColor.clear
indeterminateLayer = CALayer()
indeterminateLayer?.backgroundColor = UIColor(red: 1/255.0, green: 179/255.0, blue: 109/255.0, alpha: 1).cgColor
indeterminateLayer?.frame = CGRect(x: 0, y: 0, width: 0, height: 4)
recordingView?.layer.addSublayer(indeterminateLayer!)
connectivityIndiciatorWindow?.addSubview(recordingView!)
connectivityIndiciatorWindow?.bringSubview(toFront: recordingView!)
UIView.animate(withDuration: 0.3) {
self.connectivityIndiciatorWindow?.alpha = 1
}
}
animateConnecting(loading: loading)
}
func animateConnecting(loading: Bool) {
if loading {
loadBasicAnimation(duration: 10,
fromValue: 0,
toValue: connectivityIndiciatorWindow!.bounds.size.width * 1.9,
animationKey: WebSocketWrapper.startLoadingAnimationKey)
} else {
indeterminateLayer?.removeAnimation(forKey: WebSocketWrapper.startLoadingAnimationKey)
loadBasicAnimation(duration: 0.4,
fromValue: indeterminateLayer?.presentation()?.value(forKey: "bounds.size.width") ?? 0.0,
toValue: connectivityIndiciatorWindow!.bounds.size.width * 2,
animationKey: WebSocketWrapper.finishLoadingAnimationKey)
}
}
func loadBasicAnimation(duration: Double, fromValue: Any, toValue: Any, animationKey: String) {
let myAnimation = CABasicAnimation(keyPath: "bounds.size.width")
myAnimation.duration = duration
myAnimation.fromValue = fromValue
myAnimation.toValue = toValue
myAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
myAnimation.fillMode = kCAFillModeForwards
myAnimation.isRemovedOnCompletion = false
indeterminateLayer?.add(myAnimation, forKey: animationKey)
}
func hideConnectedView() {
if connectivityIndiciatorWindow != nil {
indeterminateLayer?.removeFromSuperlayer()
recordingView?.removeFromSuperview()
connectivityIndiciatorWindow?.isHidden = true
}
connectivityIndiciatorWindow = nil
}
func websocketDidReceiveMessage(_ socket: WebSocket, text: String) {
var shouldShowUI = false
if !connected {
connected = true
showConnectedView(loading: true)
shouldShowUI = true
if let callback = connectCallback {
callback()
}
}
if let messageData = text.data(using: String.Encoding.utf8) {
let message = WebSocketWrapper.getMessageType(for: messageData)
Logger.info(message: "WebSocket received message: \(message.debugDescription)")
if let commandOperation = message?.responseCommand(connection: self) {
commandQueue.addOperation(commandOperation)
if shouldShowUI {
showConnectedView(loading: false)
}
} else if shouldShowUI {
hideConnectedView()
}
}
}
func websocketDidReceiveData(_ socket: WebSocket, data: Data) {
var shouldShowUI = false
if !connected {
connected = true
showConnectedView(loading: true)
shouldShowUI = true
if let callback = connectCallback {
callback()
}
}
let message = WebSocketWrapper.getMessageType(for: data)
Logger.info(message: "WebSocket received message: \(message.debugDescription)")
if let commandOperation = message?.responseCommand(connection: self) {
commandQueue.addOperation(commandOperation)
if shouldShowUI {
showConnectedView(loading: false)
}
} else {
hideConnectedView()
}
}
func websocketDidConnect(_ socket: WebSocket) {
Logger.info(message: "WebSocket \(socket) did open")
commandQueue.isSuspended = false
}
func websocketDidDisconnect(_ socket: WebSocket, error: NSError?) {
if let error = error {
Logger.debug(message: "WebSocket disconnected because of: \(error.description)")
}
commandQueue.isSuspended = true
commandQueue.cancelAllOperations()
hideConnectedView()
open = false
if connected {
connected = false
open(initiate: true, maxInterval: 10, maxRetries: 10)
if let callback = disconnectCallback {
callback()
}
}
}
}
|
mit
|
58a2741f6e04ad46ac4d11cf15435b6a
| 37.719064 | 133 | 0.60672 | 5.170612 | false | false | false | false |
fabiomassimo/eidolon
|
Kiosk/Bid Fulfillment/Models/BidDetails.swift
|
1
|
1001
|
import UIKit
@objc public class BidDetails: NSObject {
public typealias DownloadImageClosure = (url: NSURL, imageView: UIImageView) -> ()
public dynamic var newUser: NewUser = NewUser()
public dynamic var saleArtwork: SaleArtwork?
public dynamic var paddleNumber: String?
public dynamic var bidderPIN: String?
public dynamic var bidAmountCents: NSNumber?
public dynamic var bidderID: String?
public var setImage: DownloadImageClosure = { (url, imageView) -> () in
imageView.sd_setImageWithURL(url)
}
public init(saleArtwork: SaleArtwork?, paddleNumber: String?, bidderPIN: String?, bidAmountCents:Int?) {
self.saleArtwork = saleArtwork
self.paddleNumber = paddleNumber
self.bidderPIN = bidderPIN
self.bidAmountCents = bidAmountCents
}
/// Not for production use
public convenience init(string: String) {
self.init(saleArtwork: nil, paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil)
}
}
|
mit
|
b11dd37975fdad1493a4bc41aa168191
| 33.551724 | 108 | 0.702298 | 4.766667 | false | false | false | false |
AbelSu131/ios-charts
|
Charts/Classes/Data/CandleChartDataEntry.swift
|
3
|
2116
|
//
// CandleChartDataEntry.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class CandleChartDataEntry: ChartDataEntry
{
/// shadow-high value
public var high = Double(0.0)
/// shadow-low value
public var low = Double(0.0)
/// close value
public var close = Double(0.0)
/// open value
public var open = Double(0.0)
public init(xIndex: Int, shadowH: Double, shadowL: Double, open: Double, close: Double)
{
super.init(value: (shadowH + shadowL) / 2.0, xIndex: xIndex);
self.high = shadowH;
self.low = shadowL;
self.open = open;
self.close = close;
}
public init(xIndex: Int, shadowH: Double, shadowL: Double, open: Double, close: Double, data: AnyObject?)
{
super.init(value: (shadowH + shadowL) / 2.0, xIndex: xIndex, data: data);
self.high = shadowH;
self.low = shadowL;
self.open = open;
self.close = close;
}
/// Returns the overall range (difference) between shadow-high and shadow-low.
public var shadowRange: Double
{
return abs(high - low);
}
/// Returns the body size (difference between open and close).
public var bodyRange: Double
{
return abs(open - close);
}
/// the center value of the candle. (Middle value between high and low)
public override var value: Double
{
get
{
return super.value;
}
set
{
super.value = (high + low) / 2.0;
}
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! CandleChartDataEntry;
copy.high = high;
copy.high = low;
copy.high = open;
copy.high = close;
return copy;
}
}
|
apache-2.0
|
9f5433c2ac2452e0b18cb3f090c0e14f
| 23.616279 | 109 | 0.575142 | 4.05364 | false | false | false | false |
jimmyhuang1114/SwiftInPractice
|
DemoClosure/DemoClosure/main.swift
|
1
|
3255
|
//
// main.swift
// DemoClosure
//
// Created by Jimmy Huang on 12/23/14.
// Copyright (c) 2014 Jimmy Huang. All rights reserved.
//
import Foundation
/* Example 1: Demo the use of normal function call */
//=> CASE 1 : call function
// define the function greeting which type is (String) -> (String)
func greeting(s0: String) -> (String) {
return "Hello \(s0) which can work together well with Objective-C!"
}
// call greeting function
var returnMsg = greeting("Swift")
println("CASE 1: \(returnMsg)")
//=> CASE 2: assign function to a variable
var funVar = greeting
// call it via variable
returnMsg = funVar("Swift")
println("CASE 2: \(returnMsg)")
//=> CASE 3: call function as a function's parameter
func useFuncAsParam(string: String, funcAsParam:(String) -> (String)) -> (String) {
return funcAsParam(string)
}
returnMsg = useFuncAsParam("Swift", greeting)
println("CASE 3: \(returnMsg)")
/* Example 2: Demo the use of closure */
//=> CASE 4: use closure as a function's parameter
returnMsg = useFuncAsParam("Swift", {(s0: String) -> (String) in
return "Hello \(s0) which can work together well with Objective-C!"})
println("CASE 4: \(returnMsg)")
//=> CASE 5: use inferred type to reduce closure
returnMsg = useFuncAsParam("Swift", {s0 in
return "Hello \(s0) which can work together well with Objective-C!"})
println("CASE 5: \(returnMsg)")
//=> CASE 6: use shorthand arguments to reduce more
returnMsg = useFuncAsParam("Swift", {
return "Hello \($0) which can work together well with Objective-C!"})
println("CASE 6: \(returnMsg)")
//=> CASE 7: use trailing closure to express
returnMsg = useFuncAsParam("Swift"){
return "Hello \($0) which can work together well with Objective-C!"
}
println("CASE 7: \(returnMsg)")
/* Example 3: use closure to sort array */
let brands = ["Apple", "Facebook", "Google", "Microsoft", "Amazon"]
//=> CASE 8: define closure for sorting
var sortedBrands = brands.sorted({
(s0: String, s1: String) -> Bool in
return s0 < s1
})
println("CASE 8: \(sortedBrands)")
//=> CASE 9: use shorthand parameter instead
sortedBrands = brands.sorted(){$0 < $1}
println("CASE 9: \(sortedBrands)")
//=> CASE 10: remove () off
sortedBrands = brands.sorted{$0 < $1}
println("CASE 10: \(sortedBrands)")
/* Example 4: use closure to map array */
//=> CASE 11
let mappingDict = ["XD":"笑到超開心", "Bj4":"不解釋", "Orz":"很冏", "魯蛇":"loser", "灑花":"很開心"]
let networkTerms = ["XD", "Orz", "Bj4"]
let transTerms = networkTerms.map{
(var term) -> String in
var each = mappingDict[term]
if let output = each {
return output
}else {
return "input error!"
}
}
println("CASE 11: \(transTerms)")
//=> CASE 12
let squareArray = [1, 2, 3].map{ $0 * $0 }
println("CASE 12: \(squareArray)")
/* Example 5: Demo capturing values */
//=> CASE 13
typealias increamentOneUnit = () -> Int
func increamentor(start from: Int, each amount: Int) -> increamentOneUnit {
var total = from
return {
total += amount
return total
}
}
let adder1 = increamentor(start: 10, each: 10)
println("CASE 13:")
println(adder1())
println(adder1())
println(adder1())
let adder2 = increamentor(start: 10, each: 10)
println(adder2())
|
apache-2.0
|
3899af6e6a849fe345eb470ce97fe5b9
| 26.07563 | 83 | 0.661596 | 3.283384 | false | false | false | false |
crashoverride777/SwiftyReceiptValidator
|
Source/Models/Responses/ReceiptResponse.swift
|
1
|
3689
|
//
// SRVReceiptResponse.swift
// SwiftyReceiptValidator
//
// Created by Dominik Ringler on 29/01/2019.
// Copyright © 2019 Dominik. All rights reserved.
//
import Foundation
public struct SRVReceiptResponse: Codable, Equatable {
// For iOS 6 style transaction receipts, the status code reflects the status of the specific transaction’s receipt.
// For iOS 7 style app receipts, the status code is reflects the status of the app receipt as a whole. For example, if you send a valid app receipt that contains an expired subscription, the response is 0 because the receipt as a whole is valid.
public let status: SRVStatusCode
// A JSON representation of the receipt that was sent for verification. For information about keys found in a receipt, see Receipt Fields.
public let receipt: SRVReceipt?
// Only returned for receipts containing auto-renewable subscriptions.
// For iOS 6 style transaction receipts, this is the base-64 encoded receipt for the most recent renewal.
// For iOS 7 style app receipts, this is the latest base-64 encoded app receipt.
public let latestReceipt: Data?
// Only returned for receipts containing auto-renewable subscriptions.
// For iOS 6 style transaction receipts, this is the JSON representation of the receipt for the most recent renewal.
// For iOS 7 style app receipts, the value of this key is an array containing all in-app purchase transactions. This excludes transactions for a consumable product that have been marked as finished by your app.
public let latestReceiptInfo: [SRVReceiptInApp]?
// Only returned for iOS 7 style app receipts containing auto-renewable subscriptions. In the JSON file, the value of this key is an array where each element contains the pending renewal information for each auto-renewable subscription identified by the Product Identifier. A pending renewal may refer to a renewal that is scheduled in the future or a renewal that failed in the past for some reason.
public let pendingRenewalInfo: [SRVPendingRenewalInfo]?
// The current environment, Sandbox or Production
public let environment: String?
}
// MARK: - Computed
extension SRVReceiptResponse {
/// All subscriptions that are currently active, sorted by expiry dates
func validSubscriptionReceipts(now: Date) -> [SRVReceiptInApp] {
guard let receipts = latestReceiptInfo ?? receipt?.inApp else {
return []
}
return receipts
// Filter receipts for subsriptions
.filter {
/*
To check whether a purchase has been cancelled by Apple Customer Support, look for the
Cancellation Date field in the receipt. If the field contains a date, regardless
of the subscription’s expiration date, the purchase has been cancelled. With respect to
providing content or service, treat a canceled transaction the same as if no purchase
had ever been made.
*/
guard $0.cancellationDate == nil else {
return false
}
// Only receipts with an expiry date are subscriptions
guard let expiresDate = $0.expiresDate else {
return false
}
// Return active subscription receipts
return expiresDate >= now
}
// Sort subscription receipts by expiry date
// We can force unwrap as nil expiry dates get filtered above
.sorted(by: { $0.expiresDate! > $1.expiresDate! })
}
}
|
mit
|
46011c2afff6752d545cd72697d3db3e
| 53.985075 | 404 | 0.679425 | 5.316017 | false | true | false | false |
uber/RIBs
|
ios/RIBs/Classes/Workflow/Workflow.swift
|
1
|
9921
|
//
// Copyright (c) 2017. Uber Technologies
//
// 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 RxSwift
/// Defines the base class for a sequence of steps that execute a flow through the application RIB tree.
///
/// At each step of a `Workflow` is a pair of value and actionable item. The value can be used to make logic decisions.
/// The actionable item is invoked to perform logic for the step. Typically the actionable item is the `Interactor` of a
/// RIB.
///
/// A workflow should always start at the root of the tree.
open class Workflow<ActionableItemType> {
/// Called when the last step observable is completed.
///
/// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle.
/// The default implementation does nothing.
open func didComplete() {
// No-op
}
/// Called when the `Workflow` is forked.
///
/// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle.
/// The default implementation does nothing.
open func didFork() {
// No-op
}
/// Called when the last step observable is has error.
///
/// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle.
/// The default implementation does nothing.
open func didReceiveError(_ error: Error) {
// No-op
}
/// Initializer.
public init() {}
/// Execute the given closure as the root step.
///
/// - parameter onStep: The closure to execute for the root step.
/// - returns: The next step.
public final func onStep<NextActionableItemType, NextValueType>(_ onStep: @escaping (ActionableItemType) -> Observable<(NextActionableItemType, NextValueType)>) -> Step<ActionableItemType, NextActionableItemType, NextValueType> {
return Step(workflow: self, observable: subject.asObservable().take(1))
.onStep { (actionableItem: ActionableItemType, _) in
onStep(actionableItem)
}
}
/// Subscribe and start the `Workflow` sequence.
///
/// - parameter actionableItem: The initial actionable item for the first step.
/// - returns: The disposable of this workflow.
public final func subscribe(_ actionableItem: ActionableItemType) -> Disposable {
guard compositeDisposable.count > 0 else {
assertionFailure("Attempt to subscribe to \(self) before it is comitted.")
return Disposables.create()
}
subject.onNext((actionableItem, ()))
return compositeDisposable
}
// MARK: - Private
private let subject = PublishSubject<(ActionableItemType, ())>()
private var didInvokeComplete = false
/// The composite disposable that contains all subscriptions including the original workflow
/// as well as all the forked ones.
fileprivate let compositeDisposable = CompositeDisposable()
fileprivate func didCompleteIfNotYet() {
// Since a workflow may be forked to produce multiple subscribed Rx chains, we should
// ensure the didComplete method is only invoked once per Workflow instance. See `Step.commit`
// on why the side-effects must be added at the end of the Rx chains.
guard !didInvokeComplete else {
return
}
didInvokeComplete = true
didComplete()
}
}
/// Defines a single step in a `Workflow`.
///
/// A step may produce a next step with a new value and actionable item, eventually forming a sequence of `Workflow`
/// steps.
///
/// Steps are asynchronous by nature.
open class Step<WorkflowActionableItemType, ActionableItemType, ValueType> {
private let workflow: Workflow<WorkflowActionableItemType>
private var observable: Observable<(ActionableItemType, ValueType)>
fileprivate init(workflow: Workflow<WorkflowActionableItemType>, observable: Observable<(ActionableItemType, ValueType)>) {
self.workflow = workflow
self.observable = observable
}
/// Executes the given closure for this step.
///
/// - parameter onStep: The closure to execute for the `Step`.
/// - returns: The next step.
public final func onStep<NextActionableItemType, NextValueType>(_ onStep: @escaping (ActionableItemType, ValueType) -> Observable<(NextActionableItemType, NextValueType)>) -> Step<WorkflowActionableItemType, NextActionableItemType, NextValueType> {
let confinedNextStep = observable
.flatMapLatest { (actionableItem, value) -> Observable<(Bool, ActionableItemType, ValueType)> in
// We cannot use generic constraint here since Swift requires constraints be
// satisfied by concrete types, preventing using protocol as actionable type.
if let interactor = actionableItem as? Interactable {
return interactor
.isActiveStream
.map({ (isActive: Bool) -> (Bool, ActionableItemType, ValueType) in
(isActive, actionableItem, value)
})
} else {
return Observable.just((true, actionableItem, value))
}
}
.filter { (isActive: Bool, _, _) -> Bool in
isActive
}
.take(1)
.flatMapLatest { (_, actionableItem: ActionableItemType, value: ValueType) -> Observable<(NextActionableItemType, NextValueType)> in
onStep(actionableItem, value)
}
.take(1)
.share()
return Step<WorkflowActionableItemType, NextActionableItemType, NextValueType>(workflow: workflow, observable: confinedNextStep)
}
/// Executes the given closure when the `Step` produces an error.
///
/// - parameter onError: The closure to execute when an error occurs.
/// - returns: This step.
public final func onError(_ onError: @escaping ((Error) -> ())) -> Step<WorkflowActionableItemType, ActionableItemType, ValueType> {
observable = observable.do(onError: onError)
return self
}
/// Commit the steps of the `Workflow` sequence.
///
/// - returns: The committed `Workflow`.
@discardableResult
public final func commit() -> Workflow<WorkflowActionableItemType> {
// Side-effects must be chained at the last observable sequence, since errors and complete
// events can be emitted by any observables on any steps of the workflow.
let disposable = observable
.do(onError: workflow.didReceiveError, onCompleted: workflow.didCompleteIfNotYet)
.subscribe()
_ = workflow.compositeDisposable.insert(disposable)
return workflow
}
/// Convert the `Workflow` into an obseravble.
///
/// - returns: The observable representation of this `Workflow`.
public final func asObservable() -> Observable<(ActionableItemType, ValueType)> {
return observable
}
}
/// `Workflow` related obervable extensions.
public extension ObservableType {
/// Fork the step from this obervable.
///
/// - parameter workflow: The workflow this step belongs to.
/// - returns: The newly forked step in the workflow. `nil` if this observable does not conform to the required
/// generic type of (ActionableItemType, ValueType).
func fork<WorkflowActionableItemType, ActionableItemType, ValueType>(_ workflow: Workflow<WorkflowActionableItemType>) -> Step<WorkflowActionableItemType, ActionableItemType, ValueType>? {
if let stepObservable = self as? Observable<(ActionableItemType, ValueType)> {
workflow.didFork()
return Step(workflow: workflow, observable: stepObservable)
}
return nil
}
}
/// `Workflow` related `Disposable` extensions.
public extension Disposable {
/// Dispose the subscription when the given `Workflow` is disposed.
///
/// When using this composition, the subscription closure may freely retain the workflow itself, since the
/// subscription closure is disposed once the workflow is disposed, thus releasing the retain cycle before the
/// `Workflow` needs to be deallocated.
///
/// - note: This is the preferred method when trying to confine a subscription to the lifecycle of a `Workflow`.
///
/// - parameter workflow: The workflow to dispose the subscription with.
func disposeWith<ActionableItemType>(workflow: Workflow<ActionableItemType>) {
_ = workflow.compositeDisposable.insert(self)
}
/// Dispose the subscription when the given `Workflow` is disposed.
///
/// When using this composition, the subscription closure may freely retain the workflow itself, since the
/// subscription closure is disposed once the workflow is disposed, thus releasing the retain cycle before the
/// `Workflow` needs to be deallocated.
///
/// - note: This is the preferred method when trying to confine a subscription to the lifecycle of a `Workflow`.
///
/// - parameter workflow: The workflow to dispose the subscription with.
@available(*, deprecated, renamed: "disposeWith(workflow:)")
func disposeWith<ActionableItemType>(worflow: Workflow<ActionableItemType>) {
disposeWith(workflow: worflow)
}
}
|
apache-2.0
|
8576c927f7e331d54bc6c6b0fcb45834
| 42.89823 | 252 | 0.675033 | 5.010606 | false | false | false | false |
wikimedia/wikipedia-ios
|
WMF Framework/Remote Notifications/RemoteNotificationsOperationsController.swift
|
1
|
13080
|
import CocoaLumberjackSwift
enum RemoteNotificationsOperationsError: LocalizedError {
case failurePullingAppLanguage
case individualErrors([Error])
var errorDescription: String? {
switch self {
case .individualErrors(let errors):
if let firstError = errors.first {
return (firstError as NSError).alertMessage()
}
default:
break
}
return CommonStrings.genericErrorDescription
}
}
public extension Notification.Name {
static let NotificationsCenterLoadingDidStart = Notification.Name("NotificationsCenterLoadingDidStart") // fired when notifications have begun importing or refreshing
static let NotificationsCenterLoadingDidEnd = Notification.Name("NotificationsCenterLoadingDidEnd") // fired when notifications have ended importing or refreshing
}
class RemoteNotificationsOperationsController: NSObject {
private let apiController: RemoteNotificationsAPIController
private let modelController: RemoteNotificationsModelController
private let operationQueue: OperationQueue
private let languageLinkController: MWKLanguageLinkController
private let authManager: WMFAuthenticationManager
private(set) var isLoadingNotifications = false
private var loadingNotificationsCompletionBlocks: [(Result<Void, Error>) -> Void] = []
required init(languageLinkController: MWKLanguageLinkController, authManager: WMFAuthenticationManager, apiController: RemoteNotificationsAPIController, modelController: RemoteNotificationsModelController) {
self.apiController = apiController
self.modelController = modelController
operationQueue = OperationQueue()
self.languageLinkController = languageLinkController
self.authManager = authManager
super.init()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Public
/// Kicks off operations to fetch and persist read and unread history of notifications from app languages, Commons, and Wikidata, + other projects with unread notifications. Designed to automatically page and fully import once per installation, then only fetch new notifications for each project when called after that. Will not attempt if loading is already in progress. Must be called from main thread.
/// - Parameter completion: Block to run once operations have completed. Dispatched to main thread.
func loadNotifications(_ completion: ((Result<Void, Error>) -> Void)? = nil) {
assert(Thread.isMainThread)
if let completion = completion {
loadingNotificationsCompletionBlocks.append(completion)
}
// Purposefully not calling completion block here, because we are tracking it in line above. It will be called when currently running loading operations complete.
guard !isLoadingNotifications else {
return
}
isLoadingNotifications = true
NotificationCenter.default.post(name: Notification.Name.NotificationsCenterLoadingDidStart, object: nil)
kickoffPagingOperations { [weak self] result in
DispatchQueue.main.async {
self?.isLoadingNotifications = false
self?.loadingNotificationsCompletionBlocks.forEach { completionBlock in
completionBlock(result)
}
self?.loadingNotificationsCompletionBlocks.removeAll()
NotificationCenter.default.post(name: Notification.Name.NotificationsCenterLoadingDidEnd, object: nil)
}
}
}
func markAsReadOrUnread(identifierGroups: Set<RemoteNotification.IdentifierGroup>, shouldMarkRead: Bool, languageLinkController: MWKLanguageLinkController, completion: ((Result<Void, Error>) -> Void)? = nil) {
assert(Thread.isMainThread)
// sort identifier groups into dictionary keyed by wiki
let requestDictionary: [String: Set<RemoteNotification.IdentifierGroup>] = identifierGroups.reduce([String: Set<RemoteNotification.IdentifierGroup>]()) { partialResult, identifierGroup in
var result = partialResult
guard let wiki = identifierGroup.wiki else {
return result
}
result[wiki, default: Set<RemoteNotification.IdentifierGroup>()].insert(identifierGroup)
return result
}
// turn into array of operations
let operations: [RemoteNotificationsMarkReadOrUnreadOperation] = requestDictionary.compactMap { element in
let wiki = element.key
guard let project = WikimediaProject(notificationsApiIdentifier: wiki, languageLinkController: languageLinkController) else {
return nil
}
return RemoteNotificationsMarkReadOrUnreadOperation(project: project, apiController: apiController, modelController: modelController, identifierGroups: identifierGroups, shouldMarkRead: shouldMarkRead)
}
let completionOperation = BlockOperation {
DispatchQueue.main.async {
let errors = operations.compactMap { $0.error }
if errors.count > 0 {
completion?(.failure(RemoteNotificationsOperationsError.individualErrors(errors)))
} else {
completion?(.success(()))
}
}
}
for operation in operations {
completionOperation.addDependency(operation)
}
operationQueue.addOperations(operations + [completionOperation], waitUntilFinished: false)
}
func markAllAsRead(languageLinkController: MWKLanguageLinkController, completion: ((Result<Void, Error>) -> Void)? = nil) {
assert(Thread.isMainThread)
let wikisWithUnreadNotifications: Set<String>
do {
wikisWithUnreadNotifications = try modelController.distinctWikisWithUnreadNotifications()
} catch let error {
completion?(.failure(error))
return
}
let projects = wikisWithUnreadNotifications.compactMap { WikimediaProject(notificationsApiIdentifier: $0, languageLinkController: self.languageLinkController) }
let operations = projects.map { RemoteNotificationsMarkAllAsReadOperation(project: $0, apiController: self.apiController, modelController: self.modelController) }
let completionOperation = BlockOperation {
DispatchQueue.main.async {
let errors = operations.compactMap { $0.error }
if errors.count > 0 {
completion?(.failure(RemoteNotificationsOperationsError.individualErrors(errors)))
} else {
completion?(.success(()))
}
}
}
for operation in operations {
completionOperation.addDependency(operation)
}
self.operationQueue.addOperations(operations + [completionOperation], waitUntilFinished: false)
}
// MARK: Private
/// Generates the correct paging operation (Import or Refresh) based on a project's persisted imported state.
/// - Parameter project: WikimediaProject to evaluate
/// - Parameter isAppLanguageProject: Boolean if this project is for the app primary language
/// - Returns: Appropriate RemoteNotificationsPagingOperation subclass instance
private func pagingOperationForProject(_ project: WikimediaProject, isAppLanguageProject: Bool) -> RemoteNotificationsPagingOperation {
if modelController.isProjectAlreadyImported(project: project) {
return RemoteNotificationsRefreshOperation(project: project, apiController: self.apiController, modelController: modelController, needsCrossWikiSummary: isAppLanguageProject)
} else {
return RemoteNotificationsImportOperation(project: project, apiController: self.apiController, modelController: modelController, needsCrossWikiSummary: isAppLanguageProject)
}
}
private func secondaryProjects(appLanguage: MWKLanguageLink) -> [WikimediaProject] {
let otherLanguages = languageLinkController.preferredLanguages.filter { $0.languageCode != appLanguage.languageCode }
var secondaryProjects: [WikimediaProject] = otherLanguages.map { .wikipedia($0.languageCode, $0.localizedName, $0.languageVariantCode) }
secondaryProjects.append(.commons)
secondaryProjects.append(.wikidata)
return secondaryProjects
}
/// Method that instantiates the appropriate paging operations for fetching & persisting remote notifications and adds them to the operation queue. Must be called from main thread.
/// - Parameters:
/// - completion: Block to run after operations have completed.
private func kickoffPagingOperations(completion: @escaping (Result<Void, Error>) -> Void) {
assert(Thread.isMainThread)
guard let appLanguage = languageLinkController.appLanguage else {
completion(.failure(RemoteNotificationsOperationsError.failurePullingAppLanguage))
return
}
let appLanguageProject = WikimediaProject.wikipedia(appLanguage.languageCode, appLanguage.localizedName, appLanguage.languageVariantCode)
let secondaryProjects = secondaryProjects(appLanguage: appLanguage)
// basic operations first - primary language then secondary (languages, commons & wikidata)
let appLanguageOperation = pagingOperationForProject(appLanguageProject, isAppLanguageProject: true)
let secondaryOperations = secondaryProjects.map { project in
pagingOperationForProject(project, isAppLanguageProject: false)
}
// BEGIN: chained cross wiki operations
// this generates additional API calls to fetch extra unread messages by inspecting the app language operation's cross wiki summary notification object in its response
let crossWikiGroupOperation = RemoteNotificationsRefreshCrossWikiGroupOperation(appLanguageProject: appLanguageProject, secondaryProjects: secondaryProjects, languageLinkController: languageLinkController, apiController: apiController, modelController: modelController)
let crossWikiAdapterOperation = BlockOperation { [weak crossWikiGroupOperation] in
crossWikiGroupOperation?.crossWikiSummaryNotification = appLanguageOperation.crossWikiSummaryNotification
}
crossWikiAdapterOperation.addDependency(appLanguageOperation)
crossWikiGroupOperation.addDependency(crossWikiAdapterOperation)
// END: chained cross wiki operations
// BEGIN: chained reauthentication operations
// these will ask the authManager to reauthenticate if the app language operation has an unauthenticaated error code in it's response
// then it will cancel existing operations running and recursively call kickoffPagingOperations again
let reauthenticateOperation = RemoteNotificationsReauthenticateOperation(authManager: authManager)
let reauthenticateAdapterOperation = BlockOperation { [weak reauthenticateOperation] in
reauthenticateOperation?.appLanguageOperationError = appLanguageOperation.error
}
reauthenticateAdapterOperation.addDependency(appLanguageOperation)
reauthenticateOperation.addDependency(reauthenticateAdapterOperation)
let recursiveKickoffOperation = BlockOperation { [weak self] in
guard let self = self else {
return
}
if reauthenticateOperation.didReauthenticate {
DispatchQueue.main.async {
self.operationQueue.cancelAllOperations()
self.kickoffPagingOperations(completion: completion)
}
}
}
recursiveKickoffOperation.addDependency(reauthenticateOperation)
// END: chained reauthentication operations
let finalListOfOperations = [appLanguageOperation, crossWikiAdapterOperation, crossWikiGroupOperation, reauthenticateAdapterOperation, reauthenticateOperation, recursiveKickoffOperation] + secondaryOperations
let completionOperation = BlockOperation {
let errors = finalListOfOperations.compactMap { ($0 as? AsyncOperation)?.error }
if errors.count > 0 {
completion(.failure(RemoteNotificationsOperationsError.individualErrors(errors)))
} else {
completion(.success(()))
}
}
for operation in finalListOfOperations {
completionOperation.addDependency(operation)
}
self.operationQueue.addOperations(finalListOfOperations + [completionOperation], waitUntilFinished: false)
}
}
|
mit
|
fc9dac38392a15d7ce4b5aa06949b59e
| 48.923664 | 408 | 0.696789 | 6.086552 | false | false | false | false |
PGSSoft/AutoMate
|
AutoMateExample/AutoMateExampleUITests/ContactsSavedDataTests.swift
|
1
|
1810
|
//
// ContactsSavedDataTests.swift
// AutoMateExample
//
// Created by Bartosz Janda on 10.03.2017.
// Copyright © 2017 PGS Software. All rights reserved.
//
import XCTest
import AutoMate
class ContactsSavedDataTests: AppUITestCase {
// MARK: Arrange Page Objects
lazy var mainPage: MainPage = MainPage(in: self.app)
lazy var autoMateLaunchEnvironmentsPage: AutoMateLaunchEnvironmentsPage = AutoMateLaunchEnvironmentsPage(in: self.app)
lazy var contactsListPage: ContactsListPage = ContactsListPage(in: self.app)
// MARK: Data
lazy var contacts: ContactLaunchEnvironment = ContactLaunchEnvironment(shouldCleanBefore: false, resources: (fileName: "contacts", bundleName: "TestResourceBundle"))
let contact = Contact(firstName: "Given Name", lastName: "Family Name")
// MARK: Set up
override func setUp() {
super.setUp()
}
// MARK: Tests
func testAddContacts() {
let token = addUIInterruptionMonitor(withDescription: "calendar") { (alert) -> Bool in
guard let alertView = AddressBookAlert(element: alert) else {
XCTFail("Cannot create AddressBookAlert object")
return false
}
XCTAssertTrue(alertView.allowElement.exists)
alertView.allowElement.tap()
return true
}
TestLauncher.configureWithDefaultOptions(app, additionalOptions: [contacts]).launch()
mainPage.goToAutoMateLaunchEnvironments()
autoMateLaunchEnvironmentsPage.goToContactsView()
removeUIInterruptionMonitor(token)
let contactCell = contactsListPage.cell(for: contact)
XCTAssertTrue(contactCell.exists)
contactsListPage.tableView.swipe(to: contactCell.cell)
XCTAssertTrue(contactCell.isVisible)
}
}
|
mit
|
d1db18fa85b1a8ba336be026524ccf74
| 31.303571 | 169 | 0.695965 | 4.545226 | false | true | false | false |
Derek316x/AIDefinitionLookup
|
CameraContrast/ViewController.swift
|
1
|
1128
|
//
// ViewController.swift
// CameraContrast
//
// Created by Michael Kavouras on 9/20/15.
// Copyright © 2015 Mike Kavouras. All rights reserved.
//
import UIKit
import AVFoundation
import GPUImage
class ViewController: UIViewController {
var videoCamera:GPUImageVideoCamera?
@IBOutlet weak var gpuImage: GPUImageView!
override func viewDidLoad() {
super.viewDidLoad()
videoCamera = GPUImageVideoCamera(sessionPreset: AVCaptureSessionPreset640x480, cameraPosition: .Back)
videoCamera!.outputImageOrientation = .Portrait;
let filterGroup = GPUImageFilterGroup()
let filters = [Filters.Contrast, Filters.Saturation]
for filter in filters {
videoCamera?.addTarget(filter)
filter.addTarget(gpuImage)
filterGroup.addFilter(filter)
}
filters[0].addTarget(filters[1])
filterGroup.initialFilters = [filters[0]]
filterGroup.terminalFilter = filters[1];
filterGroup.addTarget(gpuImage)
videoCamera?.startCameraCapture()
}
}
|
mit
|
c3d10fcdb0f94977846a124ec7bcbdaf
| 25.209302 | 110 | 0.654836 | 4.964758 | false | false | false | false |
aeidelson/light-playground
|
swift_app/light-playground/ViewControllers/OptionsViewController.swift
|
1
|
4459
|
import UIKit
class OptionsViewController: UITableViewController, UIPopoverPresentationControllerDelegate {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
fatalError("Has not been implemented")
}
override init(style: UITableViewStyle) {
fatalError("Has not been implemented")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.modalPresentationStyle = .popover
self.popoverPresentationController?.delegate = self
}
// MARK: UIViewController
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadDefaults()
}
// MARK: UIPopoverPresentationControllerDelegate
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerShouldDismissPopover(
_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
self.dismiss(animated: false)
return true
}
// MARK: Internal
func setInitialValues(
exposure: CGFloat,
lightColor: LightColor,
absorption: FractionalLightColor,
diffusion: CGFloat
) {
exposureSlider.setValue(Float(exposure), animated: false)
lightRedSlider.setValue(Float(lightColor.r), animated: false)
lightGreenSlider.setValue(Float(lightColor.g), animated: false)
lightBlueSlider.setValue(Float(lightColor.b), animated: false)
// Surface color is the inverse of the absorption.
surfaceRedSlider.setValue(1.0 - Float(absorption.r), animated: false)
surfaceGreenSlider.setValue(1.0 - Float(absorption.g), animated: false)
surfaceBlueSlider.setValue(1.0 - Float(absorption.b), animated: false)
diffusionSlider.setValue(Float(diffusion), animated: false)
}
/// Called on viewWillAppear so setInitialValues can be called.
var loadDefaults: () -> Void = {}
var onExposureChange: (CGFloat) -> Void = { _ in }
var onLightColorChange: (LightColor) -> Void = { _ in }
var onAbsorptionChange: (FractionalLightColor) -> Void = { _ in }
var onDiffusionChange: (CGFloat) -> Void = { _ in }
// MARK: Interface builder outlets
@IBOutlet weak var exposureSlider: UISlider!
@IBOutlet weak var lightRedSlider: UISlider!
@IBOutlet weak var lightGreenSlider: UISlider!
@IBOutlet weak var lightBlueSlider: UISlider!
@IBOutlet weak var diffusionSlider: UISlider!
@IBOutlet weak var surfaceRedSlider: UISlider!
@IBOutlet weak var surfaceGreenSlider: UISlider!
@IBOutlet weak var surfaceBlueSlider: UISlider!
@IBAction func exposureChanged(_ sender: Any) {
onExposureChange(CGFloat(exposureSlider.value))
}
@IBAction func redLightColorChanged(_ sender: Any) {
lightColorChanged()
}
@IBAction func greenLightColorChanged(_ sender: Any) {
lightColorChanged()
}
@IBAction func blueLightColorChanged(_ sender: Any) {
lightColorChanged()
}
@IBAction func diffusionChanged(_ sender: Any) {
onDiffusionChange(CGFloat(diffusionSlider.value))
}
@IBAction func redPassChanged(_ sender: Any) {
passChanged()
}
@IBAction func greenPassChanged(_ sender: Any) {
passChanged()
}
@IBAction func bluePassChanged(_ sender: Any) {
passChanged()
}
@IBAction func onShowTutorial(_ sender: Any) {
guard let storyboard = self.storyboard else { preconditionFailure() }
present(OnboardingViewController.new(storyboard: storyboard), animated: false, completion: nil)
}
// MARK: Private
// A helper to combine the color sliders before calling `onLightColorChange`
private func lightColorChanged() {
// The values of the sliders should be constrained at the xib-level to 0-255.
onLightColorChange(LightColor(
r: UInt8(lightRedSlider.value),
g: UInt8(lightGreenSlider.value),
b: UInt8(lightBlueSlider.value)))
}
private func passChanged() {
// `Pass` is just the inverse/friendly version of absorption.
onAbsorptionChange(FractionalLightColor(
r: 1.0 - CGFloat(surfaceRedSlider.value),
g: 1.0 - CGFloat(surfaceGreenSlider.value),
b: 1.0 - CGFloat(surfaceBlueSlider.value)))
}
}
|
apache-2.0
|
cf66043a716f167152f88295688d5afb
| 31.786765 | 106 | 0.677955 | 4.768984 | false | false | false | false |
nsgeek/ELRouter
|
ELRouterTests/RouteCollectionTypeTests.swift
|
1
|
1939
|
//
// RouteCollectionTypeTests.swift
// ELRouter
//
// Created by Angelo Di Paolo on 12/10/15.
// Copyright © 2015 Walmart. All rights reserved.
//
import XCTest
@testable import ELRouter
class RouteCollectionTypeTests: XCTestCase {
func test_filterByName_returnsRoutesForValidName() {
let routeName = "filterByName"
let routes = [Route(routeName, type: .Other), Route(routeName, type: .Static), Route("otherName", type: .Static)]
let filteredRoutes = routes.filterByName(routeName)
XCTAssertFalse(filteredRoutes.isEmpty)
XCTAssertEqual(filteredRoutes.count, 2)
for route in filteredRoutes {
XCTAssertNotNil(route.name)
XCTAssertEqual(route.name, routeName)
}
}
func test_filterByName_returnsEmptyArrayForBogusName() {
let routeName = "filterByName"
let routes = [Route(routeName, type: .Other), Route(routeName, type: .Static)]
let filteredRoutes = routes.filterByName("bogusName")
XCTAssertTrue(filteredRoutes.isEmpty)
}
}
extension RouteCollectionTypeTests {
func test_filterByType_returnsRoutesForValidType() {
let routeName = "routesByType"
let routes = [Route(routeName, type: .Other), Route(routeName, type: .Other), Route(routeName, type: .Static)]
let filteredRoutes = routes.filterByType(.Other)
XCTAssertFalse(filteredRoutes.isEmpty)
XCTAssertEqual(filteredRoutes.count, 2)
for route in filteredRoutes {
XCTAssertEqual(route.type, RoutingType.Other)
}
}
func test_filterByType_returnsEmptyArrayForBogusType() {
let routeName = "routesByType"
let routes = [Route(routeName, type: .Other), Route(routeName, type: .Other)]
let filteredRoutes = routes.filterByType(.Static)
XCTAssertTrue(filteredRoutes.isEmpty)
}
}
|
mit
|
68e57e736eb43e6fb4a5c497306a0ae6
| 33 | 121 | 0.661507 | 4.33557 | false | true | false | false |
sufangliang/SFLQRCode
|
SFLQRCodeExample/ScanQRCodeVc.swift
|
1
|
6139
|
//
// ScanQRCodeVc.swift
// SFLQRCodeExample
//
// Created by sufangliang on 2017/5/25.
// Copyright © 2017年 sufangliang. All rights reserved.
//
import UIKit
import AVFoundation
class ScanQRCodeVc: UIViewController {
@IBOutlet weak var scanPan: UIImageView!
var scanSession : AVCaptureSession?
lazy var scanLine : UIImageView =
{
let scanLine = UIImageView()
scanLine.frame = CGRect(x: 0, y: 0, width: self.scanPan.bounds.width, height: 3)
scanLine.image = UIImage(named: "QRCode_ScanLine")
return scanLine
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "扫描二维码"
scanPan.addSubview(scanLine)
setupScanSession() }
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
startScan()
}
//开始扫描
fileprivate func startScan()
{
scanLine.layer.add(scanAnimation(), forKey: "scan")
guard let scanSession = scanSession else { return }
if !scanSession.isRunning
{
scanSession.startRunning()
}
}
//扫描动画
private func scanAnimation() -> CABasicAnimation
{
//让横线在扫描的区域内
let startPoint = CGPoint(x: scanLine .center.x , y: 1)
let endPoint = CGPoint(x: scanLine.center.x, y: scanPan.bounds.size.height - 2)
let translation = CABasicAnimation(keyPath: "position")
translation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
translation.fromValue = NSValue(cgPoint: startPoint)
translation.toValue = NSValue(cgPoint: endPoint)
translation.duration = 4.0
translation.repeatCount = MAXFLOAT
translation.autoreverses = true
return translation
}
func setupScanSession()
{
do
{
//设置捕捉设备
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
//设置设备输入输出
let input = try AVCaptureDeviceInput(device: device)
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
//设置会话
let scanSession = AVCaptureSession()
scanSession.canSetSessionPreset(AVCaptureSessionPresetHigh)
if scanSession.canAddInput(input)
{
scanSession.addInput(input)
}
if scanSession.canAddOutput(output)
{
scanSession.addOutput(output)
}
//设置扫描类型(二维码和条形码)
output.metadataObjectTypes = [
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code]
//预览图层
let scanPreviewLayer = AVCaptureVideoPreviewLayer(session:scanSession)
scanPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
scanPreviewLayer!.frame = view.layer.bounds
view.layer.insertSublayer(scanPreviewLayer!, at: 0)
//设置扫描区域
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVCaptureInputPortFormatDescriptionDidChange, object: nil, queue: nil, using: { (noti) in
output.rectOfInterest = (scanPreviewLayer?.metadataOutputRectOfInterest(for: self.scanPan.frame))!
})
//保存会话
self.scanSession = scanSession
}
catch
{
//摄像头不可用
let alertVC = UIAlertController(title: "温馨提示", message: "摄像头不可用", preferredStyle: .alert)
let entureAction = UIAlertAction(title: "确定", style: .destructive, handler: nil)
alertVC.addAction(entureAction)
self.present(alertVC, animated: true, completion: nil)
return
}
}
}
//扫描 -- 代理方法
extension ScanQRCodeVc : AVCaptureMetadataOutputObjectsDelegate
{
// 扫描完成代理方法
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)
{
//停止扫描
self.scanLine.layer.removeAllAnimations()
self.scanSession!.stopRunning()
//播放声音
guard let soundPath = Bundle.main.path(forResource: "noticeMusic.caf", ofType: nil) else { return }
guard let soundUrl = NSURL(string: soundPath) else { return }
var soundID:SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundUrl, &soundID)
AudioServicesPlaySystemSound(soundID)
//扫完完成
if metadataObjects.count > 0
{
if let resultObj = metadataObjects.first as? AVMetadataMachineReadableCodeObject
{
// 展示扫描的结果或者其他处理
}
}
}
///3.确认弹出框
func confirm(title:String?,message:String?,controller:UIViewController,handler: ( (UIAlertAction) -> Swift.Void)? = nil)
{
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let entureAction = UIAlertAction(title: "确定", style: .destructive, handler: handler)
alertVC.addAction(entureAction)
controller.present(alertVC, animated: true, completion: nil)
}
}
|
mit
|
5b00674ef0bd6b58f741dcd674a8b91a
| 30.068783 | 169 | 0.584809 | 5.397059 | false | false | false | false |
matrix-org/matrix-ios-sdk
|
MatrixSDKTests/Crypto/CryptoMachine/Device+Stub.swift
|
1
|
1452
|
//
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
#if DEBUG
import MatrixSDKCrypto
extension Device {
static func stub(
userId: String = "Alice",
deviceId: String = "Device1",
displayName: String = "Alice's iPhone",
isBlocked: Bool = false,
locallyTrusted: Bool = true,
crossSigningTrusted: Bool = true
) -> Device {
return .init(
userId: userId,
deviceId: deviceId,
keys: [
"ed25519:Device1": "ABC",
"curve25519:Device1": "XYZ",
],
algorithms: [
"ed25519",
"curve25519"
],
displayName: displayName,
isBlocked: isBlocked,
locallyTrusted: locallyTrusted,
crossSigningTrusted: crossSigningTrusted
)
}
}
#endif
|
apache-2.0
|
32e3c3edb1b9483ba80367b55e150d01
| 27.470588 | 75 | 0.608815 | 4.495356 | false | false | false | false |
thebluepotato/AlamoFuzi
|
Pods/Alamofire/Source/ServerTrustEvaluation.swift
|
1
|
27221
|
//
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts.
open class ServerTrustManager {
/// Determines whether all hosts for this `ServerTrustManager` must be evaluated. Defaults to `true`.
public let allHostsMustBeEvaluated: Bool
/// The dictionary of policies mapped to a particular host.
public let evaluators: [String: ServerTrustEvaluating]
/// Initializes the `ServerTrustManager` instance with the given evaluators.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
/// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
/// pinning for host3 and disabling evaluation for host4.
///
/// - Parameters:
/// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated.
/// Defaults to `true`.
/// - evaluators: A dictionary of evaluators mappend to hosts.
public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) {
self.allHostsMustBeEvaluated = allHostsMustBeEvaluated
self.evaluators = evaluators
}
/// Returns the `ServerTrustEvaluating` value for the given host, if one is set.
///
/// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
/// this method and implement more complex mapping implementations such as wildcards.
///
/// - Parameter host: The host to use when searching for a matching policy.
/// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise.
/// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching
/// evaluators are found.
open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
guard let evaluator = evaluators[host] else {
if allHostsMustBeEvaluated {
throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host))
}
return nil
}
return evaluator
}
}
/// A protocol describing the API used to evaluate server trusts.
public protocol ServerTrustEvaluating {
#if os(Linux)
// Implement this once Linux has API for evaluating server trusts.
#else
/// Evaluates the given `SecTrust` value for the given `host`.
///
/// - Parameters:
/// - trust: The `SecTrust` value to evaluate.
/// - host: The host for which to evaluate the `SecTrust` value.
/// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`.
func evaluate(_ trust: SecTrust, forHost host: String) throws
#endif
}
// MARK: - Server Trust Evaluators
/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the
/// host provided by the challenge. Applications are encouraged to always validate the host in production environments
/// to guarantee the validity of the server's certificate chain.
public final class DefaultTrustEvaluator: ServerTrustEvaluating {
private let validateHost: Bool
/// Creates a `DefaultTrustEvalutor`.
///
/// - Parameter validateHost: Determines whether or not the evaluator should validate the host. Defaults to `true`.
public init(validateHost: Bool = true) {
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
if validateHost {
try trust.af.performValidation(forHost: host)
}
try trust.af.performDefaultValidation(forHost: host)
}
}
/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate
/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates.
/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS
/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production
/// environments to guarantee the validity of the server's certificate chain.
public final class RevocationTrustEvaluator: ServerTrustEvaluating {
/// Represents the options to be use when evaluating the status of a certificate.
/// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants).
public struct Options: OptionSet {
/// Perform revocation checking using the CRL (Certification Revocation List) method.
public static let crl = Options(rawValue: kSecRevocationCRLMethod)
/// Consult only locally cached replies; do not use network access.
public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled)
/// Perform revocation checking using OCSP (Online Certificate Status Protocol).
public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod)
/// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.
public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL)
/// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a
/// "best attempt" basis, where failure to reach the server is not considered fatal.
public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse)
/// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the
/// certificate and the value of `preferCRL`.
public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod)
/// The raw value of the option.
public let rawValue: CFOptionFlags
/// Creates an `Options` value with the given `CFOptionFlags`.
///
/// - Parameter rawValue: The `CFOptionFlags` value to initialize with.
public init(rawValue: CFOptionFlags) {
self.rawValue = rawValue
}
}
private let performDefaultValidation: Bool
private let validateHost: Bool
private let options: Options
/// Creates a `RevocationTrustEvaluator`.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. Defaults to `true`.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. Defaults to `true`.
/// - options: The `Options` to use to check the revocation status of the certificate. Defaults to `.any`.
public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) {
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
self.options = options
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { (status, result) in
AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options))
}
}
}
/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned
/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate
/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate chain in production
/// environments.
public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating {
private let certificates: [SecCertificate]
private let acceptSelfSignedCertificates: Bool
private let performDefaultValidation: Bool
private let validateHost: Bool
/// Creates a `PinnedCertificatesTrustEvaluator`.
///
/// - Parameters:
/// - certificates: The certificates to use to evalute the trust. Defaults to all `cer`, `crt`,
/// `der` certificates in `Bundle.main`.
/// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaulation, allowing
/// self-signed certificates to pass. Defaults to `false`. THIS SETTING SHOULD BE
/// FALSE IN PRODUCTION!
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. Defaults to `true`.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. Defaults to `true`.
public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
acceptSelfSignedCertificates: Bool = false,
performDefaultValidation: Bool = true,
validateHost: Bool = true) {
self.certificates = certificates
self.acceptSelfSignedCertificates = acceptSelfSignedCertificates
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
guard !certificates.isEmpty else {
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
if acceptSelfSignedCertificates {
try trust.af.setAnchorCertificates(certificates)
}
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
let serverCertificatesData = Set(trust.af.certificateData)
let pinnedCertificatesData = Set(certificates.af.data)
let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData)
if !pinnedCertificatesInServerData {
throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host,
trust: trust,
pinnedCertificates: certificates,
serverCertificates: trust.af.certificates))
}
}
}
/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned
/// public keys match one of the server certificate public keys. By validating both the certificate chain and host,
/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate chain in production
/// environments.
public final class PublicKeysTrustEvaluator: ServerTrustEvaluating {
private let keys: [SecKey]
private let performDefaultValidation: Bool
private let validateHost: Bool
/// Creates a `PublicKeysTrustEvaluator`.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all
/// certificates included in the main bundle.
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. Defaults to `true`.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition to
/// performing the default evaluation, even if `performDefaultValidation` is `false`.
/// Defaults to `true`.
public init(keys: [SecKey] = Bundle.main.af.publicKeys,
performDefaultValidation: Bool = true,
validateHost: Bool = true) {
self.keys = keys
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
guard !keys.isEmpty else {
throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound)
}
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
let pinnedKeysInServerKeys: Bool = {
for serverPublicKey in trust.af.publicKeys {
for pinnedPublicKey in keys {
if serverPublicKey == pinnedPublicKey {
return true
}
}
}
return false
}()
if !pinnedKeysInServerKeys {
throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host,
trust: trust,
pinnedKeys: keys,
serverKeys: trust.af.publicKeys))
}
}
}
/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the
/// evaluators consider it valid.
public final class CompositeTrustEvaluator: ServerTrustEvaluating {
private let evaluators: [ServerTrustEvaluating]
/// Creates a `CompositeTrustEvaluator`.
///
/// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
public init(evaluators: [ServerTrustEvaluating]) {
self.evaluators = evaluators
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
try evaluators.evaluate(trust, forHost: host)
}
}
/// Disables all evaluation which in turn will always consider any server trust as valid.
///
/// THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!
public final class DisabledEvaluator: ServerTrustEvaluating {
public init() { }
public func evaluate(_ trust: SecTrust, forHost host: String) throws { }
}
// MARK: - Extensions
public extension Array where Element == ServerTrustEvaluating {
#if os(Linux)
// Add this same convenience method for Linux.
#else
/// Evaluates the given `SecTrust` value for the given `host`.
///
/// - Parameters:
/// - trust: The `SecTrust` value to evaluate.
/// - host: The host for which to evaluate the `SecTrust` value.
/// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
func evaluate(_ trust: SecTrust, forHost host: String) throws {
for evaluator in self {
try evaluator.evaluate(trust, forHost: host)
}
}
#endif
}
extension Bundle: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType: Bundle {
/// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
var certificates: [SecCertificate] {
return paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
guard
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
return certificate
}
}
/// Returns all public keys for the valid certificates in the bundle.
var publicKeys: [SecKey] {
return certificates.af.publicKeys
}
/// Returns all pathnames for the resources identified by the provided file extensions.
///
/// - Parameter types: The filename extensions locate.
/// - Returns: All pathnames for the given filename extensions.
func paths(forResourcesOfTypes types: [String]) -> [String] {
return Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) }))
}
}
extension SecTrust: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecTrust {
/// Attempts to validate `self` using the policy provided and transforming any error produced using the closure passed.
///
/// - Parameters:
/// - policy: The `SecPolicy` used to evaluate `self`.
/// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`.
/// - Throws: Any error from applying the `policy`, or the result of `errorProducer` if validation fails.
func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
try apply(policy: policy).af.validate(errorProducer: errorProducer)
}
/// Applies a `SecPolicy` to `self`, throwing if it fails.
///
/// - Parameter policy: The `SecPolicy`.
/// - Returns: `self`, with the policy applied.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason.
func apply(policy: SecPolicy) throws -> SecTrust {
let status = SecTrustSetPolicies(type, policy)
guard status.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type,
policy: policy,
status: status))
}
return type
}
/// Validate `self`, passing any failure values through `errorProducer`.
///
/// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an
/// `Error`.
/// - Throws: The `Error` produced by the `errorProducer` closure.
func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(type, &result)
guard status.af.isSuccess && result.af.isSuccess else {
throw errorProducer(status, result)
}
}
/// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain.
///
/// - Parameter certificates: The `SecCertificate`s to add to the chain.
/// - Throws: Any error produced when applying the new certificate chain.
func setAnchorCertificates(_ certificates: [SecCertificate]) throws {
// Add additional anchor certificates.
let status = SecTrustSetAnchorCertificates(type, certificates as CFArray)
guard status.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status,
certificates: certificates))
}
// Reenable system anchor certificates.
let systemStatus = SecTrustSetAnchorCertificatesOnly(type, true)
guard systemStatus.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: systemStatus,
certificates: certificates))
}
}
/// The public keys contained in `self`.
var publicKeys: [SecKey] {
return certificates.af.publicKeys
}
/// The `SecCertificate`s contained i `self`.
var certificates: [SecCertificate] {
return (0..<SecTrustGetCertificateCount(type)).compactMap { index in
SecTrustGetCertificateAtIndex(type, index)
}
}
/// The `Data` values for all certificates contained in `self`.
var certificateData: [Data] {
return certificates.af.data
}
/// Validates `self` after applying `SecPolicy.af.default`. This evaluation does not validate the hostname.
///
/// - Parameter host: The hostname, used only in the error output if validation fails.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
func performDefaultValidation(forHost host: String) throws {
try validate(policy: SecPolicy.af.default) { (status, result) in
AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result)))
}
}
/// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as
/// hostname validation.
///
/// - Parameter host: The hostname to use in the validation.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
func performValidation(forHost host: String) throws {
try validate(policy: SecPolicy.af.hostname(host)) { (status, result) in
AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result)))
}
}
}
extension SecPolicy: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecPolicy {
/// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match.
static let `default` = SecPolicyCreateSSL(true, nil)
/// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname.
///
/// - Parameter hostname: The hostname to validate against.
/// - Returns: The `SecPolicy`.
static func hostname(_ hostname: String) -> SecPolicy {
return SecPolicyCreateSSL(true, hostname as CFString)
}
/// Creates a `SecPolicy` which checks the revocation of certificates.
///
/// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation.
/// - Returns: The `SecPolicy`.
/// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed`
/// if the policy cannot be created.
static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy {
guard let policy = SecPolicyCreateRevocation(options.rawValue) else {
throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed)
}
return policy
}
}
extension Array: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == Array<SecCertificate> {
/// All `Data` values for the contained `SecCertificate`s.
var data: [Data] {
return type.map { SecCertificateCopyData($0) as Data }
}
/// All public `SecKey` values for the contained `SecCertificate`s.
var publicKeys: [SecKey] {
return type.compactMap { $0.af.publicKey }
}
}
extension SecCertificate: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecCertificate {
/// The public key for `self`, if it can be extracted.
var publicKey: SecKey? {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust)
guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil }
return SecTrustCopyPublicKey(createdTrust)
}
}
extension OSStatus: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == OSStatus {
/// Returns whether `self` is `errSecSuccess`.
var isSuccess: Bool { return type == errSecSuccess }
}
extension SecTrustResultType: AlamofireExtended {}
public extension AlamofireExtension where ExtendedType == SecTrustResultType {
/// Returns whether `self is `.unspecified` or `.proceed`.
var isSuccess: Bool {
return (type == .unspecified || type == .proceed)
}
}
|
mit
|
170f23ea508522e95e19521b1f93825b
| 48.224231 | 228 | 0.661401 | 5.438761 | false | false | false | false |
iamyuiwong/swift-sqlite
|
SwiftSQLiteDEMO/SwiftSQLiteDEMO/ViewController.swift
|
1
|
5535
|
// ViewController.swift
// 15/10/11.
import UIKit
private let TAG: String = "SQLiteHelperDEMO"
class ViewController: UIViewController {
override func viewDidLoad() {
Log.trace()
super.viewDidLoad()
/* Do any additional setup after loading the view */
let dpo = AppUtil.getAppDocPath()
if let dp = dpo {
Log.v(tag: TAG, items: "appDocPath", dp)
}
let _dbInst = SQLiteDB.getInstance(byDBName: "demodbx.sqlite")
if let dbInst = _dbInst {
/* create table */
let ctabxxSql = "CREATE TABLE IF NOT EXISTS " //
+ "`xx`" + " (" //
+ "`id`" + " TEXT PRIMARY KEY," //
+ "`from`" + " TEXT," //
+ "`to`" + " TEXT," //
+ "`type`" + " INTEGER," //
+ "`send`" + " INTEGER," //
+ "`content`" + " TEXT" + ");"
var ret = SQLiteHelper.create(tableBySql: ctabxxSql,
useDB: dbInst.db!)
if (ret > 0) {
Log.i(tag: TAG, items: "create success")
} else {
Log.e(tag: TAG, items: "create fail: \(ret)")
}
usleep(UInt32(5 * 1e6))
/* create tables */
let ctabsSqls = [
"CREATE TABLE IF NOT EXISTS " //
+ "`yy1`" + " (" //
+ "`id`" + " TEXT PRIMARY KEY," //
+ "`content`" + " TEXT" + ");",
"CREATE TABLE IF NOT EXISTS " //
+ "`yy2`" + " (" //
+ "`id`" + " TEXT PRIMARY KEY," //
+ "`content`" + " TEXT" + ");",
"CREATE TABLE IF NOT EXISTS " //
+ "`yy3`" + " (" //
+ "`id`" + " TEXT PRIMARY KEY," //
+ "`status`" + " INTEGER," //
+ "`time`" + " DATETIME," //
+ "`content`" + " TEXT" + ");",
]
ret = SQLiteHelper.create(tablesBySqls:
array<String>(values: ctabsSqls),
useDB: dbInst.db!)
if (ret > 0) {
Log.i(tag: TAG, items: "create 2 success: \(ret)")
} else {
Log.e(tag: TAG, items: "create 2 fail: \(ret)")
}
usleep(UInt32(5 * 1e6))
/* insert */
var insSql = "INSERT INTO `yy2` (`id`, `content`) VALUES "
insSql += " ('100001', 'hello');"
ret = SQLiteHelper.insert(bySql: insSql, useDB: dbInst.db)
Log.i(tag: TAG, items: "insert ret: \(ret)")
usleep(UInt32(5 * 1e6))
/* insert 2 */
let insSqls: array<String> = array<String>()
insSqls.append("INSERT INTO `yy3` (`id`, `status`, `time`) "
+ "VALUES ('200001', 99, '2015-10-01 00:00:00');")
insSqls.append("INSERT INTO `yy3` (`id`, `status`, `time`) "
+ "VALUES ('200002', 99, '2015-10-02 00:00:00');")
ret = SQLiteHelper.insert(bySqls: insSqls, useDB: dbInst.db)
Log.i(tag: TAG, items: "insert 2 ret: \(ret)")
usleep(UInt32(5 * 1e6))
/* insert 3 */
let vsl = array<Dictionary<String, String>>()
vsl.data!.append(["`id`": "'100001'", "`status`": "1",
"`content`": "'ccaaaa'"])
vsl.data!.append(["`id`": "'100002'", "`status`": "2",
"`content`": "'ccbbbb'"])
vsl.data!.append(["`id`": "'100003'", "`status`": "3",
"`content`": "'cccccc'"])
vsl.data!.append(["`id`": "'100004'", "`status`": "4",
"`content`": "'cccccd'"])
vsl.data!.append(["`id`": "'100005'", "`status`": "5",
"`content`": "'ccccce'"])
vsl.data!.append(["`id`": "'100006'", "`status`": "6",
"`content`": "'cccccf'"])
ret = SQLiteHelper.insert(valuesList: vsl, intoTab: "yy3",
withKeyList:
array<String>(values: ["`id`", "`status`", "`content`"]),
useDB: dbInst.db)
Log.i(tag: TAG, items: "insert 3 ret: \(ret)")
usleep(UInt32(5 * 1e6))
/* select */
var queSql = "SELECT * FROM `yy3`;"
var qres = SQLiteHelper.query(bySql: queSql, useDB: dbInst.db)
Log.i(tag: TAG, items: "select result code: \(qres.code)")
if (nil != qres.rows) {
for r in qres.rows! {
let c = r.data["id"]?.value
Log.v(tag: TAG, items: "row: \(r.data)", "c: \(c)")
}
}
usleep(UInt32(5 * 1e6))
/* select 2 */
queSql = "SELECT * FROM `yy3` WHERE `status` > 3 "
queSql += "AND `id` = '100005'"
Log.v(tag: TAG, items: queSql)
qres = SQLiteHelper.query(bySql: queSql, useDB: dbInst.db)
Log.i(tag: TAG, items: "select 2 result code: \(qres.code)")
if (nil != qres.rows) {
for r in qres.rows! {
let c = r.data["id"]?.value
Log.v(tag: TAG, items: "row: \(r.data)", "c: \(c)")
}
}
usleep(UInt32(5 * 1e6))
/* count */
var c = SQLiteHelper.count(itemsInTable: "yy3", useDB: dbInst.db)
Log.i(tag: TAG, items: "count: \(c)")
usleep(UInt32(5 * 1e6))
/* count 2 */
let climSql = "WHERE `status` > 3"
c = SQLiteHelper.count(itemsInTable: "yy3",
useDB: dbInst.db,
withSqlLimit: climSql)
Log.i(tag: TAG, items: "2 count: \(c)")
usleep(UInt32(5 * 1e6))
/* drop */
ret = SQLiteHelper.drop(tableByName: "yy1", useDB: dbInst.db)
if (ret > 0) {
Log.i(tag: TAG, items: "drop success: \(ret)")
} else {
Log.e(tag: TAG, items: "drop fail: \(ret)")
}
usleep(UInt32(5 * 1e6))
/* drop 2 */
ret = SQLiteHelper.drop(tablesByNames:
array<String>(values: ["yy1", "yy2"]), useDB: dbInst.db)
if (ret > 0) {
Log.i(tag: TAG, items: "drop 2 success: \(ret)")
} else {
Log.e(tag: TAG, items: "drop 2 fail: \(ret)")
}
usleep(UInt32(5 * 1e6))
/* db!.closeDB() */
SQLiteHelper.dropDB(byDBName: "demodbx.sqlite")
} else {
Log.e(tag: TAG, items: "SQLiteHelper.getInstance fail")
}
let log = AppUtil.getAppDocPath()! + "/log"
let ret = FileUtil.rm(ofPath: log, recurrence: true)
print("rm log ret: \(ret)")
}
override func didReceiveMemoryWarning() {
Log.w(tag: TAG, items: "didReceiveMemoryWarning")
super.didReceiveMemoryWarning()
/* Dispose of any resources that can be recreated. */
}
}
|
lgpl-3.0
|
687171f30263f4e8951aca760708038b
| 26.542289 | 68 | 0.549955 | 2.650862 | false | false | false | false |
akisute/ReactiveCocoaSwift
|
ReactiveCocoaSwift/Models/BaseModel.swift
|
1
|
2237
|
//
// BaseModel.swift
// ReactiveCocoaSwift
//
// Created by Ono Masashi on 2015/01/23.
// Copyright (c) 2015年 akisute. All rights reserved.
//
import Foundation
public class BaseModel: MTLModel, MTLJSONSerializing {
private var type: String!
public var modelType: String {
return self.type!
}
private class func typeName() -> String {
return NSStringFromClass(self).componentsSeparatedByString(".").last!
}
// MARK: - Mantle
public required init!(coder: NSCoder!) {
super.init(coder: coder)
self.type = self.dynamicType.typeName()
}
public override init!() {
super.init()
self.type = self.dynamicType.typeName()
}
public override init!(dictionary dictionaryValue: [NSObject : AnyObject]!, error: NSErrorPointer) {
super.init(dictionary: dictionaryValue, error: error)
self.type = self.dynamicType.typeName()
}
public class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! {
return [:]
}
public class func typeJSONTransformer() -> NSValueTransformer {
return MTLValueTransformer.reversibleTransformerWithBlock({ (fromValue) -> AnyObject! in
return self.typeName()
})
}
// MARK: - Mantle Utility
private class var dateFormatter: NSDateFormatter {
struct Static {
static let instance: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
return dateFormatter
}()
}
return Static.instance
}
public class func NSDateTransformer() -> NSValueTransformer {
return MTLValueTransformer.reversibleTransformerWithForwardBlock({ (jsonValue) -> AnyObject! in
let string = jsonValue as String
return self.dateFormatter.dateFromString(string)
}, reverseBlock: { (objectValue) -> AnyObject! in
let date = objectValue as NSDate
return self.dateFormatter.stringFromDate(date)
})
}
}
|
mit
|
50f085b99d84f463d06c0024936e7e4c
| 30.041667 | 103 | 0.61745 | 5.068027 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.