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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lvogelzang/Blocky
|
Blocky/Levels/Level75.swift
|
1
|
877
|
//
// Level75.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level75: Level {
let levelNumber = 75
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
|
mit
|
7542def9b9e081cd14000fa55394e7a0
| 24.794118 | 89 | 0.573546 | 2.649547 | false | false | false | false |
zyphs21/HSStockChart
|
HSStockChart/KLineChart/HSKLineView.swift
|
1
|
12940
|
//
// HSKLineView.swift
// HSStockChartDemo
//
// Created by Hanson on 2017/2/16.
// Copyright © 2017年 hanson. All rights reserved.
//
import UIKit
public let TimeLineLongpress = "TimeLineLongpress"
public let TimeLineUnLongpress = "TimeLineUnLongpress"
public let TimeLineChartDidTap = "TimeLineChartDidTap"
public let KLineChartLongPress = "kLineChartLongPress"
public let KLineChartUnLongPress = "kLineChartUnLongPress"
public let KLineUperChartDidTap = "KLineUperChartDidTap"
public class HSKLineView: UIView {
var scrollView: UIScrollView!
var kLine: HSKLine!
var upFrontView: HSKLineUpFrontView!
var kLineType: HSChartType!
var widthOfKLineView: CGFloat = 0
var theme = HSKLineStyle()
public var dataK: [HSKLineModel] = []
public var isLandscapeMode = false
public var allDataK: [HSKLineModel] = []
var enableKVO: Bool = true
var kLineViewWidth: CGFloat = 0.0
var oldRightOffset: CGFloat = -1
var uperChartHeight: CGFloat {
get {
return theme.uperChartHeightScale * self.frame.height
}
}
var lowerChartTop: CGFloat {
get {
return uperChartHeight + theme.xAxisHeitht
}
}
public init(frame: CGRect, kLineType: HSChartType, theme: HSKLineStyle?, priceLabelText: String? = nil, volumeLabelText: String? = nil) {
super.init(frame: frame)
backgroundColor = UIColor.white
if let t = theme
{
self.theme = t
}
drawFrameLayer()
scrollView = UIScrollView(frame: bounds)
scrollView.showsHorizontalScrollIndicator = true
scrollView.alwaysBounceHorizontal = true
scrollView.delegate = self
scrollView.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), options: .new, context: nil)
addSubview(scrollView)
kLine = HSKLine()
kLine.setTheme(theme: self.theme)
kLine.kLineType = kLineType
scrollView.addSubview(kLine)
upFrontView = HSKLineUpFrontView(frame: bounds, priceLabelText: priceLabelText, volumeLabelText: volumeLabelText)
addSubview(upFrontView)
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGestureAction(_:)))
kLine.addGestureRecognizer(longPressGesture)
let pinGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinGestureAction(_:)))
kLine.addGestureRecognizer(pinGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureAction(_:)))
kLine.addGestureRecognizer(tapGesture)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
scrollView.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset))
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(UIScrollView.contentOffset) && enableKVO {
print("in klineview scrollView?.contentOffset.x " + "\(scrollView.contentOffset.x)")
// 拖动 ScrollView 时重绘当前显示的 klineview
kLine.contentOffsetX = scrollView.contentOffset.x
kLine.renderWidth = scrollView.frame.width
kLine.drawKLineView()
upFrontView.configureAxis(max: kLine.maxPrice, min: kLine.minPrice, maxVol: kLine.maxVolume)
}
}
public func configureView(data: [HSKLineModel]) {
dataK = data
kLine.dataK = data
let count: CGFloat = CGFloat(data.count)
// 总长度
kLineViewWidth = count * theme.candleWidth + (count + 1) * theme.candleGap
if kLineViewWidth < self.frame.width {
kLineViewWidth = self.frame.width
} else {
kLineViewWidth = count * theme.candleWidth + (count + 1) * theme.candleGap
}
// 更新view长度
print("currentWidth " + "\(kLineViewWidth)")
kLine.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: kLineViewWidth, height: scrollView.frame.height)
var contentOffsetX: CGFloat = 0
if scrollView.contentSize.width > 0 {
contentOffsetX = kLineViewWidth - scrollView.contentSize.width
} else {
// 首次加载,将 kLine 的右边和scrollview的右边对齐
contentOffsetX = kLine.frame.width - scrollView.frame.width
}
scrollView.contentSize = CGSize(width: kLineViewWidth, height: self.frame.height)
scrollView.contentOffset = CGPoint(x: contentOffsetX, y: 0)
kLine.contentOffsetX = scrollView.contentOffset.x
print("ScrollKLine contentOffsetX " + "\(contentOffsetX)")
}
func updateKlineViewWidth() {
let count: CGFloat = CGFloat(kLine.dataK.count)
// 总长度
kLineViewWidth = count * theme.candleWidth + (count + 1) * theme.candleGap
if kLineViewWidth < self.frame.width {
kLineViewWidth = self.frame.width
} else {
kLineViewWidth = count * theme.candleWidth + (count + 1) * theme.candleGap
}
// 更新view长度
print("currentWidth " + "\(kLineViewWidth)")
kLine.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: kLineViewWidth, height: scrollView.frame.height)
scrollView.contentSize = CGSize(width: kLineViewWidth, height: self.frame.height)
}
// 画边框
func drawFrameLayer() {
// K线图
let uperFramePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: frame.width, height: uperChartHeight))
// K线图 内上边线 即最高价格线
uperFramePath.move(to: CGPoint(x: 0, y: theme.viewMinYGap))
uperFramePath.addLine(to: CGPoint(x: frame.maxX, y: theme.viewMinYGap))
// K线图 内下边线 即最低价格线
uperFramePath.move(to: CGPoint(x: 0, y: uperChartHeight - theme.viewMinYGap))
uperFramePath.addLine(to: CGPoint(x: frame.maxX, y: uperChartHeight - theme.viewMinYGap))
// K线图 中间的横线
uperFramePath.move(to: CGPoint(x: 0, y: uperChartHeight / 2.0))
uperFramePath.addLine(to: CGPoint(x: frame.maxX, y: uperChartHeight / 2.0))
let uperFrameLayer = CAShapeLayer()
uperFrameLayer.lineWidth = theme.frameWidth
uperFrameLayer.strokeColor = theme.borderColor.cgColor
uperFrameLayer.fillColor = UIColor.clear.cgColor
uperFrameLayer.path = uperFramePath.cgPath
// 交易量图
let volFramePath = UIBezierPath(rect: CGRect(x: 0, y: uperChartHeight + theme.xAxisHeitht, width: frame.width, height: frame.height - uperChartHeight - theme.xAxisHeitht))
// 交易量图 内上边线 即最高交易量格线
volFramePath.move(to: CGPoint(x: 0, y: uperChartHeight + theme.xAxisHeitht + theme.volumeGap))
volFramePath.addLine(to: CGPoint(x: frame.maxX, y: uperChartHeight + theme.xAxisHeitht + theme.volumeGap))
let volFrameLayer = CAShapeLayer()
volFrameLayer.lineWidth = theme.frameWidth
volFrameLayer.strokeColor = theme.borderColor.cgColor
volFrameLayer.fillColor = UIColor.clear.cgColor
volFrameLayer.path = volFramePath.cgPath
self.layer.addSublayer(uperFrameLayer)
self.layer.addSublayer(volFrameLayer)
}
// 长按操作
@objc func handleLongPressGestureAction(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .began || recognizer.state == .changed {
let point = recognizer.location(in: kLine)
var highLightIndex = Int(point.x / (theme.candleWidth + theme.candleGap))
var positionModelIndex = highLightIndex - kLine.startIndex
highLightIndex = highLightIndex <= 0 ? 0 : highLightIndex
positionModelIndex = positionModelIndex <= 0 ? 0 : positionModelIndex
if highLightIndex < kLine.dataK.count && positionModelIndex < kLine.positionModels.count {
let entity = kLine.dataK[highLightIndex]
let left = kLine.startX + CGFloat(highLightIndex - kLine.startIndex) * (self.theme.candleWidth + theme.candleGap) - scrollView.contentOffset.x
let centerX = left + theme.candleWidth / 2.0
let highLightVolume = kLine.positionModels[positionModelIndex].volumeStartPoint.y
let highLightClose = kLine.positionModels[positionModelIndex].closeY
let preIndex = (highLightIndex - 1 >= 0) ? (highLightIndex - 1) : highLightIndex
let preData = kLine.dataK[preIndex]
upFrontView.drawCrossLine(pricePoint: CGPoint(x: centerX, y: highLightClose), volumePoint: CGPoint(x: centerX, y: highLightVolume), model: entity, chartType: kLine.kLineType)
let userInfo: [AnyHashable: Any]? = ["preClose" : preData.close, "kLineEntity" : entity]
NotificationCenter.default.post(name: Notification.Name(rawValue: KLineChartLongPress), object: self, userInfo: userInfo)
}
}
if recognizer.state == .ended {
upFrontView.removeCrossLine()
NotificationCenter.default.post(name: Notification.Name(rawValue: KLineChartUnLongPress), object: self)
}
}
// 捏合缩放扩大操作
@objc func handlePinGestureAction(_ recognizer: UIPinchGestureRecognizer) {
guard recognizer.numberOfTouches == 2 else { return }
let scale = recognizer.scale
let originScale: CGFloat = 1.0
let kLineScaleFactor: CGFloat = 0.06
let kLineScaleBound: CGFloat = 0.03
let diffScale = scale - originScale // 获取缩放倍数
switch recognizer.state {
case .began:
enableKVO = false
scrollView.isScrollEnabled = false
default:
enableKVO = true
scrollView.isScrollEnabled = true
}
if abs(diffScale) > kLineScaleBound {
let point1 = recognizer.location(ofTouch: 0, in: self)
let point2 = recognizer.location(ofTouch: 1, in: self)
let pinCenterX = (point1.x + point2.x) / 2
let scrollViewPinCenterX = pinCenterX + scrollView.contentOffset.x
// 中心点数据index
let pinCenterLeftCount = scrollViewPinCenterX / (theme.candleWidth + theme.candleGap)
// 缩放后的candle宽度
let newCandleWidth = theme.candleWidth * (recognizer.velocity > 0 ? (1 + kLineScaleFactor) : (1 - kLineScaleFactor))
if newCandleWidth > theme.candleMaxWidth {
self.theme.candleWidth = theme.candleMaxWidth
kLine.theme.candleWidth = theme.candleMaxWidth
} else if newCandleWidth < theme.candleMinWidth {
self.theme.candleWidth = theme.candleMinWidth
kLine.theme.candleWidth = theme.candleMinWidth
} else {
self.theme.candleWidth = newCandleWidth
kLine.theme.candleWidth = newCandleWidth
}
// 更新容纳的总长度
self.updateKlineViewWidth()
let newPinCenterX = pinCenterLeftCount * theme.candleWidth + (pinCenterLeftCount - 1) * theme.candleGap
let newOffsetX = newPinCenterX - pinCenterX
self.scrollView.contentOffset = CGPoint(x: newOffsetX > 0 ? newOffsetX : 0 , y: self.scrollView.contentOffset.y)
kLine.contentOffsetX = scrollView.contentOffset.x
kLine.drawKLineView()
}
}
/// 处理点击事件
@objc func handleTapGestureAction(_ recognizer: UITapGestureRecognizer) {
if !isLandscapeMode {
let point = recognizer.location(in: kLine)
if point.y < lowerChartTop {
NotificationCenter.default.post(name: Notification.Name(rawValue: KLineUperChartDidTap), object: self.tag)
}
}
}
}
extension HSKLineView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
// MARK: - 用于滑动加载更多 KLine 数据
if (scrollView.contentOffset.x < 0 && dataK.count < allDataK.count) {
self.oldRightOffset = scrollView.contentSize.width - scrollView.contentOffset.x
print("load more")
self.configureView(data: allDataK)
} else {
}
}
}
|
mit
|
acfea9704f1a557ac5cd0f97a5735302
| 40.310458 | 190 | 0.635551 | 4.318756 | false | false | false | false |
mottx/XCGLogger
|
Sources/XCGLogger/Destinations/TestDestination.swift
|
5
|
3200
|
//
// TestDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2016-08-26.
// Copyright © 2016 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Dispatch
// MARK: - TestDestination
/// A destination for testing, preload it with the expected logs, send your logs, then check for success
open class TestDestination: BaseQueuedDestination {
// MARK: - Properties
/// Array of all expected log messages
open var expectedLogMessages: [String] = []
/// Array of received, unexpected log messages
open var unexpectedLogMessages: [String] = []
/// Number of log messages still expected
open var remainingNumberOfExpectedLogMessages: Int {
get {
return expectedLogMessages.count
}
}
/// Number of unexpected log messages
open var numberOfUnexpectedLogMessages: Int {
get {
return unexpectedLogMessages.count
}
}
/// Add the messages you expect to be logged
///
/// - Parameters:
/// - expectedLogMessage: The log message, formated as you expect it to be received.
///
/// - Returns: Nothing
///
open func add(expectedLogMessage message: String) {
sync {
expectedLogMessages.append(message)
}
}
/// Execute a closure on the logQueue if it exists, otherwise just execute on the current thread
///
/// - Parameters:
/// - closure: The closure to execute.
///
/// - Returns: Nothing
///
fileprivate func sync(closure: () -> ()) {
if let logQueue = logQueue {
logQueue.sync {
closure()
}
}
else {
closure()
}
}
/// Reset our expectations etc for additional tests
///
/// - Parameters: Nothing
///
/// - Returns: Nothing
///
open func reset() {
haveLoggedAppDetails = false
expectedLogMessages = []
unexpectedLogMessages = []
}
// MARK: - Overridden Methods
/// Removes line from expected log messages if there's a match, otherwise adds to unexpected log messages.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func output(logDetails: LogDetails, message: String) {
sync {
var logDetails = logDetails
var message = message
// Apply filters, if any indicate we should drop the message, we abort before doing the actual logging
if self.shouldExclude(logDetails: &logDetails, message: &message) {
return
}
applyFormatters(logDetails: &logDetails, message: &message)
let index = expectedLogMessages.index(of: message)
if let index = index {
expectedLogMessages.remove(at: index)
}
else {
unexpectedLogMessages.append(message)
}
}
}
}
|
mit
|
d559b4d3f3f9099ac4bf5b92331678b6
| 28.348624 | 114 | 0.587684 | 4.944359 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/CheckoutShippingLineUpdatePayload.swift
|
1
|
5778
|
//
// CheckoutShippingLineUpdatePayload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Return type for `checkoutShippingLineUpdate` mutation.
open class CheckoutShippingLineUpdatePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CheckoutShippingLineUpdatePayload
/// The updated checkout object.
@discardableResult
open func checkout(alias: String? = nil, _ subfields: (CheckoutQuery) -> Void) -> CheckoutShippingLineUpdatePayloadQuery {
let subquery = CheckoutQuery()
subfields(subquery)
addField(field: "checkout", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func checkoutUserErrors(alias: String? = nil, _ subfields: (CheckoutUserErrorQuery) -> Void) -> CheckoutShippingLineUpdatePayloadQuery {
let subquery = CheckoutUserErrorQuery()
subfields(subquery)
addField(field: "checkoutUserErrors", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `checkoutUserErrors` instead.")
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CheckoutShippingLineUpdatePayloadQuery {
let subquery = UserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `checkoutShippingLineUpdate` mutation.
open class CheckoutShippingLineUpdatePayload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CheckoutShippingLineUpdatePayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "checkout":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue)
}
return try Checkout(fields: value)
case "checkoutUserErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CheckoutUserError(fields: $0) }
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UserError(fields: $0) }
default:
throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue)
}
}
/// The updated checkout object.
open var checkout: Storefront.Checkout? {
return internalGetCheckout()
}
func internalGetCheckout(alias: String? = nil) -> Storefront.Checkout? {
return field(field: "checkout", aliasSuffix: alias) as! Storefront.Checkout?
}
/// The list of errors that occurred from executing the mutation.
open var checkoutUserErrors: [Storefront.CheckoutUserError] {
return internalGetCheckoutUserErrors()
}
func internalGetCheckoutUserErrors(alias: String? = nil) -> [Storefront.CheckoutUserError] {
return field(field: "checkoutUserErrors", aliasSuffix: alias) as! [Storefront.CheckoutUserError]
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `checkoutUserErrors` instead.")
open var userErrors: [Storefront.UserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "checkout":
if let value = internalGetCheckout() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutUserErrors":
internalGetCheckoutUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
|
mit
|
8600adc3ae9ba8c4f3ec678dd1720c4a
| 36.519481 | 143 | 0.733645 | 4.28 | false | false | false | false |
cactuslab/Succulent
|
Succulent/Classes/Tracer.swift
|
1
|
14588
|
//
// Tracer.swift
// Succulent
//
// Created by Thomas Carey on 6/03/17.
// Copyright © 2017 Cactuslab. All rights reserved.
//
import Foundation
/// Provides support for reading and writing the trace format from Charles Proxy
/// Conform to this protocol if you output to the trace format
protocol Traceable {
var traceFormat: String { get }
}
struct TraceMeta: Traceable {
var method: String?
var protocolScheme: String?
var host: String?
var file: String?
var version: String?
var traceFormat: String {
var trace = [String]()
if let method = method {
trace.append("Method: \(method)")
}
if let version = version {
trace.append("Protocol-Version: \(version)")
}
if let protocolScheme = protocolScheme {
trace.append("Protocol: \(protocolScheme)")
}
if let host = host {
trace.append("Host: \(host)")
}
if let file = file {
trace.append("File: \(file)")
}
return "\n\(trace.joined(separator: "\n"))"
}
init(method: String?, protocolScheme: String?, host: String?, file: String?, version: String?) {
self.method = method
self.protocolScheme = protocolScheme
self.host = host
self.file = file
self.version = version
}
init(dictionary: [String: String]) {
self = TraceMeta(method: dictionary["Method"], protocolScheme: dictionary["Protocol"], host: dictionary["Host"], file: dictionary["File"], version: dictionary["Protocol-Version"])
}
}
extension Request: Traceable {
var traceFormat: String {
var trace = [String]()
trace.append("\(method) \(path)")
self.headers?.forEach({ (key, value) in
trace.append("\(key): \(value)")
})
return trace.joined(separator: "\n")
}
}
extension HTTPURLResponse: Traceable {
var traceFormat: String {
var trace = [String]()
trace.append("HTTP/1.1 \(statusCode)")
self.allHeaderFields.forEach { (key, value) in
trace.append("\(key): \(value)")
}
return trace.joined(separator: "\n").appending("\n")
}
}
class TraceWriter {
enum Component {
case meta
case requestHeader
case requestBody
case responseHeader
case responseBody
var name: String? {
switch self {
case .meta: return nil
case .requestBody: return "Request-Body"
case .requestHeader: return "Request-Header"
case .responseBody: return "Response-Body"
case .responseHeader: return "Response-Header"
}
}
func headerPart(token: String) -> String {
if let name = self.name {
return "\(name):<<--EOF-\(token)-\n"
} else {
return "\n"
}
}
func footerPart(token: String) -> String {
if let _ = self.name {
return "\n--EOF-\(token)-\n"
} else {
return "\n"
}
}
}
let fileURL: URL
init(fileURL: URL) {
self.fileURL = fileURL
writeHeader()
}
private func writeHeader() {
let headerString = "HTTP-Trace-Version: 1.0\nGenerator: Succulent/1.0\n"
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
if fileHandle.offsetInFile == 0 {
fileHandle.write(headerString.data(using: .utf8)!)
}
} else {
try! headerString.appendToURL(fileURL: fileURL)
}
}
func writeComponent(component: Component, content: Data, token: String) throws {
try component.headerPart(token: token).appendToURL(fileURL: fileURL)
try content.append(fileURL: fileURL)
try component.footerPart(token: token).appendToURL(fileURL: fileURL)
}
func writeComponent(component: Component, content: Traceable, token: String) throws {
let parts = [component.headerPart(token: token), content.traceFormat, component.footerPart(token: token)]
try parts.joined(separator: "").appendToURL(fileURL: fileURL)
}
}
extension String {
fileprivate func appendLineToURL(fileURL: URL) throws {
try (self + "\n").appendToURL(fileURL: fileURL)
}
fileprivate func appendToURL(fileURL: URL) throws {
let data = self.data(using: String.Encoding.utf8)!
try data.append(fileURL: fileURL)
}
}
extension Data {
fileprivate func append(fileURL: URL) throws {
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
}
else {
let directoryURL = fileURL.deletingLastPathComponent()
try? FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
try write(to: fileURL, options: .atomic)
}
}
}
struct Trace {
var meta : TraceMeta
var responseHeader : Data?
var responseBody: Data
}
class TraceReader {
let fileURL: URL
let delimiter = "\n"
let tokenStartRegex = try! NSRegularExpression(pattern: "^(.+):<<--EOF-(.+)-$", options: [])
let metaRegex = try! NSRegularExpression(pattern: "^(.+): (.+)$", options: [])
init(fileURL: URL) {
self.fileURL = fileURL
}
func readFile() -> [Trace]? {
guard let fileHandle = FileHandle(forReadingAtPath: fileURL.path) else {
return nil
}
defer {
fileHandle.closeFile()
}
if consumeHeader(fileHandle: fileHandle) {
var traces = [Trace]()
while let trace = consumeTrace(fileHandle: fileHandle) {
traces.append(trace)
}
return traces
}
return nil
}
private func consumeHeader(fileHandle: FileHandle) -> Bool {
let offset = fileHandle.offsetInFile
guard let data = fileHandle.readLine(withDelimiter: "\n") else {
fileHandle.seek(toFileOffset: offset)
return false
}
guard let contents = String(data: data, encoding: .ascii), contents == "HTTP-Trace-Version: 1.0\n" else {
fileHandle.seek(toFileOffset: offset)
return false
}
// lets just consume the next line
let _ = fileHandle.readLine(withDelimiter: "\n")
let _ = fileHandle.consumeEmptyLines()
return true
}
enum ComponentType : String {
case responseHeader = "Response-Header"
case responseBody = "Response-Body"
}
struct Component {
var type: ComponentType
var data: Data
}
private func consumeTrace(fileHandle: FileHandle) -> Trace? {
while(testForEmptyLine(fileHandle: fileHandle)) {
if !consumeLines(count: 1, fileHandle: fileHandle) {
return nil
}
}
var meta = [String: String]()
// Consume the Metas
while(!testStartOfComponent(fileHandle: fileHandle)) {
if let data = fileHandle.readLine(withDelimiter: delimiter) {
if let line = String(data: data, encoding: .utf8) {
let matches = metaRegex.matches(in: line, options: [], range: line.nsrange)
matches.forEach({ (match) in
let key = line.substring(with: match.range(at: 1))!
let value = line.substring(with: match.range(at: 2))!
meta[key] = value
})
}
} else {
// At the end of the file
return nil
}
}
var responseHeader : Data?
var responseBody : Data?
// Consume components until no longer at the start
while(testStartOfComponent(fileHandle: fileHandle)) {
if let component = consumeComponent(fileHandle: fileHandle) {
switch component.type {
case .responseBody:
responseBody = component.data
case .responseHeader:
responseHeader = component.data
}
}
}
if let responseBody = responseBody {
return Trace(meta: TraceMeta(dictionary: meta), responseHeader: responseHeader, responseBody: responseBody)
}
return nil
}
private func testStartOfComponent(fileHandle: FileHandle) -> Bool {
let startingOffset = fileHandle.offsetInFile
defer {
fileHandle.seek(toFileOffset: startingOffset)
}
guard let data = fileHandle.readLine(withDelimiter: delimiter), let line = String(data: data, encoding: .utf8) else {
return false
}
let matches = tokenStartRegex.matches(in: line, options: [], range: line.nsrange)
return matches.count > 0
}
private func consumeComponent(fileHandle: FileHandle) -> Component? {
let startingOffset = fileHandle.offsetInFile
guard let data = fileHandle.readLine(withDelimiter: delimiter), let line = String(data: data, encoding: .utf8) else {
fileHandle.seek(toFileOffset: startingOffset)
return nil
}
let matches = tokenStartRegex.matches(in: line, options: [], range: line.nsrange)
if matches.count > 0 {
let contentType = line.substring(with: matches[0].range(at: 1))!
let token = line.substring(with: matches[0].range(at: 2))!
guard let data = consumeData(forToken: token, fileHandle: fileHandle) else {
//Hit the end of the file
return nil
}
guard let componentType = ComponentType(rawValue: contentType) else {
//Unrecognised component
//discard the component and move on
return nil
}
return Component(type: componentType, data: data)
} else {
// not the start of content but could be the start of meta
fileHandle.seek(toFileOffset: startingOffset)
return nil
}
}
private func testForEmptyLine(fileHandle: FileHandle) -> Bool {
return testFor("", fileHandle: fileHandle)
}
private func testForToken(fileHandle: FileHandle, token:String) -> Bool {
return testFor("--EOF-\(token)-", fileHandle: fileHandle)
}
private func testFor(_ str :String, fileHandle: FileHandle) -> Bool {
let startingOffset = fileHandle.offsetInFile
defer {
fileHandle.seek(toFileOffset: startingOffset)
}
if let data = fileHandle.readLine(withDelimiter: delimiter) {
if let line = String(data: data, encoding: .utf8) {
if line == "\(str)\(delimiter)" {
return true
}
}
}
return false
}
private func consumeToken(fileHandle: FileHandle) -> Bool {
return consumeLines(count: 1, fileHandle: fileHandle)
}
private func consumeLines(count: Int, fileHandle: FileHandle) -> Bool {
for _ in (0..<count) {
guard let _ = fileHandle.readLine(withDelimiter: delimiter) else {
return false
}
}
return true
}
private func consumeData(forToken token: String, fileHandle: FileHandle) -> Data? {
let startingOffset = fileHandle.offsetInFile
while (!testForToken(fileHandle: fileHandle, token: token)) {
if(!consumeLines(count: 1, fileHandle: fileHandle)) {
return nil
}
}
let endingOffset = fileHandle.offsetInFile
fileHandle.seek(toFileOffset: startingOffset)
let data = fileHandle.readData(ofLength: Int(endingOffset - UInt64(fileHandle.delimiterLength(delimiter)) - startingOffset))
fileHandle.seek(toFileOffset: endingOffset)
let _ = consumeToken(fileHandle: fileHandle)
return data
}
}
extension FileHandle {
fileprivate func consumeEmptyLines() -> Int {
var offset = offsetInFile
var data = self.readLine(withDelimiter: "\n")
var counter = 0
while (data != nil) {
if let contents = String(data: data!, encoding: .ascii), contents == "\n" {
counter += 1
offset = offsetInFile
data = self.readLine(withDelimiter: "\n")
} else {
seek(toFileOffset: offset)
return counter
}
}
return counter
}
}
extension String {
/// An `NSRange` that represents the full range of the string.
var nsrange: NSRange {
return NSRange(location: 0, length: utf16.count)
}
/// Returns a substring with the given `NSRange`,
/// or `nil` if the range can't be converted.
func substring(with nsrange: NSRange) -> String? {
guard let range = Range(nsrange)
else { return nil }
let start = String.Index(utf16Offset: range.lowerBound, in: self)
let end = String.Index(utf16Offset: range.upperBound, in: self)
return String(utf16[start..<end])
}
/// Returns a range equivalent to the given `NSRange`,
/// or `nil` if the range can't be converted.
func range(from nsrange: NSRange) -> Range<Index>? {
guard let range = Range(nsrange) else { return nil }
let utf16Start = String.Index(utf16Offset: range.lowerBound, in: self)
let utf16End = String.Index(utf16Offset: range.upperBound, in: self)
guard let start = Index(utf16Start, within: self),
let end = Index(utf16End, within: self)
else { return nil }
return start..<end
}
}
|
mit
|
ddd52a1899940bf095739f05103292ac
| 30.849345 | 187 | 0.558374 | 4.839748 | false | false | false | false |
GermanCentralLibraryForTheBlind/LargePrintMusicNotes
|
LargePrintMusicNotesViewer/LoginViewController.swift
|
1
|
4522
|
// Created by Lars Voigt.
//
//The MIT License (MIT)
//Copyright (c) 2016 German Central Library for the Blind (DZB)
//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
class LoginViewController: UIViewController {
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var password: UITextField!
var connector = RESTConnector()
var compositionsJSON = [[String:AnyObject]]()
@IBAction func login(_ sender: AnyObject) {
let username = self.userName.text
let password = self.password.text
// Validate the text fields
if username!.characters.count < 1 {
showAlert("Ungültig", alertMessage: "Bitte geben Sie einen Nutzernamen ein.");
} else if password!.characters.count < 1 {
showAlert("Ungültig", alertMessage: "Bitte geben Sie das Passwort ein.");
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 150, height: 150)) as UIActivityIndicatorView
spinner.startAnimating()
self.connector.getUserData(username!, password: password!) {
(compositionsJSON, error) in
// Stop the spinner
spinner.stopAnimating()
self.compositionsJSON = compositionsJSON
if(error == nil) {
DispatchQueue.main.async{
self.performSegue(withIdentifier: "Compositions", sender:self)
}
} else {
self.showAlert("Anmeldung fehlgeschlagen", alertMessage: error!);
}
return
}
}
}
func showAlert(_ title: String, alertMessage : String) {
let alertController = UIAlertController(title: title,
message: alertMessage,
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Ok",
style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
/*
// 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.
}
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is CompositionsViewController {
let compositionsViewController : CompositionsViewController = segue.destination as! CompositionsViewController
compositionsViewController.populateTable(compositionsJSON)
}
}
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.
}
}
|
mit
|
d9b51f87c08e58fb40a501401ca780c0
| 36.983193 | 153 | 0.61969 | 5.512195 | false | false | false | false |
keshavvishwkarma/KVConstraintKit
|
KVConstraintKit/ApplyViewConstraint.swift
|
1
|
10047
|
//
// ApplyViewConstraint.swift
// https://github.com/keshavvishwkarma/KVConstraintKit.git
//
// Distributed under the MIT License.
//
// Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. 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.
//
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
// MARK: - TO APPLY PREPARED SELF CONSTRAINTS -
extension View
{
// All of the below methods of this extension are used to Apply\Add constraint in receiver view (self ).
/// Sets the aspect ratio of a view.
@available(*, deprecated: 1.2, message: "Use 'applyAspectRatio' instead")
@discardableResult public final func applyAspectRatioConstraint() -> View {
return applyAspectRatio()
}
/// Sets the width of a view.
/// - Parameter width: A CGFloat value.
@available(*, deprecated: 1.2, message: "Use 'applyWidth' instead")
@discardableResult public final func applyWidthConstraint(_ width: CGFloat) -> View {
return applyWidth(width)
}
/// Sets the height of a view.
/// - Parameter height: A CGFloat value.
@available(*, deprecated: 1.2, message: "Use 'applyHeight' instead")
@discardableResult public final func applyHeightConstraint(_ height: CGFloat) -> View {
return applyHeight(height)
}
/// Sets the at least height of a view.
/// - Parameter height: A CGFloat value.
@available(*, deprecated: 1.2, message: "Use 'applyAtLeastHeight' instead")
@discardableResult public final func applyAtLeastHeightConstraint(_ height: CGFloat) -> View {
return applyAtLeastHeight(height)
}
/// Sets the at most height of a view.
/// - Parameter height: A CGFloat value.
@available(*, deprecated: 1.2, message: "Use 'applyAtMostHeight' instead")
@discardableResult public final func applyAtMostHeightConstraint(_ height: CGFloat) -> View {
return applyAtMostHeight(height)
}
/// Sets the at least width of a view.
/// - Parameter width: A CGFloat value.
@available(*, deprecated: 1.2, message: "Use 'applyAtLeastWidth' instead")
@discardableResult public final func applyAtLeastWidthConstraint(_ width: CGFloat) -> View {
return applyAtLeastWidth(width)
}
/// Sets the at most width of a view.
/// - Parameter width: A CGFloat value.
@available(*, deprecated: 1.2, message: "Use 'applyAtMostWidth' instead")
@discardableResult public final func applyAtMostWidthConstraint(_ width: CGFloat) -> View {
return applyAtMostWidth(width)
}
}
// MARK : - TO APPLIED PREPARED CONSTRAINTS
extension View
{
// All the below methods of this category are used to applied\add constraints in supreview of receiver view (self)
/// A receiver view is aligned from the left with padding.
/// - Parameter padding: A CGFloat value to the left side padding.
@available(*, deprecated: 1.2, message: "Use 'applyLeft' instead")
@discardableResult public final func applyLeftPinConstraintToSuperview(_ padding: CGFloat) -> View {
return applyLeft(padding)
}
/// A receiver view is aligned from the right with padding.
/// - Parameter padding: A CGFloat value to the right side padding.
@available(*, deprecated: 1.2, message: "Use 'applyRight' instead")
@discardableResult public final func applyRightPinConstraintToSuperview(_ padding: CGFloat) -> View {
return applyRight(padding)
}
/// A receiver view is aligned from the top with padding.
/// - Parameter padding: A CGFloat value to the top side padding.
@available(*, deprecated: 1.2, message: "Use 'applyTop' instead")
@discardableResult public final func applyTopPinConstraintToSuperview(_ padding: CGFloat) -> View {
return applyTop(padding)
}
/// A receiver view is aligned from the bottom with padding.
/// - Parameter padding: A CGFloat value to the bottom side padding.
@available(*, deprecated: 1.2, message: "Use 'applyBottom' instead")
@discardableResult public final func applyBottomPinConstraintToSuperview(_ padding: CGFloat) -> View {
return applyBottom(padding)
}
/// A receiver view is aligned from the left with padding.
/// - Parameter padding: A CGFloat value to the left side padding.
@available(*, deprecated: 1.2, message: "Use 'applyLeading' instead")
@discardableResult public final func applyLeadingPinConstraintToSuperview(_ padding: CGFloat) -> View {
return applyLeading(padding)
}
/// A receiver view is aligned from the right with padding.
/// - Parameter padding: A CGFloat value to the right side padding.
@available(*, deprecated: 1.2, message: "Use 'applyTrailing' instead")
@discardableResult public final func applyTrailingPinConstraintToSuperview(_ padding: CGFloat) -> View {
return applyTrailing(padding)
}
/// To horizontally Center a receiver view in it's superview with an optional offset value.
/// - Parameter offsetX: A CGFloat value for the offset along the x axis.
@available(*, deprecated: 1.2, message: "Use 'applyCenterX' instead")
@discardableResult public final func applyCenterXPinConstraintToSuperview(_ offsetX: CGFloat) -> View {
return applyCenterX(offsetX)
}
/// To vertically Center a receiver view in it's superview with an optional offset value.
/// - Parameter offsetY: A CGFloat value for the offset along the y axis.
@available(*, deprecated: 1.2, message: "Use 'applyCenterY' instead")
@discardableResult public final func applyCenterYPinConstraintToSuperview(_ offsetY: CGFloat) -> View {
return applyCenterY(offsetY)
}
}
// MARK: - TO APPLY PREPARED CONSTRAINTS FOR CENTERING VIEW
extension View
{
/// Centers the view horizontally in its `superview` with an optional offset.
/// - Parameter offsetX: A CGFloat value for the offset along the x axis.
/// - Returns: Itself, enabling chaining.
@available(*, deprecated: 1.2, message: "Use 'applyCenterX' instead")
public final func applyConstraintToCenterHorizontallyInSuperview(_ offsetX: CGFloat = 0) -> View {
return applyCenterX(offsetX)
}
/// Centers the view vertically in its superview with an optional offset.
/// - Parameter offsetY: A CGFloat value for the offset along the y axis
/// - Returns: Itself, enabling chaining.
@available(*, deprecated: 1.2, message: "Use 'applyCenterY' instead")
public final func applyConstraintToCenterVerticallyInSuperview(_ offsetY: CGFloat = 0) -> View {
return applyCenterY(offsetY)
}
/// Centers the view horizontally & vertically in its superview with an optional offset.
/// - Parameter offset: A CGFloat value for the offset along the x & y axis.
/// - Returns: Itself, enabling chaining.
@available(*, deprecated: 1.2, message: "Use 'applyCenter' instead")
public final func applyConstraintToCenterInSuperview(_ offset:CGPoint = CGPoint.zero) -> View {
return applyCenter()
}
}
extension View
{
/// To apply\add same leading, trailing, Top and Bottom pin constraints to superview with same optional padding.
/// - Parameter padding: A CGFloat value to the all side (left, right, top & bottm) padding between the receiver view & its superview.
@available(*, deprecated: 1.2, message: "Use 'fitToSuperview' instead")
@discardableResult public final func applyConstraintFitToSuperview(_ padding: CGFloat = 0) -> View {
return fitToSuperview(padding)
}
/// To apply\add same leading and trailing pin constraints to superview with same optional padding.
/// - Parameter padding: A CGFloat value to the left & right side padding between the receiver view & its superview.
@available(*, deprecated: 1.2, message: "Use 'fitHorizontallyToSuperview' instead")
@discardableResult public final func applyConstraintFitHorizontallyToSuperview(_ padding: CGFloat = 0) -> View {
return fitVerticallyToSuperview(padding)
}
/// To apply\add same top and bottom pin constraints to superview with same optional padding.
/// - Parameter padding: A CGFloat value to the top & bottom side padding between the receiver view & its superview.
@available(*, deprecated: 1.2, message: "Use 'fitVerticallyToSuperview' instead")
@discardableResult public final func applyConstraintFitVerticallyToSuperview(_ padding: CGFloat = 0) -> View {
return fitVerticallyToSuperview(padding)
}
/// To apply\add same leading, trailing, top and bottom pin constraints to superview with optional content inset.
@available(*, deprecated: 1.2, message: "Use 'fitToSuperview(contentInset:)' instead")
@discardableResult public final func applyConstraintFitToSuperview(contentInset inset: EdgeInsets) -> View {
return fitToSuperview(contentInset:inset)
}
}
|
mit
|
e7d620521d963f0227903719a0aa45ab
| 45.725581 | 138 | 0.703265 | 4.580939 | false | false | false | false |
rhodgkins/RDHDecimalNumberOperations
|
Tests/RDHDecimalNumberOperationsTests/SubtractionTests.swift
|
1
|
8593
|
//
// SubtractionTests.swift
// RDHDecimalNumberOperations
//
// Created by Richard Hodgkins on 29/11/2014.
// Copyright (c) 2014 Rich H. All rights reserved.
//
import Foundation
#if os(watchOS)
// No testing supported
@testable import RDHDecimalNumberOperations
#else
import XCTest
#if DEBUG
@testable import RDHDecimalNumberOperations
#else
import RDHDecimalNumberOperations
#endif
class SubtractionTests: XCTestCase {
// MARK: - Infix
func testPositiveNumbers() {
XCTAssertEqual(NSDecimalNumber.one() - NSDecimalNumber.one(), NSDecimalNumber.one().decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
let leftNumber = NSDecimalNumber(string: "4")
let rightNumber = NSDecimalNumber(string: "6.5")
XCTAssertEqual(leftNumber - rightNumber, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber - leftNumber, rightNumber.decimalNumberBySubtracting(leftNumber), "Incorrect")
XCTAssertEqual(leftNumber - NSDecimalNumber.zero(), leftNumber, "Should not change")
XCTAssertEqual(NSDecimalNumber.zero() - NSDecimalNumber.zero(), NSDecimalNumber.zero(), "Should be zero")
}
func testNegativeNumbers() {
XCTAssertEqual(NSDecimalNumber.minusOne - NSDecimalNumber.minusOne, NSDecimalNumber.minusOne.decimalNumberBySubtracting(NSDecimalNumber.minusOne), "Incorrect")
let leftNumber = NSDecimalNumber(string: "-8")
let rightNumber = NSDecimalNumber(string: "-7.9")
XCTAssertEqual(leftNumber - rightNumber, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber - leftNumber, rightNumber.decimalNumberBySubtracting(leftNumber), "Incorrect")
XCTAssertEqual(leftNumber - NSDecimalNumber.zero(), leftNumber, "Should not change")
}
func testPostiveToNegativeNumbers() {
XCTAssertEqual(NSDecimalNumber.one() - NSDecimalNumber.minusOne, NSDecimalNumber.one().decimalNumberBySubtracting(NSDecimalNumber.minusOne), "Incorrect")
let leftNumber = NSDecimalNumber(string: "12")
let rightNumber = NSDecimalNumber(string: "-90.1")
XCTAssertEqual(leftNumber - rightNumber, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber - leftNumber, rightNumber.decimalNumberBySubtracting(leftNumber), "Incorrect")
}
func testNegativeToPostiveNumbers() {
XCTAssertEqual(NSDecimalNumber.minusOne - NSDecimalNumber.one(), NSDecimalNumber.minusOne.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
let leftNumber = NSDecimalNumber(string: "-12122.32")
let rightNumber = NSDecimalNumber(string: "23")
XCTAssertEqual(leftNumber - rightNumber, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber - leftNumber, rightNumber.decimalNumberBySubtracting(leftNumber), "Incorrect")
}
// MARK: - Assignment
func testAssignmentWithPositiveNumbers() {
let leftNumber = NSDecimalNumber(string: "4")
let rightNumber = NSDecimalNumber(string: "6.5")
var result = leftNumber
result -= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
result -= NSDecimalNumber.zero()
XCTAssertEqual(result, result, "Should not change")
}
func testAssignmentWithNegativeNumbers() {
let leftNumber = NSDecimalNumber(string: "-8")
let rightNumber = NSDecimalNumber(string: "-7.9")
var result = leftNumber
result -= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
result -= NSDecimalNumber.zero()
XCTAssertEqual(result, result, "Should not change")
}
func testAssignmentWithPostiveToNegativeNumbers() {
let leftNumber = NSDecimalNumber(string: "12")
let rightNumber = NSDecimalNumber(string: "-90.1")
var result = leftNumber
result -= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
result -= NSDecimalNumber.zero()
XCTAssertEqual(result, result, "Should not change")
}
func testAssignmentWithNegativeToPostiveNumbers() {
let leftNumber = NSDecimalNumber(string: "-12122.32")
let rightNumber = NSDecimalNumber(string: "23")
var result = leftNumber
result -= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberBySubtracting(rightNumber), "Incorrect")
result -= NSDecimalNumber.zero()
XCTAssertEqual(result, result, "Should not change")
}
// MARK: - Prefix
func testPrefixWithPositiveNumbers() {
let value = NSDecimalNumber(string: "34")
var incrementing = value
let result = --incrementing
XCTAssertEqual(incrementing, value.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(result, value.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(result, incrementing, "Incorrect")
}
func testPrefixWithNegativeNumbers() {
let value = NSDecimalNumber(string: "-383")
var incrementing = value
let result = --incrementing
XCTAssertEqual(incrementing, value.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(result, value.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(result, incrementing, "Incorrect")
}
// MARK: - Suffix
func testSuffixWithPositiveNumbers() {
let value = NSDecimalNumber(string: "234")
var incrementing = value
let result = incrementing--
XCTAssertEqual(incrementing, value.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(result, value, "Incorrect")
XCTAssertNotEqual(result, incrementing, "Incorrect")
XCTAssertEqual(result.decimalNumberBySubtracting(NSDecimalNumber.one()), incrementing, "Incorrect")
}
func testSuffixWithNegativeNumbers() {
let value = NSDecimalNumber(string: "-4358")
var incrementing = value
let result = incrementing--
XCTAssertEqual(incrementing, value.decimalNumberBySubtracting(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(result, value, "Incorrect")
XCTAssertNotEqual(result, incrementing, "Incorrect")
XCTAssertEqual(result.decimalNumberBySubtracting(NSDecimalNumber.one()), incrementing, "Incorrect")
}
// MARK: - Unary negation
func testNegationWithPositiveNumbers() {
let value = NSDecimalNumber(string: "9351.3214")
let negatedValue = -value
XCTAssertEqual(negatedValue, value.decimalNumberByMultiplyingBy(NSDecimalNumber.minusOne), "Incorrect")
}
func testNegationWithNegativeNumbers() {
let value = NSDecimalNumber(string: "-234.0234")
let negatedValue = -value
XCTAssertEqual(negatedValue, value.decimalNumberByMultiplyingBy(NSDecimalNumber.minusOne), "Incorrect")
}
func testNegationWithZero() {
let value = NSDecimalNumber.zero()
let negatedValue = -value
XCTAssertEqual(negatedValue, value, "Incorrect")
XCTAssertEqual(negatedValue, value.decimalNumberByMultiplyingBy(NSDecimalNumber.minusOne), "Incorrect")
}
func testDoubleNegation() {
let value = NSDecimalNumber(string: "-234.0234")
let negatedValue = -(-value)
XCTAssertEqual(negatedValue, value, "Incorrect")
}
// MARK: - Overflow
func testOverflow() {
let leftNumber = NSDecimalNumber.maximumDecimalNumber()
let rightNumber = NSDecimalNumber.minimumDecimalNumber()
XCTAssertEqual(leftNumber &- rightNumber, NSDecimalNumber.notANumber(), "Should not throw an exception and be NaN")
}
}
#endif
|
mit
|
a331048925af315eee0e7c104290058a
| 35.565957 | 167 | 0.667055 | 5.459339 | false | true | false | false |
kwizzad/kwizzad-ios
|
Source/Reward.swift
|
1
|
7403
|
//
// Reward.swift
// KwizzadSDK
//
// Created by Sandro Manke on 20.10.16.
// Copyright © 2016 Kwizzad. All rights reserved.
//
import Foundation
func enumerateAsText(_ array: [String]) -> String? {
switch (array.count) {
case 0: return nil;
case 1: return array[0];
case 2:
let format = LocalizedString("%@ and %@", comment: "Joins two strings with an 'and' to generate a human-readable enumeration");
return String.init(format: format, array[0], array[1]);
default:
let format = LocalizedString("%@, and %@", comment: "Joins a list of comma-separated values with a last values to form a human-readable enumeration (e.g. with oxford comma)");
return String.init(format: format, array.dropLast().joined(separator: ", "), array.last!);
}
}
/// Reward object obtained when an ad is available.
@objc(KwizzadReward)
open class Reward : NSObject, FromDict {
/// Defines the amount of the reward.
public let amount : NSNumber?
/// Defines the currency of the reward.
public let currency : String?
/// Optional: maximal potential amount of the reward. The actual reward the user receives can be lower than this.
public let maxAmount : NSNumber?
/// Optional: Defines the state to user has to reach to be rewarded.
public let type : String?
let UnknownType = "UNKNOWN";
/// Initialize the reward model with a JSON object.
public required init(_ map: [String : Any]) {
amount = map["amount"] as? NSNumber
maxAmount = map["maxAmount"] as? NSNumber
currency = map["currency"] as? String
if let rt = map["type"] as? String? {
if let type = rt {
self.type = type
}
else {
type = UnknownType
}
}
else {
type = UnknownType
}
}
public init(amount: Int, maxAmount: Int, currency: String) {
self.amount = amount as NSNumber;
self.maxAmount = maxAmount as NSNumber;
self.currency = currency;
self.type = UnknownType;
}
/// - returns: a string that describes the (potential) reward that you can
/// display to a user.
public func valueDescription() -> String? {
if let maxAmount = self.maxAmount, let currency = self.currency {
if (maxAmount.intValue > 0) {
let format = LocalizedString("up to %@", comment: "Description of an amount with an upper limit");
return String.init(format: format, "\(maxAmount.intValue) \(currency)");
}
}
if let amount = self.amount, let currency = self.currency {
return "\(amount.intValue) \(currency)"
}
return nil;
}
/// - returns: A string that describes the (potential) reward that you can
@objc
public func valueOrMaxValue() -> NSNumber? {
if let maxAmount = self.maxAmount {
if (maxAmount.intValue > 0) {
return maxAmount;
}
}
if let amount = self.amount {
return amount;
}
return nil;
}
public static func limitedAmountString(maxAmount: Int, currency: String) -> String {
let format = LocalizedString("up to %@", comment: "Description of an amount with an upper limit");
return String.init(format: format, "\(maxAmount) \(currency)");
}
public static func staticAmountString(amount: Int, currency: String) -> String {
return "\(amount) \(currency)";
}
/// use for debugging rewards.
public func asDebugString() -> String? {
if let maxAmount = self.maxAmount, let currency = self.currency {
if (maxAmount.intValue > 0) {
return "up to \(maxAmount) \(currency) for \(String(describing: type))"
}
}
if let amount = self.amount, let currency = self.currency {
return "\(amount) \(currency) for \(String(describing: type))"
}
return nil;
}
/// - returns: One `Reward` object for each found currency in the given rewards. The amount of each reward
/// is the sum of the given reward amounts in the same currency.
public static func summarize(rewards: [Reward]) -> [Reward] {
var rewardsByCurrency: [String: [Reward]] = [:]
for reward in rewards {
if let currency = reward.currency {
if case nil = rewardsByCurrency[currency]?.append(reward) {
rewardsByCurrency[currency] = [reward]
}
}
}
return rewardsByCurrency.flatMap({ (key: String, value: [Reward]) -> Reward in
let amount = value.reduce(0) { $0 + ($1.amount?.intValue ?? 0) }
let maxAmount = value.reduce(0) { $0 + ($1.maxAmount?.intValue ?? 0) }
return Reward(amount: amount, maxAmount: maxAmount, currency: key);
})
}
/// Returns a text describing the given rewards. This does not take maximal amounts into account.
public static func enumerateRewardsAsText(rewards: [Reward]) -> String? {
guard !rewards.isEmpty else { return nil };
return enumerateAsText(summarize(rewards: rewards).flatMap({ $0.valueDescription() }));
}
/// Returns a text that you can use to incentivize the user to earn the given rewards.
public static func incentiveTextFor(rewards: [Reward]) -> String? {
let currencyCount = Set(rewards.flatMap({ $0.currency })).count;
if (currencyCount == 0) {
return nil;
}
let formatString = LocalizedString("Earn %@ with a quiz.", comment: "Can be shown as incentive text, for example on an ad banner. First parameter is the potential total reward.");
if (currencyCount == 1) {
let totalAmount = rewards.reduce(0) { $0 + ($1.amount?.intValue ?? 0) };
let maxTotalAmount = rewards.reduce(0) { $0 + ($1.maxAmount?.intValue ?? $1.amount?.intValue ?? 0) };
let currency = rewards[0].currency ?? "";
let hasPotentiallyHigherAmount = maxTotalAmount > totalAmount;
let rewardsHaveDifferentTypes = Set(rewards.flatMap({ $0.type })).count > 1;
let useRewardWithLimit = hasPotentiallyHigherAmount || rewardsHaveDifferentTypes;
let potentialTotalReward = useRewardWithLimit ? limitedAmountString(maxAmount: maxTotalAmount, currency: currency) : staticAmountString(amount: totalAmount, currency: currency);
return String.init(format: formatString, potentialTotalReward);
}
let potentialTotalReward = enumerateAsText(rewards.flatMap({ $0.valueDescription() })) ?? "";
return String.init(format: formatString, potentialTotalReward);
}
public static func confirmationText(rewards: [Reward]) -> String {
if let enumeration = enumerateRewardsAsText(rewards: rewards) {
let format = LocalizedString("Congratulations, you earned %@!", comment: "Shown in a confirmation dialog when the user earns a known, specific reward.");
return String.init(format: format, enumeration);
}
return LocalizedString("Congratulations, you earned a reward!", comment: "Shown in a confirmation dialog when the user earns an unspecified reward.");
}
}
|
mit
|
4730446a21f4cd9a2ca1ad75b95fb632
| 40.79096 | 189 | 0.611464 | 4.450662 | false | false | false | false |
vasili-v/themis
|
vendor/github.com/apache/thrift/lib/swift/Sources/TApplicationError.swift
|
9
|
5773
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
public struct TApplicationError : TError {
public enum Code : TErrorCode {
case unknown
case unknownMethod(methodName: String?)
case invalidMessageType
case wrongMethodName(methodName: String?)
case badSequenceId
case missingResult(methodName: String?)
case internalError
case protocolError
case invalidTransform
case invalidProtocol
case unsupportedClientType
/// Initialize a TApplicationError with a Thrift error code
/// Normally this would be achieved with RawRepresentable however
/// by doing this we can allow for associated properties on enum cases for
/// case specific context data in a Swifty, type-safe manner.
///
/// - parameter thriftErrorCode: Integer TApplicationError(exception) error code.
/// Default to 0 (.unknown)
public init(thriftErrorCode: Int) {
switch thriftErrorCode {
case 1: self = .unknownMethod(methodName: nil)
case 2: self = .invalidMessageType
case 3: self = .wrongMethodName(methodName: nil)
case 4: self = .badSequenceId
case 5: self = .missingResult(methodName: nil)
case 6: self = .internalError
case 7: self = .protocolError
case 8: self = .invalidProtocol
case 9: self = .invalidTransform
case 10: self = .unsupportedClientType
default: self = .unknown
}
}
public var thriftErrorCode: Int {
switch self {
case .unknown: return 0
case .unknownMethod: return 1
case .invalidMessageType: return 2
case .wrongMethodName: return 3
case .badSequenceId: return 4
case .missingResult: return 5
case .internalError: return 6
case .protocolError: return 7
case .invalidProtocol: return 8
case .invalidTransform: return 9
case .unsupportedClientType: return 10
}
}
public var description: String {
/// Output "for #methodName" if method is not nil else empty
let methodUnwrap: (String?) -> String = { method in
return "\(method == nil ? "" : " for \(method ?? "")")"
}
switch self {
case .unknown: return "Unknown TApplicationError"
case .unknownMethod(let method): return "Unknown Method\(methodUnwrap(method))"
case .invalidMessageType: return "Invalid Message Type"
case .wrongMethodName(let method): return "Wrong Method Name\(methodUnwrap(method))"
case .badSequenceId: return "Bad Sequence ID"
case .missingResult(let method): return "Missing Result\(methodUnwrap(method))"
case .internalError: return "Internal Error"
case .protocolError: return "Protocol Error"
case .invalidProtocol: return "Invalid Protocol"
case .invalidTransform: return "Invalid Transform"
case .unsupportedClientType: return "Unsupported Client Type"
}
}
}
public init() { }
public init(thriftErrorCode code: Int, message: String? = nil) {
self.error = Code(thriftErrorCode: code)
self.message = message
}
public var error: Code = .unknown
public var message: String? = nil
public static var defaultCase: Code { return .unknown }
}
extension TApplicationError : TSerializable {
public static var thriftType: TType { return .struct }
public static func read(from proto: TProtocol) throws -> TApplicationError {
var errorCode: Int = 0
var message: String? = nil
_ = try proto.readStructBegin()
fields: while true {
let (_, fieldType, fieldID) = try proto.readFieldBegin()
switch (fieldID, fieldType) {
case (_, .stop):
break fields
case (1, .string):
message = try proto.read()
case (2, .i32):
errorCode = Int(try proto.read() as Int32)
case let (_, unknownType):
try proto.skip(type: unknownType)
}
try proto.readFieldEnd()
}
try proto.readStructEnd()
return TApplicationError(thriftErrorCode: errorCode, message: message)
}
public func write(to proto: TProtocol) throws {
try proto.writeStructBegin(name: "TApplicationException")
try proto.writeFieldBegin(name: "message", type: .string, fieldID: 1)
try proto.write(message ?? "")
try proto.writeFieldEnd()
try proto.writeFieldBegin(name: "type", type: .i32, fieldID: 2)
let val = Int32(error.thriftErrorCode)
try proto.write(val)
try proto.writeFieldEnd()
try proto.writeFieldStop()
try proto.writeStructEnd()
}
public var hashValue: Int {
return error.thriftErrorCode &+ (message?.hashValue ?? 0)
}
}
public func ==(lhs: TApplicationError, rhs: TApplicationError) -> Bool {
return lhs.error.thriftErrorCode == rhs.error.thriftErrorCode && lhs.message == rhs.message
}
|
apache-2.0
|
3e6deafa1ebff03dc9c5a6c7040d746c
| 35.770701 | 93 | 0.652867 | 4.556433 | false | false | false | false |
tadija/mappable
|
Sources/Mappable.swift
|
1
|
3522
|
import Foundation
public protocol Mappable {
var map: [String : Any] { get }
init(map: [String : Any]) throws
}
public enum MappableError: Error {
case mappingFailed
case valueMissing(forKey: String)
case valueTypeWrong(forKey: String)
}
public extension Mappable {
public var map: [String : Any] {
var map = [String : Any]()
Mirror(reflecting: self).children.forEach { property in
if let propertyName = property.label {
if let object = property.value as? Mappable {
map[propertyName] = object.map
} else if let objectArray = property.value as? [Mappable] {
map[propertyName] = objectArray.map { $0.map }
} else {
map[propertyName] = property.value
}
}
}
return map
}
}
public extension Mappable {
public init(jsonData: Data, options: JSONSerialization.ReadingOptions = .allowFragments) throws {
if let json = try JSONSerialization.jsonObject(with: jsonData, options: options) as? [String : Any] {
try self.init(map: json)
} else {
throw MappableError.mappingFailed
}
}
public func json(options: JSONSerialization.WritingOptions = .prettyPrinted) throws -> Data {
let data = try JSONSerialization.data(withJSONObject: map, options: options)
return data
}
public static func mappableArray<T: Mappable>(with jsonData: Data,
options: JSONSerialization.ReadingOptions = .allowFragments) throws -> [T] {
guard let json = try JSONSerialization.jsonObject(with: jsonData, options: options) as? [Any] else {
throw MappableError.mappingFailed
}
let mappableArray: [T] = try json.mappableArray()
return mappableArray
}
}
public extension Dictionary where Key: ExpressibleByStringLiteral {
public func value<T>(forKey key: String) throws -> T {
guard let value = self[key as! Key] else {
throw MappableError.valueMissing(forKey: key)
}
guard let typedValue = value as? T else {
throw MappableError.valueTypeWrong(forKey: key)
}
return typedValue
}
public func mappable<T: Mappable>(forKey key: String) throws -> T {
guard let value = self[key as! Key] else {
throw MappableError.valueMissing(forKey: key)
}
guard let map = value as? [String : Any] else {
throw MappableError.valueTypeWrong(forKey: key)
}
return try T(map: map)
}
public func mappableArray<T: Mappable>(forKey key: String) throws -> [T] {
guard let value = self[key as! Key] else {
throw MappableError.valueMissing(forKey: key)
}
guard let array = value as? Array<[String : Any]> else {
throw MappableError.valueTypeWrong(forKey: key)
}
let mappableArray: [T] = try array.mappableArray()
return mappableArray
}
}
public extension Array {
public func mappableArray<T: Mappable>() throws -> [T] {
var array = [T]()
try forEach {
if let map = $0 as? [String : Any] {
let model = try T(map: map)
array.append(model)
} else {
throw MappableError.mappingFailed
}
}
return array
}
}
|
mit
|
78868cf2e7a9ee81f8fbee3b2956d8cc
| 31.018182 | 113 | 0.578932 | 4.609948 | false | false | false | false |
mactive/rw-courses-note
|
your-second-swift-app/CheckList/Checklists/Checklists/ChecklistViewController.swift
|
1
|
3882
|
//
// ViewController.swift
// Checklists
//
// Created by Brian on 8/14/17.
// Copyright © 2017 Razeware. All rights reserved.
//
import UIKit
class ChecklistViewController: UITableViewController {
var items: [ChecklistItem]
@IBAction func addItem(_ sender: Any) {
// let newRowIndex = items.count
let item = ChecklistItem()
var titles = ["Empty todo item", "Generic todo", "First todo: fill me out", "I need something to do", "Much todo about nothing"]
let randomNumber = arc4random_uniform(UInt32(titles.count))
let title = titles[Int(randomNumber)]
item.text = title
item.checked = true
// items.append(item)
// insert at the begining
items.insert(item, at: 0)
let indexPath = IndexPath(row: 0, section: 0)
let indexPaths = [indexPath]
tableView.insertRows(at: indexPaths, with: .automatic)
}
required init?(coder aDecoder: NSCoder) {
items = [ChecklistItem]()
let row0Item = ChecklistItem()
row0Item.text = "Walk the dog"
row0Item.checked = false
items.append(row0Item)
let row1Item = ChecklistItem()
row1Item.text = "Brush my teeth"
row1Item.checked = false
items.append(row1Item)
let row2Item = ChecklistItem()
row2Item.text = "Learn iOS development"
row2Item.checked = false
items.append(row2Item)
let row3Item = ChecklistItem()
row3Item.text = "Soccer pratice"
row3Item.checked = false
items.append(row3Item)
let row4Item = ChecklistItem()
row4Item.text = "Eat ice cream"
row4Item.checked = false
items.append(row4Item)
let row5Item = ChecklistItem()
row5Item.text = "Watch Game of Thrones"
row5Item.checked = true
items.append(row5Item)
let row6Item = ChecklistItem()
row6Item.text = "Read iOS Apprentice"
row6Item.checked = true
items.append(row6Item)
let row7Item = ChecklistItem()
row7Item.text = "Take a nap"
row7Item.checked = false
items.append(row7Item)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationController?.navigationBar.prefersLargeTitles = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
items.remove(at: indexPath.row);
let indexPaths = [indexPath]
tableView.deleteRows(at: indexPaths, with: .automatic)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
let item = items[indexPath.row]
item.toggleChecked()
configureCheckmark(for: cell, with: item)
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath)
let item = items[indexPath.row]
configureText(for: cell, with: item)
configureCheckmark(for: cell, with: item)
return cell
}
func configureText(for cell: UITableViewCell, with item: ChecklistItem) {
let label = cell.viewWithTag(1000) as! UILabel
label.text = item.text
}
func configureCheckmark(for cell: UITableViewCell, with item: ChecklistItem) {
if item.checked {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
}
}
|
mit
|
d9cd0c7edf0db8976cc0d4062085c56e
| 26.524823 | 134 | 0.679464 | 4.1597 | false | false | false | false |
sashohadz/swift
|
examPrep/examPrep/examPrep/AddNewItemSecondViewController.swift
|
1
|
1268
|
//
// AddNewItemSecondViewController.swift
// examPrep
//
// Created by Sasho Hadzhiev on 2/16/17.
// Copyright © 2017 Sasho Hadzhiev. All rights reserved.
//
import UIKit
class AddNewItemSecondViewController: UIViewController {
@IBOutlet weak var firstSlider: UISlider!
@IBOutlet weak var secondSlider: UISlider!
@IBOutlet weak var thirdSlider: UISlider!
@IBOutlet weak var firstLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
@IBOutlet weak var thirdLabel: UILabel!
@IBOutlet weak var doneButton: UIBarButtonItem!
var dataDictionary:[String:Any?] = [String:Any?]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func doneButtonClicked(_ sender: UIBarButtonItem) {
self.dataDictionary[DataNames.value1.rawValue] = self.firstSlider.value
self.dataDictionary[DataNames.value2.rawValue] = self.secondSlider.value
self.dataDictionary[DataNames.value3.rawValue] = self.thirdSlider.value
DBCommunication.instance.sendInfoToDB(info: self.dataDictionary)
_ = self.navigationController?.popToRootViewController(animated: true)
}
}
|
mit
|
be6d4e2d6a598f8984162b415038477b
| 31.487179 | 80 | 0.713496 | 4.508897 | false | false | false | false |
JoMo1970/cordova-plugin-qrcode-reader
|
src/ios/QRCodeReaderApp.swift
|
1
|
12178
|
/*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import AVFoundation
/// Reader object base on the `AVCaptureDevice` to read / scan 1D and 2D codes.
public final class QRCodeReaderApp: NSObject, AVCaptureMetadataOutputObjectsDelegate {
var defaultDevice: AVCaptureDevice = .defaultDevice(withMediaType: AVMediaTypeVideo)
var frontDevice: AVCaptureDevice? = {
if #available(iOS 10, *) {
return AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front)
}
else {
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
if let _device = device as? AVCaptureDevice , _device.position == AVCaptureDevicePosition.front {
return _device
}
}
}
return nil
}()
lazy var defaultDeviceInput: AVCaptureDeviceInput? = {
return try? AVCaptureDeviceInput(device: self.defaultDevice)
}()
lazy var frontDeviceInput: AVCaptureDeviceInput? = {
if let _frontDevice = self.frontDevice {
return try? AVCaptureDeviceInput(device: _frontDevice)
}
return nil
}()
public var metadataOutput = AVCaptureMetadataOutput()
var session = AVCaptureSession()
// MARK: - Managing the Properties
/// CALayer that you use to display video as it is being captured by an input device.
public lazy var previewLayer: AVCaptureVideoPreviewLayer = {
return AVCaptureVideoPreviewLayer(session: self.session)
}()
/// An array of strings identifying the types of metadata objects to process.
public let metadataObjectTypes: [String]
// MARK: - Managing the Code Discovery
/// Flag to know whether the scanner should stop scanning when a code is found.
public var stopScanningWhenCodeIsFound: Bool = true
/// Block is executed when a metadata object is found.
public var didFindCode: ((QRCodeReaderResult) -> Void)?
/// Block is executed when a found metadata object string could not be decoded.
public var didFailDecoding: ((Void) -> Void)?
// MARK: - Creating the Code Reade
/**
Initializes the code reader with the QRCode metadata type object.
*/
public convenience override init() {
self.init(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: .back)
}
/**
Initializes the code reader with an array of metadata object types, and the default initial capture position
- parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process.
*/
public convenience init(metadataObjectTypes types: [String]) {
self.init(metadataObjectTypes: types, captureDevicePosition: .back)
}
/**
Initializes the code reader with the starting capture device position, and the default array of metadata object types
- parameter captureDevicePosition: The capture position to use on start of scanning
*/
public convenience init(captureDevicePosition position: AVCaptureDevicePosition) {
self.init(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: position)
}
/**
Initializes the code reader with an array of metadata object types.
- parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process.
- parameter captureDevicePosition: The Camera to use on start of scanning.
*/
public init(metadataObjectTypes types: [String], captureDevicePosition: AVCaptureDevicePosition) {
metadataObjectTypes = types
super.init()
configureDefaultComponents(withCaptureDevicePosition: captureDevicePosition)
}
// MARK: - Initializing the AV Components
private func configureDefaultComponents(withCaptureDevicePosition: AVCaptureDevicePosition) {
session.addOutput(metadataOutput)
switch withCaptureDevicePosition {
case .front:
if let _frontDeviceInput = frontDeviceInput {
session.addInput(_frontDeviceInput)
}
case .back, .unspecified:
if let _defaultDeviceInput = defaultDeviceInput {
session.addInput(_defaultDeviceInput)
}
}
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metadataOutput.metadataObjectTypes = metadataObjectTypes
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
}
/// Switch between the back and the front camera.
@discardableResult
public func switchDeviceInput() -> AVCaptureDeviceInput? {
if let _frontDeviceInput = frontDeviceInput {
session.beginConfiguration()
if let _currentInput = session.inputs.first as? AVCaptureDeviceInput {
session.removeInput(_currentInput)
let newDeviceInput = (_currentInput.device.position == .front) ? defaultDeviceInput : _frontDeviceInput
session.addInput(newDeviceInput)
}
session.commitConfiguration()
}
return session.inputs.first as? AVCaptureDeviceInput
}
// MARK: - Controlling Reader
/**
Starts scanning the codes.
*Notes: if `stopScanningWhenCodeIsFound` is sets to true (default behaviour), each time the scanner found a code it calls the `stopScanning` method.*
*/
public func startScanning() {
if !session.isRunning {
session.startRunning()
}
}
/// Stops scanning the codes.
public func stopScanning() {
if session.isRunning {
session.stopRunning()
}
}
/**
Indicates whether the session is currently running.
The value of this property is a Bool indicating whether the receiver is running.
Clients can key value observe the value of this property to be notified when
the session automatically starts or stops running.
*/
public var isRunning: Bool {
return session.isRunning
}
/**
Indicates whether a front device is available.
- returns: true whether the device has a front device.
*/
public var hasFrontDevice: Bool {
return frontDevice != nil
}
/**
Indicates whether the torch is available.
- returns: true if a torch is available.
*/
public var isTorchAvailable: Bool {
return defaultDevice.isTorchAvailable
}
/**
Toggles torch on the default device.
*/
public func toggleTorch() {
do {
try defaultDevice.lockForConfiguration()
let current = defaultDevice.torchMode
defaultDevice.torchMode = AVCaptureTorchMode.on == current ? .off : .on
defaultDevice.unlockForConfiguration()
}
catch _ { }
}
// MARK: - Managing the Orientation
/**
Returns the video orientation corresponding to the given device orientation.
- parameter orientation: The orientation of the app's user interface.
- parameter supportedOrientations: The supported orientations of the application.
- parameter fallbackOrientation: The video orientation if the device orientation is FaceUp or FaceDown.
*/
public class func videoOrientation(deviceOrientation orientation: UIDeviceOrientation, withSupportedOrientations supportedOrientations: UIInterfaceOrientationMask, fallbackOrientation: AVCaptureVideoOrientation? = nil) -> AVCaptureVideoOrientation {
let result: AVCaptureVideoOrientation
switch (orientation, fallbackOrientation) {
case (.landscapeLeft, _):
result = .landscapeRight
case (.landscapeRight, _):
result = .landscapeLeft
case (.portrait, _):
result = .portrait
case (.portraitUpsideDown, _):
result = .portraitUpsideDown
case (_, .some(let orientation)):
result = orientation
default:
result = .portrait
}
if supportedOrientations.contains(orientationMask(videoOrientation: result)) {
return result
}
else if let orientation = fallbackOrientation , supportedOrientations.contains(orientationMask(videoOrientation: orientation)) {
return orientation
}
else if supportedOrientations.contains(.portrait) {
return .portrait
}
else if supportedOrientations.contains(.landscapeLeft) {
return .landscapeLeft
}
else if supportedOrientations.contains(.landscapeRight) {
return .landscapeRight
}
else {
return .portraitUpsideDown
}
}
class func orientationMask(videoOrientation orientation: AVCaptureVideoOrientation) -> UIInterfaceOrientationMask {
switch orientation {
case .landscapeLeft:
return .landscapeLeft
case .landscapeRight:
return .landscapeRight
case .portrait:
return .portrait
case .portraitUpsideDown:
return .portraitUpsideDown
}
}
// MARK: - Checking the Reader Availabilities
/**
Checks whether the reader is available.
- returns: A boolean value that indicates whether the reader is available.
*/
public class func isAvailable() -> Bool {
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
return (try? AVCaptureDeviceInput(device: captureDevice)) != nil
}
/**
Checks and return whether the given metadata object types are supported by the current device.
- parameter metadataTypes: An array of strings identifying the types of metadata objects to check.
- returns: A boolean value that indicates whether the device supports the given metadata object types.
*/
public class func supportsMetadataObjectTypes(_ metadataTypes: [String]? = nil) throws -> Bool {
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
let output = AVCaptureMetadataOutput()
let session = AVCaptureSession()
session.addInput(deviceInput)
session.addOutput(output)
var metadataObjectTypes = metadataTypes
if metadataObjectTypes == nil || metadataObjectTypes?.count == 0 {
// Check the QRCode metadata object type by default
metadataObjectTypes = [AVMetadataObjectTypeQRCode]
}
for metadataObjectType in metadataObjectTypes! {
if !output.availableMetadataObjectTypes.contains(where: { $0 as! String == metadataObjectType }) {
return false
}
}
return true
}
// MARK: - AVCaptureMetadataOutputObjects Delegate Methods
public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
for current in metadataObjects {
if let _readableCodeObject = current as? AVMetadataMachineReadableCodeObject {
if _readableCodeObject.stringValue != nil {
if metadataObjectTypes.contains(_readableCodeObject.type) {
if let sVal = _readableCodeObject.stringValue {
if stopScanningWhenCodeIsFound {
stopScanning()
}
let scannedResult = QRCodeReaderResult(value: sVal, metadataType:_readableCodeObject.type)
DispatchQueue.main.async(execute: { [weak self] in
self?.didFindCode?(scannedResult)
})
}
}
}
else {
didFailDecoding?()
}
}
}
}
}
|
mit
|
4c659e67e0be533687d27f7e07f7b5b8
| 32.640884 | 251 | 0.719412 | 5.352967 | false | false | false | false |
ajaybeniwal/IOS11AppStoreClone
|
IOS11AppStoreClone/IOS11AppStoreClone/ModelTransitionAnimator.swift
|
1
|
3472
|
//
// ModelTransitionAnimator.swift
// IOS11AppStoreClone
//
// Created by Ajay Singh on 16/5/18.
// Copyright © 2018 Ajay Singh. All rights reserved.
//
import UIKit
class ModelTransitionAnimator:NSObject,UIViewControllerAnimatedTransitioning{
private var edgeLayoutConstraints: NSEdgeLayoutConstraints?
let duration = 0.8
var presenting = true
var originFrame = CGRect.zero
var dismissCompletion: (()->Void)?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { return }
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return }
let modalView: UIView = presenting ? toView : fromView
containerView.addSubview(toView)
containerView.layer.cornerRadius=0
let underLineTableView:UITableView = modalView.subviews[0] as! UITableView
underLineTableView.layer.cornerRadius = 0;
containerView.bringSubview(toFront: modalView)
if(!presenting){
edgeLayoutConstraints?.constants(to: 0)
let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.8)
animator.addAnimations {
underLineTableView.layer.cornerRadius = 10;
underLineTableView.layer.masksToBounds = true
// modalView.layer.cornerRadius = 10
// modalView.layer.masksToBounds = true
self.edgeLayoutConstraints?.match(to: self.originFrame,
container: containerView)
containerView.layoutIfNeeded()
modalView.layoutIfNeeded()
}
animator.addCompletion { position in
switch position {
case .end:
transitionContext.completeTransition(true)
default:
transitionContext.completeTransition(true)
}
}
animator.startAnimation()
}
else{
modalView.translatesAutoresizingMaskIntoConstraints = false
edgeLayoutConstraints = NSEdgeLayoutConstraints(view: modalView,
container: containerView,
frame: originFrame)
edgeLayoutConstraints?.toggleConstraints(true)
containerView.layoutIfNeeded()
modalView.layoutIfNeeded()
let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.8)
animator.addAnimations {
self.edgeLayoutConstraints?.constants(to: 0)
containerView.layoutIfNeeded()
modalView.layoutIfNeeded()
}
animator.addCompletion { position in
switch position {
case .end:
transitionContext.completeTransition(true)
default:
transitionContext.completeTransition(true)
}
}
animator.startAnimation()
}
}
}
|
mit
|
6351b30e69eaf7653f25fc90409054ec
| 40.321429 | 109 | 0.599251 | 6.598859 | false | false | false | false |
teodorpatras/Hackfest
|
PayCode/PayCode/PayMethodsViewController.swift
|
1
|
19945
|
//
// PayMethodsViewController.swift
// PayCode
//
// Created by Teodor Patras on 26/09/15.
// Copyright © 2015 Teodor Patras. All rights reserved.
//
import CoreData
import UIKit
import SVProgressHUD
import TGLStackedViewController
import FontAwesomeKit
import Alamofire
class PayMethodsViewController: TGLStackedViewController, CardIOPaymentViewControllerDelegate,PayPalFuturePaymentDelegate, NSFetchedResultsControllerDelegate {
weak var addButton : UIButton!
lazy var fetchedResultController:NSFetchedResultsController = {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let sortDescriptor = NSSortDescriptor(key: "identifier", ascending: true)
let fetchRequest = NSFetchRequest(entityName: "Payment")
fetchRequest.fetchBatchSize = 20
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: appDelegate.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultController.delegate = self
return fetchedResultController
}()
override var exposedItemIndexPath : NSIndexPath?{
didSet{
let enabled = exposedItemIndexPath == nil
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.addButton.alpha = enabled ? 1 : 0
}) { _ -> Void in
self.addButton.enabled = enabled
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
configureUI()
CardIOUtilities.preload()
PayPalMobile.preconnectWithEnvironment(PayPalEnvironmentSandbox)
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: .Slide)
try! self.fetchedResultController.performFetch()
if self.fetchedResultController.sections![0].numberOfObjects == 0 {
SVProgressHUD.show()
let request = NSMutableURLRequest(URL: NSURL(string: "http://ohf.hern.as/payments/")!)
request.HTTPMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(request).responseJSON { (request, response, result) -> Void in
SVProgressHUD.dismiss()
if let array = result.value as? [[String : AnyObject]] {
for dict in array {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let payment = NSEntityDescription.insertNewObjectForEntityForName("Payment", inManagedObjectContext: appDelegate.managedObjectContext) as! Payment
payment.name = (dict["data"] as? [String: AnyObject])?["name"] as? String ?? "Teodor Patras"
payment.id = dict["id"] as! Int
payment.type = (dict["card_type"] as? String)?.lowercaseString ?? "paypal"
payment.identifier = (dict["data"] as? [String: AnyObject])?["email"] as? String ?? ((dict["data"] as? [String: AnyObject])?["number"] as? String)!.curatedString()
if let str = (dict["data"] as? [String: AnyObject])?["expiration"] as? String {
payment.validUntill = str
}
}
}
}
}
self.collectionView?.reloadData()
}
// MARK: - CardIO -
func userDidCancelPaymentViewController(paymentViewController: CardIOPaymentViewController!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func userDidProvideCreditCardInfo(cardInfo: CardIOCreditCardInfo!, inPaymentViewController paymentViewController: CardIOPaymentViewController!) {
if let info = cardInfo {
// 5173 3709 8453 3122
let str = "\(info.expiryYear)"
let year = str.substringFromIndex(2)
let expiration = "\(info.expiryMonth)/\(year)"
let dict = ["number" : info.cardNumber, "expiration" : expiration, "cvv" : info.cvv]
let request = NSMutableURLRequest(URL: NSURL(string: "http://ohf.hern.as/payments/card/")!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
try! request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dict, options: [])
SVProgressHUD.show()
Alamofire.request(request).responseJSON { (request, response, result) -> Void in
SVProgressHUD.dismiss()
if let dict = result.value as? [String : AnyObject] {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let payment = NSEntityDescription.insertNewObjectForEntityForName("Payment", inManagedObjectContext: appDelegate.managedObjectContext) as! Payment
payment.name = "Teodor Patras"
payment.id = dict["id"] as! Int
payment.type = (dict["card_type"] as! String).lowercaseString
payment.identifier = info.redactedCardNumber
payment.validUntill = expiration
}
}
}
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - CollectionView -
var flag = true
override func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if flag == true {
cell.transform = CGAffineTransformMakeScale(0.00001, 0.00001)
UIView.animateWithDuration(0.75, delay: Double(0.2) * Double(indexPath.item + 1), usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: .CurveEaseInOut, animations: { () -> Void in
cell.transform = CGAffineTransformIdentity
}, completion: nil)
if indexPath.row == 2 {
flag = false
}
}
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("paymentCell", forIndexPath: indexPath) as! PaymentCell
cell.configureWithModel(self.fetchedResultController.objectAtIndexPath(indexPath) as! Payment)
return cell
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let section:NSFetchedResultsSectionInfo = self.fetchedResultController.sections![section]
return section.numberOfObjects
}
// MARK: - PayPalFuturePayment -
func payPalFuturePaymentDidCancel(futurePaymentViewController: PayPalFuturePaymentViewController!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func payPalFuturePaymentViewController(futurePaymentViewController: PayPalFuturePaymentViewController!, didAuthorizeFuturePayment futurePaymentAuthorization: [NSObject : AnyObject]!) {
let clientCode = (futurePaymentAuthorization["response"] as! [String : AnyObject])["code"] as! String
let dict = ["authorization_code" : clientCode, "correlation_id" : PayPalMobile.clientMetadataID()]
let request = NSMutableURLRequest(URL: NSURL(string: "http://ohf.hern.as/payments/paypal/")!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
try! request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dict, options: [])
SVProgressHUD.show()
Alamofire.request(request).responseJSON { (request, response, result) -> Void in
SVProgressHUD.dismiss()
if let dict = (result.value as? [String : AnyObject])?["data"] as? [String : AnyObject] {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let payment = NSEntityDescription.insertNewObjectForEntityForName("Payment", inManagedObjectContext: appDelegate.managedObjectContext) as! Payment
payment.name = dict["name"] as! String
payment.id = (result.value as? [String : AnyObject])?["id"] as! Int
payment.type = "paypal"
payment.identifier = dict["email"] as! String
}
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func payPalFuturePaymentViewController(futurePaymentViewController: PayPalFuturePaymentViewController!, willAuthorizeFuturePayment futurePaymentAuthorization: [NSObject : AnyObject]!, completionBlock: PayPalFuturePaymentDelegateCompletionBlock!) {
completionBlock()
}
// MARK: - Callbacks -
func addPayment() {
let controller = UIAlertController(title: "Choose payment method", message: nil, preferredStyle: .ActionSheet)
let payPalAction = UIAlertAction(title: "PayPal", style: .Default) { _ -> Void in
let configuration = PayPalConfiguration()
configuration.merchantName = "PayCode"
configuration.merchantPrivacyPolicyURL = NSURL(string: "http://www.google.com")
configuration.merchantUserAgreementURL = NSURL(string: "http://www.google.com")
let controller = PayPalFuturePaymentViewController(configuration: configuration, delegate: self)
self.presentViewController(controller, animated: true, completion: nil)
}
let cardAction = UIAlertAction(title: "Credit card", style: .Default) { _ -> Void in
// card
let cardIOVC = CardIOPaymentViewController(paymentDelegate: self)
cardIOVC.modalPresentationStyle = .FormSheet
cardIOVC.view.frame = self.view.bounds
for view in cardIOVC.view.subviews {
view.frame = self.view.bounds
}
self.presentViewController(cardIOVC, animated: true) { () -> Void in
UIApplication.sharedApplication().statusBarStyle = .LightContent
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { _ -> Void in
}
controller.addAction(payPalAction)
controller.addAction(cardAction)
controller.addAction(cancelAction)
self.presentViewController(controller, animated: true, completion: nil)
controller.view.tintColor = UIColor.blackColor()
}
// MARK: - Helpers -
func configureUI() {
configureStackView()
let screenSize = UIScreen.mainScreen().bounds.size
let y : CGFloat = 30
let label = UILabel(frame: CGRectMake(10, y, 250, 70))
label.backgroundColor = UIColor.clearColor()
label.textColor = UIColor.whiteColor()
label.font = AppTheme.font(20)
label.text = "Your payment methods"
let button = UIButton(frame: CGRectMake(screenSize.width - 55, y + 10, 50, 50))
button.addTarget(self, action: "addPayment", forControlEvents: .TouchUpInside)
let icon = FAKFontAwesome.plusSquareOIconWithSize(25)
icon.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor())
button.setImage(icon.imageWithSize(CGSizeMake(50, 50)), forState: .Normal)
self.view.addSubview(button)
self.addButton = button
self.view.insertSubview(label, belowSubview: self.collectionView!)
self.collectionView?.backgroundColor = UIColor.clearColor()
self.collectionView?.registerNib(UINib(nibName: "PaymentCell", bundle: nil), forCellWithReuseIdentifier: "paymentCell")
}
func configureStackView() {
// Set to NO to prevent a small number
// of cards from filling the entire
// view height evenly and only show
// their -topReveal amount
//
self.stackedLayout.fillHeight = true;
// Set to NO to prevent a small number
// of cards from being scrollable and
// bounce
//
self.stackedLayout.alwaysBounce = true;
// Set to NO to prevent unexposed
// items at top and bottom from
// being selectable
//
self.unexposedItemsAreSelectable = true;
let size = CGSizeMake(0, 260.0)
self.stackedLayout.topReveal = 200.0
self.exposedItemSize = size
self.stackedLayout.itemSize = size
self.exposedPinningMode = .All;
self.exposedTopOverlap = 50.0;
self.exposedBottomOverlap = 50.0;
self.exposedBottomOverlapCount = 4
self.exposedTopPinningCount = 2
self.exposedBottomPinningCount = 5
self.collectionView?.contentInset = UIEdgeInsetsMake(100, 0, 0, 0)
}
// // I just implemented that with Swift. So I would like to share my implementation.
// // First initialise an array of NSBlockOperations:
// var blockOperations: [NSBlockOperation] = []
//
//
// // In the did change object method:
// func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
//
// if type == NSFetchedResultsChangeType.Insert {
// print("Insert Object: \(newIndexPath)")
//
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.insertItemsAtIndexPaths([newIndexPath!])
// }
// })
// )
// }
// else if type == NSFetchedResultsChangeType.Update {
// print("Update Object: \(indexPath)")
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.reloadItemsAtIndexPaths([indexPath!])
// }
// })
// )
// }
// else if type == NSFetchedResultsChangeType.Move {
// print("Move Object: \(indexPath)")
//
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.moveItemAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
// }
// })
// )
// }
// else if type == NSFetchedResultsChangeType.Delete {
// print("Delete Object: \(indexPath)")
//
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.deleteItemsAtIndexPaths([indexPath!])
// }
// })
// )
// }
// }
//
// // In the did change section method:
// func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
//
// if type == NSFetchedResultsChangeType.Insert {
// print("Insert Section: \(sectionIndex)")
//
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.insertSections(NSIndexSet(index: sectionIndex))
// }
// })
// )
// }
// else if type == NSFetchedResultsChangeType.Update {
// print("Update Section: \(sectionIndex)")
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.reloadSections(NSIndexSet(index: sectionIndex))
// }
// })
// )
// }
// else if type == NSFetchedResultsChangeType.Delete {
// print("Delete Section: \(sectionIndex)")
//
// blockOperations.append(
// NSBlockOperation(block: { [weak self] in
// if let this = self {
// this.collectionView!.deleteSections(NSIndexSet(index: sectionIndex))
// }
// })
// )
// }
// }
//
// And finally, in the did controller did change content method:
func controllerDidChangeContent(controller: NSFetchedResultsController) {
collectionView!.reloadData()
collectionView?.collectionViewLayout.invalidateLayout()
}
//
// // I personally added some code in the deinit method as well, in order to cancel the operations when the ViewController is about to get deallocated:
// deinit {
// // Cancel all block operations when VC deallocates
// for operation: NSBlockOperation in blockOperations {
// operation.cancel()
// }
//
// blockOperations.removeAll(keepCapacity: false)
// }
}
extension String
{
func substringFromIndex(index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substringFromIndex(self.startIndex.advancedBy(index))
}
func substringToIndex(index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substringToIndex(self.startIndex.advancedBy(index))
}
func substringWithRange(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
return self.substringWithRange(range)
}
func substringWithRange(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
return self.substringWithRange(range)
}
func curatedString() -> String {
if self.characters.count == 16 {
var copy = self.substringFromIndex(12)
copy = "••••••••••••" + copy
return copy
} else {
return ""
}
}
}
|
mit
|
96b6b834ffdec4b8a92f50858b495d7b
| 40.936842 | 251 | 0.593122 | 5.3534 | false | false | false | false |
adrianomazucato/SwiftSockets
|
ARISockets/DNS.swift
|
1
|
2780
|
//
// DNS.swift
// ARISockets
//
// Created by Helge Hess on 7/3/14.
// Copyright (c) 2014 Always Right Institute. All rights reserved.
//
import Darwin
func gethoztbyname<T: SocketAddress>
(name : String, flags : Int32 = AI_CANONNAME,
cb : ( String, String?, T? ) -> Void)
{
// Note: I can't just provide a name and a cb, swiftc will complain.
var hints = addrinfo()
hints.ai_flags = flags // AI_CANONNAME, AI_NUMERICHOST, etc
hints.ai_family = T.domain
var ptr = UnsafeMutablePointer<addrinfo>(nil)
/* run lookup (synchronously, can be slow!) */
// b3: (cs : CString) doesn't pick up the right overload?
var rc = name.withCString { (cs : UnsafePointer<CChar>) -> Int32 in
return getaddrinfo(cs, nil, &hints, &ptr)
}
if rc != 0 {
cb(name, nil, nil)
return
}
/* copy results - we just take the first match */
var cn : String? = nil
var addr : T? = ptr.memory.address()
if rc == 0 && ptr != nil {
cn = ptr.memory.canonicalName
addr = ptr.memory.address()
}
/* free OS resources */
freeaddrinfo(ptr)
/* report results */
cb(name, cn, addr)
}
/**
* This is awkward :-) But it actually works. Though it is not what you want,
* the address here should be dynamic depending on the domain of the C struct.
*
* Whatever, this runs:
* let hhost : String = "mail.google.com" // why is this necessary?
* gethostzbyname(hhost, flags: Int32(AI_CANONNAME)) {
* ( cn: String, infos: [ ( cn: String?, address: sockaddr_in? )]? ) -> Void
* in
* println("result \(cn): \(infos)")
* }
*
* TBD: The 'flags' has to be provided, otherwise the trailing closure is not
* detected right?
*/
func gethostzbyname<T: SocketAddress>
(name : String, flags : Int32 = AI_CANONNAME,
cb : ( String, [ ( cn: String?, address: T? ) ]? ) -> Void
) -> Void
{
// Note: I can't just provide a name and a cb, swiftc will complain.
var hints = addrinfo()
hints.ai_flags = flags // AI_CANONNAME, AI_NUMERICHOST, etc
hints.ai_family = T.domain
var ptr = UnsafeMutablePointer<addrinfo>(nil)
/* run lookup (synchronously, can be slow!) */
var rc = name.withCString { (cs : UnsafePointer<CChar>) -> Int32 in
return getaddrinfo(cs, nil, &hints, &ptr)
}
if rc != 0 {
cb(name, nil)
return
}
/* copy results - we just take the first match */
typealias hapair = (cn: String?, address: T?)
var results : Array<hapair>! = nil
if rc == 0 && ptr != nil {
var pairs = Array<hapair>()
for info in ptr.memory {
let pair : hapair = ( info.canonicalName, info.address() )
pairs.append(pair)
}
results = pairs
}
/* free OS resources */
freeaddrinfo(ptr)
/* report results */
cb(name, results)
}
|
mit
|
c9cf0bbcee6b13e1361aef85b8188f43
| 26.254902 | 80 | 0.613669 | 3.394383 | false | false | false | false |
blstream/TOZ_iOS
|
TOZ_iOS/AddScheduleRequest.swift
|
1
|
1872
|
//
// AddScheduleRequest.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import Foundation
final class AddScheduleRequest: BackendAPIRequest {
private let dataObject: ReservationItem
private let modificationMessage: String
private var ownerId: String?
init(dataObject: ReservationItem, modificationMessage: String, ownerId: String? = nil) {
self.dataObject = dataObject
self.modificationMessage = modificationMessage
self.ownerId = ownerId
}
var endpoint: String {
return "/schedule"
}
var method: NetworkService.Method {
return .POST
}
var parameters: [String: Any]? {
var startTime = ""
var endTime = ""
if dataObject.timeOfDay == .morning {
startTime = "08:00"
endTime = "12:00"
} else {
startTime = "12:00"
endTime = "16:00"
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.string(from: dataObject.date)
var parametersInDictionary: [String: Any] = [:]
parametersInDictionary["date"] = date
parametersInDictionary["startTime"] = startTime
parametersInDictionary["endTime"] = endTime
parametersInDictionary["modificationMessage"] = modificationMessage
if let ownerId = ownerId {
parametersInDictionary["ownerId"] = ownerId
}
if let ownerSurname = dataObject.ownerSurname {
parametersInDictionary["ownerSurname"] = ownerSurname
}
if let ownerForename = dataObject.ownerForename {
parametersInDictionary["ownerName"] = ownerForename
}
return parametersInDictionary
}
var headers: [String: String]? {
return headersWhenJSONSent()
}
}
|
apache-2.0
|
3156e2faf87ff8fa3812b3401447c284
| 28.234375 | 92 | 0.625869 | 4.910761 | false | false | false | false |
roecrew/AudioKit
|
AudioKit/Common/Nodes/Effects/AudioKit Operation-Based Effect/AKOperationEffect.swift
|
1
|
4368
|
//
// AKOperationEffect.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Operation-based effect
public class AKOperationEffect: AKNode, AKToggleable {
// MARK: - Properties
private var internalAU: AKOperationEffectAudioUnit?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
/// Parameters for changing internal operations
public var parameters: [Double] {
get {
var result: [Double] = []
if let floatParameters = internalAU?.parameters as? [NSNumber] {
for number in floatParameters {
result.append(number.doubleValue)
}
}
return result
}
set {
internalAU?.parameters = newValue
}
}
// MARK: - Initializers
/// Initialize the generator for stereo (2 channels)
///
/// - Parameters:
/// - input: AKNode to use for processing
/// - numberOfChannels: Only 2 channels are supported, but need to differentiate the initializer
/// - operations: Array of operations [left, right]
///
public convenience init(_ input: AKNode,
numberOfChannels: Int,
operations: (AKStereoOperation, [AKOperation])->[AKOperation]) {
let computedParameters = operations(AKStereoOperation.input, AKOperation.parameters)
let left = computedParameters[0]
if numberOfChannels == 2 {
let right = computedParameters[1]
self.init(input, sporth: "\(right.sporth) \(left.sporth)")
} else {
self.init(input, sporth: "\(left.sporth)")
}
}
/// Initialize the generator for stereo (2 channels)
///
/// - Parameters:
/// - input: AKNode to use for processing
/// - operation: Operation to generate, can be mono or stereo
///
public convenience init(_ input: AKNode,
operation: (AKStereoOperation, [AKOperation])->AKComputedParameter) {
let computedParameter = operation(AKStereoOperation.input, AKOperation.parameters)
if computedParameter.dynamicType == AKOperation.self {
let monoOperation = computedParameter as! AKOperation
self.init(input, sporth: monoOperation.sporth + " dup ")
} else {
let stereoOperation = computedParameter as! AKStereoOperation
self.init(input, sporth: stereoOperation.sporth + " swap ")
}
}
/// Initialize the effect with an input and a valid Sporth string
///
/// - Parameters:
/// - input: AKNode to use for processing
/// - sporth: String of valid Sporth code
///
public init(_ input: AKNode, sporth: String) {
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = fourCC("cstm")
description.componentManufacturer = fourCC("AuKt")
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKOperationEffectAudioUnit.self,
asComponentDescription: description,
name: "Local AKOperationEffect",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKOperationEffectAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
self.internalAU?.setSporth(sporth)
}
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
internalAU!.stop()
}
}
|
mit
|
821937e4eebc1271dc4efbd3b4fa4b23
| 32.6 | 102 | 0.604625 | 5.333333 | false | false | false | false |
Legoless/iOS-Course
|
2015-1/Lesson13/PersonViewer/PersonViewer/ViewController.swift
|
1
|
2779
|
//
// ViewController.swift
// PersonViewer
//
// Created by Dal Rupnik on 23/11/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadData () {
let request = NSMutableURLRequest()
request.URL = NSURL(string: "https://randomuser.me/api/")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let data = data {
do {
let object = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
if let dictionary = object as? [String : AnyObject] {
if let results = dictionary["results"] as? [AnyObject] {
if results.count > 0 {
if let user = results[0]["user"] as? [String : AnyObject] {
//print (user)
let name = user["name"]!["first"]! as! String
print(name)
let url = user["picture"]!["large"]! as! String
let imageData = NSData(contentsOfURL: NSURL(string: url)!)
let image = UIImage(data: imageData!)!
dispatch_async(dispatch_get_main_queue(), {
self.infoLabel.text = (name as! NSString).capitalizedString
self.imageView.image = image
})
}
}
}
}
}
catch {
}
}
}
task.resume()
}
}
|
mit
|
8624c22d0e754e84829a482f27103266
| 33.725 | 125 | 0.402808 | 6.77561 | false | false | false | false |
seem-sky/ios-charts
|
Charts/Classes/Animation/ChartAnimationEasing.swift
|
1
|
13856
|
//
// ChartAnimationUtils.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/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
@objc
public enum ChartEasingOption: Int
{
case Linear
case EaseInQuad
case EaseOutQuad
case EaseInOutQuad
case EaseInCubic
case EaseOutCubic
case EaseInOutCubic
case EaseInQuart
case EaseOutQuart
case EaseInOutQuart
case EaseInQuint
case EaseOutQuint
case EaseInOutQuint
case EaseInSine
case EaseOutSine
case EaseInOutSine
case EaseInExpo
case EaseOutExpo
case EaseInOutExpo
case EaseInCirc
case EaseOutCirc
case EaseInOutCirc
case EaseInElastic
case EaseOutElastic
case EaseInOutElastic
case EaseInBack
case EaseOutBack
case EaseInOutBack
case EaseInBounce
case EaseOutBounce
case EaseInOutBounce
}
public typealias ChartEasingFunctionBlock = ((elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat);
internal func easingFunctionFromOption(easing: ChartEasingOption) -> ChartEasingFunctionBlock
{
switch easing
{
case .Linear:
return EasingFunctions.Linear;
case .EaseInQuad:
return EasingFunctions.EaseInQuad;
case .EaseOutQuad:
return EasingFunctions.EaseOutQuad;
case .EaseInOutQuad:
return EasingFunctions.EaseInOutQuad;
case .EaseInCubic:
return EasingFunctions.EaseInCubic;
case .EaseOutCubic:
return EasingFunctions.EaseOutCubic;
case .EaseInOutCubic:
return EasingFunctions.EaseInOutCubic;
case .EaseInQuart:
return EasingFunctions.EaseInQuart;
case .EaseOutQuart:
return EasingFunctions.EaseOutQuart;
case .EaseInOutQuart:
return EasingFunctions.EaseInOutQuart;
case .EaseInQuint:
return EasingFunctions.EaseInQuint;
case .EaseOutQuint:
return EasingFunctions.EaseOutQuint;
case .EaseInOutQuint:
return EasingFunctions.EaseInOutQuint;
case .EaseInSine:
return EasingFunctions.EaseInSine;
case .EaseOutSine:
return EasingFunctions.EaseOutSine;
case .EaseInOutSine:
return EasingFunctions.EaseInOutSine;
case .EaseInExpo:
return EasingFunctions.EaseInExpo;
case .EaseOutExpo:
return EasingFunctions.EaseOutExpo;
case .EaseInOutExpo:
return EasingFunctions.EaseInOutExpo;
case .EaseInCirc:
return EasingFunctions.EaseInCirc;
case .EaseOutCirc:
return EasingFunctions.EaseOutCirc;
case .EaseInOutCirc:
return EasingFunctions.EaseInOutCirc;
case .EaseInElastic:
return EasingFunctions.EaseInElastic;
case .EaseOutElastic:
return EasingFunctions.EaseOutElastic;
case .EaseInOutElastic:
return EasingFunctions.EaseInOutElastic;
case .EaseInBack:
return EasingFunctions.EaseInBack;
case .EaseOutBack:
return EasingFunctions.EaseOutBack;
case .EaseInOutBack:
return EasingFunctions.EaseInOutBack;
case .EaseInBounce:
return EasingFunctions.EaseInBounce;
case .EaseOutBounce:
return EasingFunctions.EaseOutBounce;
case .EaseInOutBounce:
return EasingFunctions.EaseInOutBounce;
}
}
internal struct EasingFunctions
{
internal static let Linear = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return CGFloat(elapsed / duration); };
internal static let EaseInQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position;
};
internal static let EaseOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return -position * (position - 2.0);
};
internal static let EaseInOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position;
}
return -0.5 * ((--position) * (position - 2.0) - 1.0);
};
internal static let EaseInCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position * position;
};
internal static let EaseOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return (position * position * position + 1.0);
};
internal static let EaseInOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position * position;
}
position -= 2.0;
return 0.5 * (position * position * position + 2.0);
};
internal static let EaseInQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position * position * position;
};
internal static let EaseOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return -(position * position * position * position - 1.0);
};
internal static let EaseInOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position * position * position;
}
position -= 2.0;
return -0.5 * (position * position * position * position - 2.0);
};
internal static let EaseInQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position * position * position * position;
};
internal static let EaseOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return (position * position * position * position * position + 1.0);
};
internal static let EaseInOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position * position * position * position;
}
else
{
position -= 2.0;
return 0.5 * (position * position * position * position * position + 2.0);
}
};
internal static let EaseInSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
return CGFloat( -cos(position * M_PI_2) + 1.0 );
};
internal static let EaseOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
return CGFloat( sin(position * M_PI_2) );
};
internal static let EaseInOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
return CGFloat( -0.5 * (cos(M_PI * position) - 1.0) );
};
internal static let EaseInExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
return (elapsed == 0) ? 0.0 : CGFloat(pow(2.0, 10.0 * (elapsed / duration - 1.0)));
};
internal static let EaseOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
return (elapsed == duration) ? 1.0 : (-CGFloat(pow(2.0, -10.0 * elapsed / duration)) + 1.0);
};
internal static let EaseInOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0)
{
return 0.0;
}
if (elapsed == duration)
{
return 1.0;
}
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position < 1.0)
{
return CGFloat( 0.5 * pow(2.0, 10.0 * (position - 1.0)) );
}
return CGFloat( 0.5 * (-pow(2.0, -10.0 * --position) + 2.0) );
};
internal static let EaseInCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return -(CGFloat(sqrt(1.0 - position * position)) - 1.0);
};
internal static let EaseOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return CGFloat( sqrt(1 - position * position) );
};
internal static let EaseInOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position < 1.0)
{
return CGFloat( -0.5 * (sqrt(1.0 - position * position) - 1.0) );
}
position -= 2.0;
return CGFloat( 0.5 * (sqrt(1.0 - position * position) + 1.0) );
};
internal static let EaseInElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0.0)
{
return 0.0;
}
var position: NSTimeInterval = elapsed / duration;
if (position == 1.0)
{
return 1.0;
}
var p = duration * 0.3;
var s = p / (2.0 * M_PI) * asin(1.0);
position -= 1.0;
return CGFloat( -(pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) );
};
internal static let EaseOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0.0)
{
return 0.0;
}
var position: NSTimeInterval = elapsed / duration;
if (position == 1.0)
{
return 1.0;
}
var p = duration * 0.3;
var s = p / (2.0 * M_PI) * asin(1.0);
return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) + 1.0 );
};
internal static let EaseInOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0.0)
{
return 0.0;
}
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position == 2.0)
{
return 1.0;
}
var p = duration * (0.3 * 1.5);
var s = p / (2.0 * M_PI) * asin(1.0);
if (position < 1.0)
{
position -= 1.0;
return CGFloat( -0.5 * (pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) );
}
position -= 1.0;
return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) * 0.5 + 1.0 );
};
internal static let EaseInBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
let s: NSTimeInterval = 1.70158;
var position: NSTimeInterval = elapsed / duration;
return CGFloat( position * position * ((s + 1.0) * position - s) );
};
internal static let EaseOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
let s: NSTimeInterval = 1.70158;
var position: NSTimeInterval = elapsed / duration;
position--;
return CGFloat( (position * position * ((s + 1.0) * position + s) + 1.0) );
};
internal static let EaseInOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var s: NSTimeInterval = 1.70158;
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position < 1.0)
{
s *= 1.525;
return CGFloat( 0.5 * (position * position * ((s + 1.0) * position - s)) );
}
s *= 1.525;
position -= 2.0;
return CGFloat( 0.5 * (position * position * ((s + 1.0) * position + s) + 2.0) );
};
internal static let EaseInBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
return 1.0 - EaseOutBounce(duration - elapsed, duration);
};
internal static let EaseOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
if (position < (1.0 / 2.75))
{
return CGFloat( 7.5625 * position * position );
}
else if (position < (2.0 / 2.75))
{
position -= (1.5 / 2.75);
return CGFloat( 7.5625 * position * position + 0.75 );
}
else if (position < (2.5 / 2.75))
{
position -= (2.25 / 2.75);
return CGFloat( 7.5625 * position * position + 0.9375 );
}
else
{
position -= (2.625 / 2.75);
return CGFloat( 7.5625 * position * position + 0.984375 );
}
};
internal static let EaseInOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed < (duration / 2.0))
{
return EaseInBounce(elapsed * 2.0, duration) * 0.5;
}
return EaseOutBounce(elapsed * 2.0 - duration, duration) * 0.5 + 0.5;
};
};
|
apache-2.0
|
c64254c4245174ba53d69a8e3f1be4c7
| 34.259542 | 139 | 0.598802 | 4.408527 | false | false | false | false |
CM-Studio/NotLonely-iOS
|
NotLonely-iOS/View/NLTabBar.swift
|
1
|
1138
|
//
// NLTabBar.swift
// NotLonely-iOS
//
// Created by plusub on 4/3/16.
// Copyright © 2016 cm. All rights reserved.
//
import UIKit
class NLTabBar: UITabBar {
lazy var publishBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "ic_tabbar_publish"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "ic_tabbar_publish"), forState: UIControlState.Highlighted)
self.addSubview(btn)
return btn
}()
override func layoutSubviews() {
super.layoutSubviews()
let width = self.bounds.width / 5
let height = self.bounds.height
let frame = CGRectMake(0, 0, width, height)
var index: CGFloat = 0
for view in self.subviews {
if (view is UIControl && !(view is UIButton)) {
view.frame = CGRectOffset(frame, index * width, 0)
index += (index == 1) ? 2 : 1
}
}
self.publishBtn.frame = frame
self.publishBtn.center = CGPointMake(self.bounds.width * 0.5, self.bounds.height * 0.5 )
}
}
|
mit
|
61014e7a4a3250586f141939b62e194d
| 26.731707 | 96 | 0.567282 | 4.119565 | false | false | false | false |
zeroleaf/LeetCode
|
LeetCode/LeetCodeTests/9_PalindromeNumberSpec.swift
|
1
|
1396
|
//
// PalindromeNumberSpec.swift
// LeetCode
//
// Created by zeroleaf on 16/1/26.
// Copyright © 2016年 zeroleaf. All rights reserved.
//
import XCTest
import Quick
import Nimble
class PalindromeNumber {
func isPalindrome(x: Int) -> Bool {
if x < 0 || (x % 10 == 0 && x != 0) {
return false
}
var i = 0, j = x
while i < j {
i = i * 10 + (j % 10)
j /= 10
}
return i == j || i / 10 == j
}
}
class PalindromeNumberSpec: QuickSpec {
override func spec() {
describe("Palindrome Number") {
var s: PalindromeNumber!
beforeEach {
s = PalindromeNumber()
}
it("Negetive value") {
expect(s.isPalindrome(-10)).to(equal(false))
}
it("Zero") {
expect(s.isPalindrome(0)).to(equal(true))
}
it("One digit") {
expect(s.isPalindrome(7)).to(equal(true))
}
it("Times of ten") {
expect(s.isPalindrome(20)).to(equal(false))
}
it("Odd Palindrome Number") {
expect(s.isPalindrome(121)).to(equal(true))
}
it("Even Palindrome Number") {
expect(s.isPalindrome(1221)).to(equal(true))
}
}
}
}
|
mit
|
047da1f12f47a78fd863ca9a54699fae
| 19.188406 | 60 | 0.455851 | 4.014409 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Components/AssetPriceView/AssetPriceViewPresenter.swift
|
1
|
1813
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxCocoa
import RxRelay
import RxSwift
public final class AssetPriceViewPresenter {
typealias PresentationState = DashboardAsset.State.AssetPrice.Presentation
// MARK: - Exposed Properties
var state: Observable<PresentationState> {
_ = setup
return stateRelay
.observe(on: MainScheduler.instance)
}
var alignment: Driver<UIStackView.Alignment> {
alignmentRelay.asDriver()
}
// MARK: - Injected
private let interactor: AssetPriceViewInteracting
// MARK: - Private Accessors
private lazy var setup: Void = {
// Map interaction state into presentation state
// and bind it to `stateRelay`
interactor.state
.map(weak: self) { (self, state) -> PresentationState in
PresentationState(with: state, descriptors: self.descriptors)
}
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
}()
private let descriptors: DashboardAsset.Value.Presentation.AssetPrice.Descriptors
private let alignmentRelay: BehaviorRelay<UIStackView.Alignment>
private let stateRelay = BehaviorRelay<PresentationState>(value: .loading)
private let disposeBag = DisposeBag()
// MARK: - Setup
public init(
interactor: AssetPriceViewInteracting,
alignment: UIStackView.Alignment = .fill,
descriptors: DashboardAsset.Value.Presentation.AssetPrice.Descriptors
) {
self.interactor = interactor
self.descriptors = descriptors
alignmentRelay = BehaviorRelay<UIStackView.Alignment>(value: alignment)
}
// MARK: - Public Functions
public func refresh() {
interactor.refresh()
}
}
|
lgpl-3.0
|
bbc9c63bb35c5adc7de8c7e402ad5dd0
| 27.3125 | 85 | 0.675497 | 5.191977 | false | false | false | false |
richy486/ReactiveReSwiftRouter
|
ReSwiftRouterTests/ReSwiftRouterTestsUnitTests.swift
|
1
|
11684
|
//
// SwiftFlowRouterUnitTests.swift
// Meet
//
// Created by Benjamin Encz on 12/2/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Quick
import Nimble
import ReactiveReSwift
@testable import ReactiveReSwiftRouter
class ReSwiftRouterUnitTests: QuickSpec {
// Used as test app state
struct AppState {}
override func spec() {
describe("routing calls") {
enum Routes: RouteElement {
case tabBarViewControllerIdentifier
case counterViewControllerIdentifier
case statsViewControllerIdentifier
case infoViewControllerIdentifier
}
it("calculates transitions from an empty route to a multi segment route") {
let oldRoute: Route = []
let newRoute = [RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier),
RouteIdentifiable(element: Routes.statsViewControllerIdentifier)]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
var action1Correct: Bool?
var action2Correct: Bool?
if case let RoutingActions.push(responsibleRoutableIndex, segmentToBePushed)
= routingActions[0] {
if responsibleRoutableIndex == 0
&& segmentToBePushed.element == Routes.tabBarViewControllerIdentifier {
action1Correct = true
}
}
if case let RoutingActions.push(responsibleRoutableIndex, segmentToBePushed)
= routingActions[1] {
if responsibleRoutableIndex == 1
&& segmentToBePushed.element == Routes.statsViewControllerIdentifier {
action2Correct = true
}
}
expect(routingActions).to(haveCount(2))
expect(action1Correct).to(beTrue())
expect(action2Correct).to(beTrue())
}
it("generates a Change action on the last common subroute") {
let commonSubroute = RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier)
let oldRoute = [commonSubroute,
RouteIdentifiable(element: Routes.counterViewControllerIdentifier)]
let newRoute = [commonSubroute,
RouteIdentifiable(element: Routes.statsViewControllerIdentifier)]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
var controllerIndex: Int?
var toBeReplaced: RouteElementIdentifier?
var new: RouteElementIdentifier?
if case let RoutingActions.change(responsibleControllerIndex, controllerToBeReplaced, newController) = routingActions.first! {
controllerIndex = responsibleControllerIndex
toBeReplaced = controllerToBeReplaced
new = newController
}
expect(routingActions).to(haveCount(1))
expect(controllerIndex).to(equal(1))
expect(Routes.counterViewControllerIdentifier).to(equal(Routes.counterViewControllerIdentifier))
guard let toBeReplacedElement = toBeReplaced?.element, let newElement = new?.element else {
fail()
return
}
expect(toBeReplacedElement == Routes.counterViewControllerIdentifier).to(beTrue())
expect(newElement == Routes.statsViewControllerIdentifier).to(beTrue())
}
it("generates a Change action on the last common subroute, also for routes of different length") {
let commonSubroute = RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier)
let oldRoute = [commonSubroute,
RouteIdentifiable(element: Routes.counterViewControllerIdentifier)]
let newRoute = [commonSubroute,
RouteIdentifiable(element: Routes.statsViewControllerIdentifier),
RouteIdentifiable(element: Routes.infoViewControllerIdentifier)]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
var action1Correct: Bool?
var action2Correct: Bool?
if case let RoutingActions.change(responsibleRoutableIndex, segmentToBeReplaced,
newSegment)
= routingActions[0] {
if responsibleRoutableIndex == 1
&& segmentToBeReplaced.element == Routes.counterViewControllerIdentifier
&& newSegment.element == Routes.statsViewControllerIdentifier{
action1Correct = true
}
}
if case let RoutingActions.push(responsibleRoutableIndex, segmentToBePushed)
= routingActions[1] {
if responsibleRoutableIndex == 2
&& segmentToBePushed.element == Routes.infoViewControllerIdentifier {
action2Correct = true
}
}
expect(routingActions).to(haveCount(2))
expect(action1Correct).to(beTrue())
expect(action2Correct).to(beTrue())
}
it("generates a Change action on root when root element changes") {
let oldRoute = [RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier)]
let newRoute = [RouteIdentifiable(element: Routes.statsViewControllerIdentifier)]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
var controllerIndex: Int?
var toBeReplaced: RouteElementIdentifier?
var new: RouteElementIdentifier?
if case let RoutingActions.change(responsibleControllerIndex,
controllerToBeReplaced,
newController) = routingActions.first! {
controllerIndex = responsibleControllerIndex
toBeReplaced = controllerToBeReplaced
new = newController
}
expect(routingActions).to(haveCount(1))
expect(controllerIndex).to(equal(0))
guard let toBeReplacedElement = toBeReplaced?.element, let newElement = new?.element else {
fail()
return
}
expect(toBeReplacedElement == Routes.tabBarViewControllerIdentifier).to(beTrue())
expect(newElement == Routes.statsViewControllerIdentifier).to(beTrue())
}
it("calculates no actions for transition from empty route to empty route") {
let oldRoute: Route = []
let newRoute: Route = []
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
expect(routingActions).to(haveCount(0))
}
it("calculates no actions for transitions between identical, non-empty routes") {
let routeElementTabBar = RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier)
let routeElementStatus = RouteIdentifiable(element: Routes.statsViewControllerIdentifier)
let oldRoute = [routeElementTabBar, routeElementStatus]
let newRoute = [routeElementTabBar, routeElementStatus]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
expect(routingActions).to(haveCount(0))
}
it("calculates transitions with multiple pops") {
let commonSubroute = RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier)
let oldRoute = [commonSubroute,
RouteIdentifiable(element: Routes.statsViewControllerIdentifier),
RouteIdentifiable(element: Routes.counterViewControllerIdentifier)]
let newRoute = [commonSubroute]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
var action1Correct: Bool?
var action2Correct: Bool?
if case let RoutingActions.pop(responsibleRoutableIndex, segmentToBePopped)
= routingActions[0] {
if responsibleRoutableIndex == 2
&& segmentToBePopped.element == Routes.counterViewControllerIdentifier {
action1Correct = true
}
}
if case let RoutingActions.pop(responsibleRoutableIndex, segmentToBePopped)
= routingActions[1] {
if responsibleRoutableIndex == 1
&& segmentToBePopped.element == Routes.statsViewControllerIdentifier {
action2Correct = true
}
}
expect(action1Correct).to(beTrue())
expect(action2Correct).to(beTrue())
expect(routingActions).to(haveCount(2))
}
it("calculates transitions with multiple pushes") {
let commonSubroute = RouteIdentifiable(element: Routes.tabBarViewControllerIdentifier)
let oldRoute = [commonSubroute]
let newRoute = [commonSubroute,
RouteIdentifiable(element: Routes.statsViewControllerIdentifier),
RouteIdentifiable(element: Routes.counterViewControllerIdentifier)]
let routingActions = Router<AppState>.routingActionsForTransitionFrom(oldRoute,
newRoute: newRoute)
var action1Correct: Bool?
var action2Correct: Bool?
if case let RoutingActions.push(responsibleRoutableIndex, segmentToBePushed)
= routingActions[0] {
if responsibleRoutableIndex == 1
&& segmentToBePushed.element == Routes.statsViewControllerIdentifier {
action1Correct = true
}
}
if case let RoutingActions.push(responsibleRoutableIndex, segmentToBePushed)
= routingActions[1] {
if responsibleRoutableIndex == 2
&& segmentToBePushed.element == Routes.counterViewControllerIdentifier {
action2Correct = true
}
}
expect(action1Correct).to(beTrue())
expect(action2Correct).to(beTrue())
expect(routingActions).to(haveCount(2))
}
}
}
}
|
mit
|
d8a8a8febdfd2529927b984585bb591d
| 41.794872 | 142 | 0.560045 | 6.237587 | false | false | false | false |
Automattic/Automattic-Tracks-iOS
|
Sources/Encrypted Logs/EventLoggingNetworkService.swift
|
1
|
2148
|
import Foundation
class EventLoggingNetworkService {
typealias ResultCallback = (Result<Data?, Error>) -> Void
private let urlSession: URLSession
init(urlSession: URLSession = URLSession.shared) {
self.urlSession = urlSession
}
func uploadFile(request: URLRequest, fileURL: URL, completion: @escaping ResultCallback) {
urlSession.uploadTask(with: request, fromFile: fileURL, completionHandler: { data, response, error in
if let error = error {
completion(.failure(error))
return
}
/// The `response` should *always* be an HTTPURLResponse.
/// Fail fast by force-unwrapping – this will cause a crash and will bring the issue to our attention if something has changed.
let statusCode = (response as! HTTPURLResponse).statusCode
if !(200 ... 299).contains(statusCode) {
/// Use the server-provided error messaging, if possible
if let data = data, let error = self.decodeError(data: data) {
completion(.failure(EventLoggingFileUploadError.httpError(error.error, error.message, statusCode)))
}
/// Fallback to a reasonable error message based on the HTTP status and response body
else {
let errorMessage = HTTPURLResponse.localizedString(forStatusCode: statusCode)
let errorBody = String(data: data ?? Data(), encoding: .utf8) ?? ""
completion(.failure(EventLoggingFileUploadError.httpError(errorMessage, errorBody, statusCode)))
}
return
}
completion(.success(data))
}).resume()
}
// MARK: - API Errors
/// An object representing the associated WordPress.com API error
struct EventLoggingNetworkServiceError: Codable {
let error: String
let message: String
}
private func decodeError(data: Data) -> EventLoggingNetworkServiceError? {
return try? JSONDecoder().decode(EventLoggingNetworkServiceError.self, from: data)
}
}
|
gpl-2.0
|
57ab10fa05f87ef8beff410407e0afec
| 38.018182 | 139 | 0.623486 | 5.46056 | false | false | false | false |
PomTTcat/YYModelGuideRead_JEFF
|
RxSwiftGuideRead/RxSwift-master/Tests/RxSwiftTests/AtomicTests.swift
|
2
|
4927
|
//
// AtomicTests.swift
// Tests
//
// Created by Krunoslav Zaher on 10/29/18.
// Copyright © 2018 Krunoslav Zaher. All rights reserved.
//
import XCTest
import Dispatch
#if true
typealias AtomicPrimitive = AtomicInt
#else
private struct AtomicIntSanityCheck {
var atom: Int32 = 0
init() {
}
init(_ atom: Int32) {
self.atom = atom
}
mutating func add(_ value: Int32) -> Int32 {
defer { self.atom += value }
return self.atom
}
mutating func sub(_ value: Int32) -> Int32 {
defer { self.atom -= value }
return self.atom
}
mutating func fetchOr(_ value: Int32) -> Int32 {
defer { self.atom |= value }
return self.atom
}
func load() -> Int32 {
return self.atom
}
}
fileprivate typealias AtomicPrimitive = AtomicIntSanityCheck
#endif
class AtomicTests: RxTest {}
extension AtomicTests {
func testAtomicInitialValue() {
let atomic = AtomicPrimitive(4)
XCTAssertEqual(globalLoad(atomic), 4)
}
func testAtomicInitialDefaultValue() {
let atomic = AtomicPrimitive()
XCTAssertEqual(globalLoad(atomic), 0)
}
}
extension AtomicTests {
private static let repeatCount = 100
private static let concurrency = 8
func testFetchOrSetsBits() {
let atomic = AtomicPrimitive()
XCTAssertEqual(fetchOr(atomic, 0), 0)
XCTAssertEqual(fetchOr(atomic, 4), 0)
XCTAssertEqual(fetchOr(atomic, 8), 4)
XCTAssertEqual(fetchOr(atomic, 0), 12)
}
func testFetchOrConcurrent() {
let queue = DispatchQueue.global(qos: .default)
for _ in 0 ..< AtomicTests.repeatCount {
let atomic = AtomicPrimitive(0)
let counter = AtomicPrimitive(0)
var expectations = [XCTestExpectation]()
for _ in 0 ..< AtomicTests.concurrency {
let expectation = self.expectation(description: "wait until operation completes")
queue.async {
while globalLoad(atomic) == 0 {}
if fetchOr(atomic, -1) == 1 {
globalAdd(counter, 1)
}
expectation.fulfill()
}
expectations.append(expectation)
}
fetchOr(atomic, 1)
#if os(Linux)
self.waitForExpectations(timeout: 1.0) { _ in }
#else
XCTWaiter().wait(for: expectations, timeout: 1.0)
#endif
XCTAssertEqual(globalLoad(counter), 1)
}
}
func testAdd() {
let atomic = AtomicPrimitive(0)
XCTAssertEqual(globalAdd(atomic, 4), 0)
XCTAssertEqual(globalAdd(atomic, 3), 4)
XCTAssertEqual(globalAdd(atomic, 10), 7)
}
func testAddConcurrent() {
let queue = DispatchQueue.global(qos: .default)
for _ in 0 ..< AtomicTests.repeatCount {
let atomic = AtomicPrimitive(0)
let counter = AtomicPrimitive(0)
var expectations = [XCTestExpectation]()
for _ in 0 ..< AtomicTests.concurrency {
let expectation = self.expectation(description: "wait until operation completes")
queue.async {
while globalLoad(atomic) == 0 {}
globalAdd(counter, 1)
expectation.fulfill()
}
expectations.append(expectation)
}
fetchOr(atomic, 1)
#if os(Linux)
waitForExpectations(timeout: 1.0) { _ in }
#else
XCTWaiter().wait(for: expectations, timeout: 1.0)
#endif
XCTAssertEqual(globalLoad(counter), 8)
}
}
func testSub() {
let atomic = AtomicPrimitive(0)
XCTAssertEqual(sub(atomic, -4), 0)
XCTAssertEqual(sub(atomic, -3), 4)
XCTAssertEqual(sub(atomic, -10), 7)
}
func testSubConcurrent() {
let queue = DispatchQueue.global(qos: .default)
for _ in 0 ..< AtomicTests.repeatCount {
let atomic = AtomicPrimitive(0)
let counter = AtomicPrimitive(0)
var expectations = [XCTestExpectation]()
for _ in 0 ..< AtomicTests.concurrency {
let expectation = self.expectation(description: "wait until operation completes")
queue.async {
while globalLoad(atomic) == 0 {}
sub(counter, 1)
expectation.fulfill()
}
expectations.append(expectation)
}
fetchOr(atomic, 1)
#if os(Linux)
waitForExpectations(timeout: 1.0) { _ in }
#else
XCTWaiter().wait(for: expectations, timeout: 1.0)
#endif
XCTAssertEqual(globalLoad(counter), -8)
}
}
}
|
mit
|
c0ac70d9647f3889554e6a80a0bf43ce
| 25.918033 | 97 | 0.549127 | 4.727447 | false | true | false | false |
ashleybrgr/surfPlay
|
surfPlay/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallRotate.swift
|
12
|
3815
|
//
// NVActivityIndicatorAnimationBallRotate.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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
class NVActivityIndicatorAnimationBallRotate: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(controlPoints: 0.7, -0.13, 0.22, 0.86)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = [0, 0.5, 1]
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, Double.pi, 2 * Double.pi]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circles
let leftCircle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let rightCircle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let centerCircle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
leftCircle.opacity = 0.8
leftCircle.frame = CGRect(x: 0, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
rightCircle.opacity = 0.8
rightCircle.frame = CGRect(x: size.width - circleSize, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
centerCircle.frame = CGRect(x: (size.width - circleSize) / 2, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
let circle = CALayer()
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height)
circle.frame = frame
circle.addSublayer(leftCircle)
circle.addSublayer(rightCircle)
circle.addSublayer(centerCircle)
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
|
apache-2.0
|
d48049e1538763754e32a9d24f0d1f25
| 45.52439 | 162 | 0.711927 | 4.646772 | false | false | false | false |
ashleybrgr/surfPlay
|
surfPlay/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallZigZag.swift
|
12
|
3533
|
//
// NVActivityIndicatorAnimationBallZigZag.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 QuartzCore
class NVActivityIndicatorAnimationBallZigZag: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.7
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle 1
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
// Circle 2 animation
animation.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
]
// Draw circle 2
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
}
func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) {
let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
|
apache-2.0
|
ee4194eec818b989b533bca7feded28b
| 44.294872 | 160 | 0.706482 | 4.685676 | false | false | false | false |
eraydiler/password-locker
|
PasswordLockerSwift/Supporting Files/AppDelegate.swift
|
1
|
3076
|
//
// AppDelegate.swift
// PasswordLockerSwift
//
// Created by Eray on 19/01/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
import CoreData
import MagicalRecord
let kPasswordLockerUserDefaultsHasInitialized = "kPasswordLockerUserDefaultsHasInitialized"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
MagicalRecord.setupCoreDataStack()
let managedObjectContext = NSManagedObjectContext.mr_default()
let isAppInitializedWithData = UserDefaults.standard.bool(forKey: kPasswordLockerUserDefaultsHasInitialized)
if (isAppInitializedWithData == false) {
DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Category")
DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Type")
DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Row")
DataFactory.setupInitialData(managedObjectContext)
UserDefaults.standard.set(true, forKey: kPasswordLockerUserDefaultsHasInitialized)
print("Initial Data inserted")
}
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) {
guard let splashController = self.window?.rootViewController else {
return
}
guard let aController = splashController.presentedViewController
else {
return
}
guard let tabBarController = aController.presentedViewController else {
return
}
tabBarController.dismiss(animated: false)
}
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:.
MagicalRecord.cleanUp()
}
}
|
mit
|
7c60c37081827cf0dd154c6e02057784
| 39.473684 | 285 | 0.726268 | 5.749533 | false | false | false | false |
WebAPIKit/WebAPIKit
|
Sources/WebAPIKit/Stub/StubConnection.swift
|
1
|
3086
|
/**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* 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
/// A stub type to handle a http request.
open class StubConnection: Cancelable {
public var request: URLRequest
public var queue: DispatchQueue?
public var handler: HTTPHandler
public init(request: URLRequest, queue: DispatchQueue?, handler: @escaping HTTPHandler) {
self.request = request
self.queue = queue
self.handler = handler
}
public var responder: StubResponder?
public var isResponded = false
public var isCanceled = false
open func cancel() {
guard isActive else { return }
isCanceled = true
}
open func respond(data: Data?, response: HTTPURLResponse?, error: Error?) {
guard isActive else { return }
handler(data, response, error)
isResponded = true
}
open func respond() {
if let responder = responder {
responder.respond(to: self)
} else {
respond(data: nil, response: nil, error: nil)
}
}
}
extension StubConnection {
/// If the connection is not yet responded to or canceled.
var isActive: Bool {
return !isResponded && !isCanceled
}
}
/// A type that log all connections.
public protocol StubConnectionLogger {
/// All logged connections.
var connections: [StubConnection] { get }
}
extension StubConnectionLogger {
/// If there is any connection logged.
public var hasConnection: Bool {
return connections.count > 0
}
/// The last connection that is not sent to `passthroughClient`.
public var lastConnection: StubConnection? {
return connections.last
}
/// If there is any connection that is not yet responded to or canceled.
public var hasActiveConnection: Bool {
for connection in connections where connection.isActive {
return true
}
return false
}
}
|
mit
|
abddcbd5e357940b16a70e9bc4f5b521
| 29.554455 | 93 | 0.682437 | 4.565089 | false | false | false | false |
alessioros/mobilecodegenerator3
|
examples/ParkTraining/completed/ios/ParkTraining/ParkTraining/PhotoEditViewController.swift
|
2
|
3426
|
import UIKit
import CoreData
class PhotoEditViewController: UIViewController
{
@IBOutlet weak var deletePhotoButton: UIButton!
@IBOutlet weak var mImageView: UIImageView!
var photoIndex: Int = 0
var photo: NSManagedObject!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//Legge la foto
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Photo")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
self.photo = results[self.photoIndex] as! NSManagedObject
} catch {
print("Error")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//aggiorna ui
let path = self.photo.valueForKey("path") as! String
print(path)
//self.mImageView.image = UIImage(contentsOfFile: path)
}
override func viewDidLoad() {
super.viewDidLoad()
deletePhotoButton.layer.cornerRadius = 36
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
@IBAction func deletePhotoButtonTouchDown(sender: UIButton) {
// Changes background color of button when clicked
sender.backgroundColor = UIColor(red: 0.7019608, green: 0.019607844, blue: 0.019607844, alpha: 1)
//TODO Implement the action
}
@IBAction func deletePhotoButtonTouchUpInside(sender: UIButton) {
// Restore original background color of button after click
sender.backgroundColor = UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 1)
//TODO Implement the action
//Create the AlertController
let deletePhotoDialog: UIAlertController = UIAlertController(title: "Delete Photo", message: "Are you sure?", preferredStyle: .Alert)
//Create and add the Cancel action
let deletePhotoDialogCancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the alert
}
//Create and add the Ok action
let deletePhotoDialogOkAction: UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { action -> Void in
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
managedContext.deleteObject(self.photo)
do {
try managedContext.save()
} catch {
print("error")
}
self.navigationController?.popViewControllerAnimated(true)
}
deletePhotoDialog.addAction(deletePhotoDialogCancelAction)
deletePhotoDialog.addAction(deletePhotoDialogOkAction)
//Present the AlertController
self.presentViewController(deletePhotoDialog, animated: true, completion: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {}
}
|
gpl-3.0
|
fd2c9e02ce3432a5c941baae46c72c3d
| 32.920792 | 141 | 0.661413 | 5.144144 | false | false | false | false |
ming1016/smck
|
smck/Lib/RxSwift/ObserverBase.swift
|
15
|
759
|
//
// ObserverBase.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class ObserverBase<ElementType> : Disposable, ObserverType {
typealias E = ElementType
private var _isStopped: AtomicInt = 0
func on(_ event: Event<E>) {
switch event {
case .next:
if _isStopped == 0 {
onCore(event)
}
case .error, .completed:
if !AtomicCompareAndSwap(0, 1, &_isStopped) {
return
}
onCore(event)
}
}
func onCore(_ event: Event<E>) {
abstractMethod()
}
func dispose() {
_ = AtomicCompareAndSwap(0, 1, &_isStopped)
}
}
|
apache-2.0
|
40ee7ccae19cd1312f690ed7277094b3
| 19.486486 | 60 | 0.530343 | 4.187845 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/Pods/MaterialKit/Source/MKColor.swift
|
4
|
16532
|
//
// MKColor.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
extension UIColor {
convenience public init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat((hex & 0xFF)) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
public struct MKColor {
public struct Red {
public static let P50 = UIColor(hex: 0xFFEBEE)
public static let P100 = UIColor(hex: 0xFFCDD2)
public static let P200 = UIColor(hex: 0xEF9A9A)
public static let P300 = UIColor(hex: 0xE57373)
public static let P400 = UIColor(hex: 0xEF5350)
public static let P500 = UIColor(hex: 0xF44336)
public static let P600 = UIColor(hex: 0xE53935)
public static let P700 = UIColor(hex: 0xD32F2F)
public static let P800 = UIColor(hex: 0xC62828)
public static let P900 = UIColor(hex: 0xB71C1C)
public static let A100 = UIColor(hex: 0xFF8A80)
public static let A200 = UIColor(hex: 0xFF5252)
public static let A400 = UIColor(hex: 0xFF1744)
public static let A700 = UIColor(hex: 0xD50000)
}
public struct Pink {
public static let P50 = UIColor(hex: 0xFCE4EC)
public static let P100 = UIColor(hex: 0xF8BBD0)
public static let P200 = UIColor(hex: 0xF48FB1)
public static let P300 = UIColor(hex: 0xF06292)
public static let P400 = UIColor(hex: 0xEC407A)
public static let P500 = UIColor(hex: 0xE91E63)
public static let P600 = UIColor(hex: 0xD81B60)
public static let P700 = UIColor(hex: 0xC2185B)
public static let P800 = UIColor(hex: 0xAD1457)
public static let P900 = UIColor(hex: 0x880E4F)
public static let A100 = UIColor(hex: 0xFF80AB)
public static let A200 = UIColor(hex: 0xFF4081)
public static let A400 = UIColor(hex: 0xF50057)
public static let A700 = UIColor(hex: 0xC51162)
}
public struct Purple {
public static let P50 = UIColor(hex: 0xF3E5F5)
public static let P100 = UIColor(hex: 0xE1BEE7)
public static let P200 = UIColor(hex: 0xCE93D8)
public static let P300 = UIColor(hex: 0xBA68C8)
public static let P400 = UIColor(hex: 0xAB47BC)
public static let P500 = UIColor(hex: 0x9C27B0)
public static let P600 = UIColor(hex: 0x8E24AA)
public static let P700 = UIColor(hex: 0x7B1FA2)
public static let P800 = UIColor(hex: 0x6A1B9A)
public static let P900 = UIColor(hex: 0x4A148C)
public static let A100 = UIColor(hex: 0xEA80FC)
public static let A200 = UIColor(hex: 0xE040FB)
public static let A400 = UIColor(hex: 0xD500F9)
public static let A700 = UIColor(hex: 0xAA00FF)
}
public struct DeepPurple {
public static let P50 = UIColor(hex: 0xEDE7F6)
public static let P100 = UIColor(hex: 0xD1C4E9)
public static let P200 = UIColor(hex: 0xB39DDB)
public static let P300 = UIColor(hex: 0x9575CD)
public static let P400 = UIColor(hex: 0x7E57C2)
public static let P500 = UIColor(hex: 0x673AB7)
public static let P600 = UIColor(hex: 0x5E35B1)
public static let P700 = UIColor(hex: 0x512DA8)
public static let P800 = UIColor(hex: 0x4527A0)
public static let P900 = UIColor(hex: 0x311B92)
public static let A100 = UIColor(hex: 0xB388FF)
public static let A200 = UIColor(hex: 0x7C4DFF)
public static let A400 = UIColor(hex: 0x651FFF)
public static let A700 = UIColor(hex: 0x6200EA)
}
public struct Indigo {
public static let P50 = UIColor(hex: 0xE8EAF6)
public static let P100 = UIColor(hex: 0xC5CAE9)
public static let P200 = UIColor(hex: 0x9FA8DA)
public static let P300 = UIColor(hex: 0x7986CB)
public static let P400 = UIColor(hex: 0x5C6BC0)
public static let P500 = UIColor(hex: 0x3F51B5)
public static let P600 = UIColor(hex: 0x3949AB)
public static let P700 = UIColor(hex: 0x303F9F)
public static let P800 = UIColor(hex: 0x283593)
public static let P900 = UIColor(hex: 0x1A237E)
public static let A100 = UIColor(hex: 0x8C9EFF)
public static let A200 = UIColor(hex: 0x536DFE)
public static let A400 = UIColor(hex: 0x3D5AFE)
public static let A700 = UIColor(hex: 0x304FFE)
}
public struct Blue {
public static let P50 = UIColor(hex: 0xE3F2FD)
public static let P100 = UIColor(hex: 0xBBDEFB)
public static let P200 = UIColor(hex: 0x90CAF9)
public static let P300 = UIColor(hex: 0x64B5F6)
public static let P400 = UIColor(hex: 0x42A5F5)
public static let P500 = UIColor(hex: 0x2196F3)
public static let P600 = UIColor(hex: 0x1E88E5)
public static let P700 = UIColor(hex: 0x1976D2)
public static let P800 = UIColor(hex: 0x1565C0)
public static let P900 = UIColor(hex: 0x0D47A1)
public static let A100 = UIColor(hex: 0x82B1FF)
public static let A200 = UIColor(hex: 0x448AFF)
public static let A400 = UIColor(hex: 0x2979FF)
public static let A700 = UIColor(hex: 0x2962FF)
}
public struct LightBlue {
public static let P50 = UIColor(hex: 0xE1F5FE)
public static let P100 = UIColor(hex: 0xB3E5FC)
public static let P200 = UIColor(hex: 0x81D4FA)
public static let P300 = UIColor(hex: 0x4FC3F7)
public static let P400 = UIColor(hex: 0x29B6F6)
public static let P500 = UIColor(hex: 0x03A9F4)
public static let P600 = UIColor(hex: 0x039BE5)
public static let P700 = UIColor(hex: 0x0288D1)
public static let P800 = UIColor(hex: 0x0277BD)
public static let P900 = UIColor(hex: 0x01579B)
public static let A100 = UIColor(hex: 0x80D8FF)
public static let A200 = UIColor(hex: 0x40C4FF)
public static let A400 = UIColor(hex: 0x00B0FF)
public static let A700 = UIColor(hex: 0x0091EA)
}
public struct Cyan {
public static let P50 = UIColor(hex: 0xE0F7FA)
public static let P100 = UIColor(hex: 0xB2EBF2)
public static let P200 = UIColor(hex: 0x80DEEA)
public static let P300 = UIColor(hex: 0x4DD0E1)
public static let P400 = UIColor(hex: 0x26C6DA)
public static let P500 = UIColor(hex: 0x00BCD4)
public static let P600 = UIColor(hex: 0x00ACC1)
public static let P700 = UIColor(hex: 0x0097A7)
public static let P800 = UIColor(hex: 0x00838F)
public static let P900 = UIColor(hex: 0x006064)
public static let A100 = UIColor(hex: 0x84FFFF)
public static let A200 = UIColor(hex: 0x18FFFF)
public static let A400 = UIColor(hex: 0x00E5FF)
public static let A700 = UIColor(hex: 0x00B8D4)
}
public struct Teal {
public static let P50 = UIColor(hex: 0xE0F2F1)
public static let P100 = UIColor(hex: 0xB2DFDB)
public static let P200 = UIColor(hex: 0x80CBC4)
public static let P300 = UIColor(hex: 0x4DB6AC)
public static let P400 = UIColor(hex: 0x26A69A)
public static let P500 = UIColor(hex: 0x009688)
public static let P600 = UIColor(hex: 0x00897B)
public static let P700 = UIColor(hex: 0x00796B)
public static let P800 = UIColor(hex: 0x00695C)
public static let P900 = UIColor(hex: 0x004D40)
public static let A100 = UIColor(hex: 0xA7FFEB)
public static let A200 = UIColor(hex: 0x64FFDA)
public static let A400 = UIColor(hex: 0x1DE9B6)
public static let A700 = UIColor(hex: 0x00BFA5)
}
public struct Green {
public static let P50 = UIColor(hex: 0xE8F5E9)
public static let P100 = UIColor(hex: 0xC8E6C9)
public static let P200 = UIColor(hex: 0xA5D6A7)
public static let P300 = UIColor(hex: 0x81C784)
public static let P400 = UIColor(hex: 0x66BB6A)
public static let P500 = UIColor(hex: 0x4CAF50)
public static let P600 = UIColor(hex: 0x43A047)
public static let P700 = UIColor(hex: 0x388E3C)
public static let P800 = UIColor(hex: 0x2E7D32)
public static let P900 = UIColor(hex: 0x1B5E20)
public static let A100 = UIColor(hex: 0xB9F6CA)
public static let A200 = UIColor(hex: 0x69F0AE)
public static let A400 = UIColor(hex: 0x00E676)
public static let A700 = UIColor(hex: 0x00C853)
}
public struct LightGreen {
public static let P50 = UIColor(hex: 0xF1F8E9)
public static let P100 = UIColor(hex: 0xDCEDC8)
public static let P200 = UIColor(hex: 0xC5E1A5)
public static let P300 = UIColor(hex: 0xAED581)
public static let P400 = UIColor(hex: 0x9CCC65)
public static let P500 = UIColor(hex: 0x8BC34A)
public static let P600 = UIColor(hex: 0x7CB342)
public static let P700 = UIColor(hex: 0x689F38)
public static let P800 = UIColor(hex: 0x558B2F)
public static let P900 = UIColor(hex: 0x33691E)
public static let A100 = UIColor(hex: 0xCCFF90)
public static let A200 = UIColor(hex: 0xB2FF59)
public static let A400 = UIColor(hex: 0x76FF03)
public static let A700 = UIColor(hex: 0x64DD17)
}
public struct Lime {
public static let P50 = UIColor(hex: 0xF9FBE7)
public static let P100 = UIColor(hex: 0xF0F4C3)
public static let P200 = UIColor(hex: 0xE6EE9C)
public static let P300 = UIColor(hex: 0xDCE775)
public static let P400 = UIColor(hex: 0xD4E157)
public static let P500 = UIColor(hex: 0xCDDC39)
public static let P600 = UIColor(hex: 0xC0CA33)
public static let P700 = UIColor(hex: 0xAFB42B)
public static let P800 = UIColor(hex: 0x9E9D24)
public static let P900 = UIColor(hex: 0x827717)
public static let A100 = UIColor(hex: 0xF4FF81)
public static let A200 = UIColor(hex: 0xEEFF41)
public static let A400 = UIColor(hex: 0xC6FF00)
public static let A700 = UIColor(hex: 0xAEEA00)
}
public struct Yellow {
public static let P50 = UIColor(hex: 0xFFFDE7)
public static let P100 = UIColor(hex: 0xFFF9C4)
public static let P200 = UIColor(hex: 0xFFF59D)
public static let P300 = UIColor(hex: 0xFFF176)
public static let P400 = UIColor(hex: 0xFFEE58)
public static let P500 = UIColor(hex: 0xFFEB3B)
public static let P600 = UIColor(hex: 0xFDD835)
public static let P700 = UIColor(hex: 0xFBC02D)
public static let P800 = UIColor(hex: 0xF9A825)
public static let P900 = UIColor(hex: 0xF57F17)
public static let A100 = UIColor(hex: 0xFFFF8D)
public static let A200 = UIColor(hex: 0xFFFF00)
public static let A400 = UIColor(hex: 0xFFEA00)
public static let A700 = UIColor(hex: 0xFFD600)
}
public struct Amber {
public static let P50 = UIColor(hex: 0xFFF8E1)
public static let P100 = UIColor(hex: 0xFFECB3)
public static let P200 = UIColor(hex: 0xFFE082)
public static let P300 = UIColor(hex: 0xFFD54F)
public static let P400 = UIColor(hex: 0xFFCA28)
public static let P500 = UIColor(hex: 0xFFC107)
public static let P600 = UIColor(hex: 0xFFB300)
public static let P700 = UIColor(hex: 0xFFA000)
public static let P800 = UIColor(hex: 0xFF8F00)
public static let P900 = UIColor(hex: 0xFF6F00)
public static let A100 = UIColor(hex: 0xFFE57F)
public static let A200 = UIColor(hex: 0xFFD740)
public static let A400 = UIColor(hex: 0xFFC400)
public static let A700 = UIColor(hex: 0xFFAB00)
}
public struct Orange {
public static let P50 = UIColor(hex: 0xFFF3E0)
public static let P100 = UIColor(hex: 0xFFE0B2)
public static let P200 = UIColor(hex: 0xFFCC80)
public static let P300 = UIColor(hex: 0xFFB74D)
public static let P400 = UIColor(hex: 0xFFA726)
public static let P500 = UIColor(hex: 0xFF9800)
public static let P600 = UIColor(hex: 0xFB8C00)
public static let P700 = UIColor(hex: 0xF57C00)
public static let P800 = UIColor(hex: 0xEF6C00)
public static let P900 = UIColor(hex: 0xE65100)
public static let A100 = UIColor(hex: 0xFFD180)
public static let A200 = UIColor(hex: 0xFFAB40)
public static let A400 = UIColor(hex: 0xFF9100)
public static let A700 = UIColor(hex: 0xFF6D00)
}
public struct DeepOrange {
public static let P50 = UIColor(hex: 0xFBE9E7)
public static let P100 = UIColor(hex: 0xFFCCBC)
public static let P200 = UIColor(hex: 0xFFAB91)
public static let P300 = UIColor(hex: 0xFF8A65)
public static let P400 = UIColor(hex: 0xFF7043)
public static let P500 = UIColor(hex: 0xFF5722)
public static let P600 = UIColor(hex: 0xF4511E)
public static let P700 = UIColor(hex: 0xE64A19)
public static let P800 = UIColor(hex: 0xD84315)
public static let P900 = UIColor(hex: 0xBF360C)
public static let A100 = UIColor(hex: 0xFF9E80)
public static let A200 = UIColor(hex: 0xFF6E40)
public static let A400 = UIColor(hex: 0xFF3D00)
public static let A700 = UIColor(hex: 0xDD2C00)
}
public struct Brown {
public static let P50 = UIColor(hex: 0xEFEBE9)
public static let P100 = UIColor(hex: 0xD7CCC8)
public static let P200 = UIColor(hex: 0xBCAAA4)
public static let P300 = UIColor(hex: 0xA1887F)
public static let P400 = UIColor(hex: 0x8D6E63)
public static let P500 = UIColor(hex: 0x795548)
public static let P600 = UIColor(hex: 0x6D4C41)
public static let P700 = UIColor(hex: 0x5D4037)
public static let P800 = UIColor(hex: 0x4E342E)
public static let P900 = UIColor(hex: 0x3E2723)
}
public struct Grey {
public static let P50 = UIColor(hex: 0xFAFAFA)
public static let P100 = UIColor(hex: 0xF5F5F5)
public static let P200 = UIColor(hex: 0xEEEEEE)
public static let P300 = UIColor(hex: 0xE0E0E0)
public static let P400 = UIColor(hex: 0xBDBDBD)
public static let P500 = UIColor(hex: 0x9E9E9E)
public static let P600 = UIColor(hex: 0x757575)
public static let P700 = UIColor(hex: 0x616161)
public static let P800 = UIColor(hex: 0x424242)
public static let P900 = UIColor(hex: 0x212121)
}
public struct BlueGrey {
public static let P50 = UIColor(hex: 0xECEFF1)
public static let P100 = UIColor(hex: 0xCFD8DC)
public static let P200 = UIColor(hex: 0xB0BEC5)
public static let P300 = UIColor(hex: 0x90A4AE)
public static let P400 = UIColor(hex: 0x78909C)
public static let P500 = UIColor(hex: 0x607D8B)
public static let P600 = UIColor(hex: 0x546E7A)
public static let P700 = UIColor(hex: 0x455A64)
public static let P800 = UIColor(hex: 0x37474F)
public static let P900 = UIColor(hex: 0x263238)
}
}
}
|
mit
|
2c7e26b61a54c0ca4223540afd1dcf3f
| 48.645646 | 67 | 0.606339 | 3.566775 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Private Messages/MessageAssertion.swift
|
1
|
1705
|
import EurofurenceModel
import TestUtilities
class MessageAssertion: Assertion {
func assertMessages(_ messages: [Message], characterisedBy characteristics: [MessageCharacteristics]) {
guard messages.count == characteristics.count else {
fail(message: "Differing amount of expected/actual messages")
return
}
let sortedCharacteristics = characteristics.sorted { (first, second) -> Bool in
return first.receivedDateTime.compare(second.receivedDateTime) == .orderedDescending
}
for (idx, message) in messages.enumerated() {
let characteristic = sortedCharacteristics[idx]
assertMessage(message, characterisedBy: characteristic)
}
}
func assertMessage(_ message: Message?, characterisedBy characteristic: MessageCharacteristics) {
guard let message = message else {
fail(message: "Expected a message with id \(characteristic.identifier), got nil")
return
}
let observer = CapturingPrivateMessageObserver()
message.add(observer)
let expectedReadState: CapturingPrivateMessageObserver.ReadState = characteristic.isRead ? .read : .unread
assert(message.identifier.rawValue, isEqualTo: characteristic.identifier)
assert(message.authorName, isEqualTo: characteristic.authorName)
assert(message.receivedDateTime, isEqualTo: characteristic.receivedDateTime)
assert(message.subject, isEqualTo: characteristic.subject)
assert(message.contents, isEqualTo: characteristic.contents)
assert(expectedReadState, isEqualTo: observer.currentReadState)
}
}
|
mit
|
e7f8e8cbe454912213fb9c7f389398e3
| 40.585366 | 114 | 0.695015 | 5.664452 | false | false | false | false |
DJBen/MathUtil
|
MathUtil/SCNVector3+Util.swift
|
1
|
7481
|
/*
* Copyright (c) 2013-2014 Kim Pedersen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import SceneKit
public extension SCNVector3 {
/**
* Negates the vector described by SCNVector3
*/
public mutating func negate() -> SCNVector3 {
self = negated()
return self
}
/**
* Negates the vector described by SCNVector3 and returns
* the result as a new SCNVector3.
*/
public func negated() -> SCNVector3 {
return self * -1
}
/**
* Returns the length (magnitude) of the vector described by the SCNVector3
*/
public func length() -> Float {
#if os(OSX)
return sqrt(x*x + y*y + z*z)
#else
return sqrtf(x*x + y*y + z*z)
#endif
}
/**
* Normalizes the vector described by the SCNVector3 to length 1.0 and returns
* the result as a new SCNVector3.
*/
public func normalized() -> SCNVector3 {
return self / length()
}
/**
* Normalizes the vector described by the SCNVector3 to length 1.0.
*/
public mutating func normalize() -> SCNVector3 {
self = normalized()
return self
}
/**
* Calculates the distance between two SCNVector3. Pythagoras!
*/
public func distance(_ vector: SCNVector3) -> Float {
return (self - vector).length()
}
/**
* Calculates the dot product between two SCNVector3.
*/
public func dot(_ vector: SCNVector3) -> Float {
return x * vector.x + y * vector.y + z * vector.z
}
/**
* Calculates the cross product between two SCNVector3.
*/
public func cross(_ vector: SCNVector3) -> SCNVector3 {
return SCNVector3Make(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x)
}
}
public prefix func -(v: SCNVector3) -> SCNVector3 {
return v.negated()
}
/**
* Adds two SCNVector3 vectors and returns the result as a new SCNVector3.
*/
public func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z)
}
/**
* Increments a SCNVector3 with the value of another.
*/
public func += (left: inout SCNVector3, right: SCNVector3) {
left = left + right
}
/**
* Subtracts two SCNVector3 vectors and returns the result as a new SCNVector3.
*/
public func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
}
/**
* Decrements a SCNVector3 with the value of another.
*/
public func -= (left: inout SCNVector3, right: SCNVector3) {
left = left - right
}
/**
* Multiplies two SCNVector3 vectors and returns the result as a new SCNVector3.
*/
public func * (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x * right.x, left.y * right.y, left.z * right.z)
}
/**
* Multiplies a SCNVector3 with another.
*/
public func *= (left: inout SCNVector3, right: SCNVector3) {
left = left * right
}
/**
* Multiplies the x, y and z fields of a SCNVector3 with the same scalar value and
* returns the result as a new SCNVector3.
*/
public func * (vector: SCNVector3, scalar: Float) -> SCNVector3 {
return SCNVector3Make(vector.x * scalar, vector.y * scalar, vector.z * scalar)
}
/**
* Multiplies the x and y fields of a SCNVector3 with the same scalar value.
*/
public func *= (vector: inout SCNVector3, scalar: Float) {
vector = vector * scalar
}
/**
* Divides two SCNVector3 vectors abd returns the result as a new SCNVector3
*/
public func / (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.x / right.x, left.y / right.y, left.z / right.z)
}
/**
* Divides a SCNVector3 by another.
*/
public func /= (left: inout SCNVector3, right: SCNVector3) {
left = left / right
}
/**
* Divides the x, y and z fields of a SCNVector3 by the same scalar value and
* returns the result as a new SCNVector3.
*/
public func / (vector: SCNVector3, scalar: Float) -> SCNVector3 {
return SCNVector3Make(vector.x / scalar, vector.y / scalar, vector.z / scalar)
}
/**
* Divides the x, y and z of a SCNVector3 by the same scalar value.
*/
public func /= (vector: inout SCNVector3, scalar: Float) {
vector = vector / scalar
}
/**
* Negate a vector
*/
func SCNVector3Negate(vector: SCNVector3) -> SCNVector3 {
return vector * -1
}
/**
* Returns the length (magnitude) of the vector described by the SCNVector3
*/
func SCNVector3Length(_ vector: SCNVector3) -> Float {
#if os(OSX)
return sqrt(vector.x*vector.x + vector.y*vector.y + vector.z*vector.z)
#else
return sqrtf(vector.x*vector.x + vector.y*vector.y + vector.z*vector.z)
#endif
}
/**
* Returns the distance between two SCNVector3 vectors
*/
func SCNVector3Distance(vectorStart: SCNVector3, vectorEnd: SCNVector3) -> Float {
return SCNVector3Length(vectorEnd - vectorStart)
}
/**
* Returns the distance between two SCNVector3 vectors
*/
func SCNVector3Normalize(vector: SCNVector3) -> SCNVector3 {
return vector / SCNVector3Length(vector)
}
/**
* Calculates the dot product between two SCNVector3 vectors
*/
func SCNVector3DotProduct(left: SCNVector3, right: SCNVector3) -> Float {
return left.x * right.x + left.y * right.y + left.z * right.z
}
/**
* Calculates the cross product between two SCNVector3 vectors
*/
func SCNVector3CrossProduct(left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3Make(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x)
}
/**
* Calculates the SCNVector from lerping between two SCNVector3 vectors
*/
func SCNVector3Lerp(vectorStart: SCNVector3, vectorEnd: SCNVector3, t: Float) -> SCNVector3 {
return SCNVector3Make(vectorStart.x + ((vectorEnd.x - vectorStart.x) * t), vectorStart.y + ((vectorEnd.y - vectorStart.y) * t), vectorStart.z + ((vectorEnd.z - vectorStart.z) * t))
}
/**
* Project the vector, vectorToProject, onto the vector, projectionVector.
*/
func SCNVector3Project(vectorToProject: SCNVector3, projectionVector: SCNVector3) -> SCNVector3 {
let scale: Float = SCNVector3DotProduct(left: projectionVector, right: vectorToProject) / SCNVector3DotProduct(left: projectionVector, right: projectionVector)
let v: SCNVector3 = projectionVector * scale
return v
}
|
mit
|
26bf60520e83cca44973d993d27c2c59
| 29.913223 | 184 | 0.677851 | 3.768766 | false | false | false | false |
eface2face/cordova-plugin-iosrtc
|
src/PluginMediaStreamTrack.swift
|
2
|
3937
|
import Foundation
class PluginMediaStreamTrack : NSObject {
var rtcMediaStreamTrack: RTCMediaStreamTrack
var id: String
var kind: String
var eventListener: ((_ data: NSDictionary) -> Void)?
var eventListenerForEnded: (() -> Void)?
var lostStates = Array<String>()
var renders: [String : PluginMediaStreamRenderer]
init(rtcMediaStreamTrack: RTCMediaStreamTrack, trackId: String? = nil) {
NSLog("PluginMediaStreamTrack#init()")
self.rtcMediaStreamTrack = rtcMediaStreamTrack
if (trackId == nil) {
// Handle possible duplicate remote trackId with janus or short duplicate name
// See: https://github.com/cordova-rtc/cordova-plugin-iosrtc/issues/432
if (rtcMediaStreamTrack.trackId.count<36) {
self.id = rtcMediaStreamTrack.trackId + "_" + UUID().uuidString;
} else {
self.id = rtcMediaStreamTrack.trackId;
}
} else {
self.id = trackId!;
}
self.kind = rtcMediaStreamTrack.kind
self.renders = [:]
}
deinit {
NSLog("PluginMediaStreamTrack#deinit()")
stop()
}
func run() {
NSLog("PluginMediaStreamTrack#run() [kind:%@, id:%@]", String(self.kind), String(self.id))
}
func getReadyState() -> String {
switch self.rtcMediaStreamTrack.readyState {
case RTCMediaStreamTrackState.live:
return "live"
case RTCMediaStreamTrackState.ended:
return "ended"
default:
return "ended"
}
}
func getJSON() -> NSDictionary {
return [
"id": self.id,
"kind": self.kind,
"trackId": self.rtcMediaStreamTrack.trackId,
"enabled": self.rtcMediaStreamTrack.isEnabled ? true : false,
"capabilities": self.rtcMediaStreamTrack.capabilities,
"readyState": self.getReadyState()
]
}
func setListener(
_ eventListener: @escaping (_ data: NSDictionary) -> Void,
eventListenerForEnded: @escaping () -> Void
) {
if(self.eventListener != nil){
NSLog("PluginMediaStreamTrack#setListener():Error Listener already Set [kind:%@, id:%@]", String(self.kind), String(self.id));
return;
}
NSLog("PluginMediaStreamTrack#setListener() [kind:%@, id:%@]", String(self.kind), String(self.id))
self.eventListener = eventListener
self.eventListenerForEnded = eventListenerForEnded
for readyState in self.lostStates {
self.eventListener!([
"type": "statechange",
"readyState": readyState,
"enabled": self.rtcMediaStreamTrack.isEnabled ? true : false
])
if readyState == "ended" {
if(self.eventListenerForEnded != nil) {
self.eventListenerForEnded!()
}
}
}
self.lostStates.removeAll()
}
func setEnabled(_ value: Bool) {
NSLog("PluginMediaStreamTrack#setEnabled() [kind:%@, id:%@, value:%@]",
String(self.kind), String(self.id), String(value))
if (self.rtcMediaStreamTrack.isEnabled != value) {
self.rtcMediaStreamTrack.isEnabled = value
if (value) {
self.rtcMediaStreamTrack.videoCaptureController?.startCapture()
}else {
self.rtcMediaStreamTrack.videoCaptureController?.stopCapture()
}
}
}
func switchCamera() {
self.rtcMediaStreamTrack.videoCaptureController?.switchCamera()
}
func registerRender(render: PluginMediaStreamRenderer) {
if let exist = self.renders[render.id] {
_ = exist
} else {
self.renders[render.id] = render
}
}
func unregisterRender(render: PluginMediaStreamRenderer) {
self.renders.removeValue(forKey: render.id);
}
func stop() {
NSLog("PluginMediaStreamTrack#stop() [kind:%@, id:%@]", String(self.kind), String(self.id))
self.rtcMediaStreamTrack.videoCaptureController?.stopCapture();
// Let's try setEnabled(false), but it also fails.
self.rtcMediaStreamTrack.isEnabled = false
// eventListener could be null if the track is never used
if(self.eventListener != nil){
self.eventListener!([
"type": "statechange",
"readyState": "ended",
"enabled": self.rtcMediaStreamTrack.isEnabled ? true : false
])
}
for (_, render) in self.renders {
render.stop()
}
self.renders.removeAll();
}
}
|
mit
|
5de93d98591f6ba1f79988f162ed3141
| 25.965753 | 129 | 0.696977 | 3.707156 | false | false | false | false |
tensorflow/swift-models
|
Checkpoints/CheckpointReader.swift
|
1
|
15302
|
// Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The TensorFlow v2 checkpoint format is described in the following:
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/tensor_bundle/tensor_bundle.h
// and consists of an index file (with a `.index` extension) and a series of sharded data files that
// have the same base file name, but extensions of the form `.data-00001-of-00020`. The index file
// contains key-value pairs of metadata that provide shapes of tensors and where to read in the
// shards to obtain their raw bytes.
import Foundation
import ModelSupport
import TensorFlow
/// A Swift-native TensorFlow v2 checkpoint reader that can download all checkpoint files from
/// remote locations and store them in a local temporary directory. This reader has no dependencies
/// on the TensorFlow runtime or libraries.
open class CheckpointReader {
let header: Tensorflow_BundleHeaderProto
let metadata: [String: Tensorflow_BundleEntryProto]
var shardCache: [URL: Data] = [:]
let fileSystem: FileSystem
/// The local checkpoint location.
public let localCheckpointLocation: URL
/// The number of tensors stored in the checkpoint.
public var tensorCount: Int { metadata.count }
/// The names of the tensors stored in the checkpoint.
public var tensorNames: [String] { [String](metadata.keys) }
/// CRC verification during checkpoint loading is enabled by default, but can be selectively
/// disabled to speed up reads in debug builds or test cases.
public var isCRCVerificationEnabled: Bool = true
/// Initializes the checkpoint reader from either a local or remote directory. If remote,
/// automatically downloads the checkpoint files into a temporary directory.
///
/// - Parameters:
/// - checkpointLocation: Either a URL to the checkpoint files, where the last component is the file
/// base of the checkpoint files, or a URL to an archive containing the checkpoint files.
/// - modelName: A distinct name for the model, to ensure that checkpoints with the same base
/// name but for different models don't collide when downloaded.
public init(
checkpointLocation: URL, modelName: String, additionalFiles: [String] = [],
fileSystem: FileSystem = FoundationFileSystem()
) throws {
self.fileSystem = fileSystem
let temporaryDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(
modelName, isDirectory: true)
// If this is an archive, download if necessary and point to the locally extracted files.
let finalCheckpointLocation: URL
if checkpointLocation.isArchive {
finalCheckpointLocation = try CheckpointReader.downloadAndExtractArchive(
from: checkpointLocation, to: temporaryDirectory)
} else {
finalCheckpointLocation = checkpointLocation
}
// If URL that was passed in was a file, or if an archive was downloaded and extracted,
// read the local checkpoint from the filesystem. Otherwise, download the index first and
// determine what other files to download.
let checkpointBase = finalCheckpointLocation.lastPathComponent
let indexReader: CheckpointIndexReader
if finalCheckpointLocation.isFileURL {
self.localCheckpointLocation = finalCheckpointLocation
indexReader = try CheckpointIndexReader(
file: finalCheckpointLocation.appendingPathExtension("index"),
fileSystem: fileSystem)
self.header = try indexReader.readHeader()
} else {
let temporaryCheckpointBase = temporaryDirectory.appendingPathComponent(checkpointBase)
self.localCheckpointLocation = temporaryCheckpointBase
let localIndexFileLocation = temporaryCheckpointBase.appendingPathExtension("index")
if FileManager.default.fileExists(atPath: localIndexFileLocation.path) {
indexReader = try CheckpointIndexReader(file: localIndexFileLocation,
fileSystem: fileSystem)
self.header = try indexReader.readHeader()
} else {
// The index file contains the number of shards, so obtain that first.
try CheckpointReader.downloadIndexFile(
from: finalCheckpointLocation, to: temporaryDirectory)
indexReader = try CheckpointIndexReader(file: localIndexFileLocation,
fileSystem: fileSystem)
self.header = try indexReader.readHeader()
try CheckpointReader.downloadCheckpointFiles(
from: finalCheckpointLocation, to: temporaryDirectory,
shards: Int(self.header.numShards), additionalFiles: additionalFiles)
}
}
self.metadata = try indexReader.readAllKeysAndValues()
}
/// Downloads an archive file, if necessary, and then extracts it and finds the name of the
/// index file. The returned URL contains the path and the base name for the checkpoint.
static func downloadAndExtractArchive(from checkpointLocation: URL, to temporaryDirectory: URL)
throws -> URL
{
func findCheckpointBase(in directory: URL) throws -> URL? {
guard
let directoryEnumerator = FileManager.default.enumerator(
at: directory, includingPropertiesForKeys: [.isDirectoryKey],
options: .skipsHiddenFiles)
else {
return nil
}
for case let location as URL in directoryEnumerator {
let resourceValues = try location.resourceValues(forKeys: [.isDirectoryKey])
if !(resourceValues.isDirectory ?? false) && location.path.hasSuffix(".index") {
return URL(
fileURLWithPath: String(location.path.prefix(location.path.count - 6)))
}
}
return nil
}
if let checkpointBase = try findCheckpointBase(in: temporaryDirectory) {
return checkpointBase
}
let archiveLocation: URL
if checkpointLocation.isFileURL {
archiveLocation = checkpointLocation
try createDirectoryIfMissing(at: temporaryDirectory.path)
} else {
try download(from: checkpointLocation, to: temporaryDirectory)
archiveLocation = temporaryDirectory.appendingPathComponent(
checkpointLocation.lastPathComponent)
}
extractArchive(at: archiveLocation, to: temporaryDirectory, deleteArchiveWhenDone: false)
guard let checkpointBase = try findCheckpointBase(in: temporaryDirectory) else {
fatalError("Unable to find checkpoint index in downloaded archive.")
}
return checkpointBase
}
/// Constructs the file names for checkpoint components from a base URL and downloads them to a
/// target directory.
static func downloadIndexFile(from checkpointLocation: URL, to temporaryDirectory: URL) throws {
let indexFile = checkpointLocation.appendingPathExtension("index")
try download(from: indexFile, to: temporaryDirectory)
}
/// Constructs the file names for checkpoint components from a base URL and downloads them to a
/// target directory.
static func downloadCheckpointFiles(
from checkpointLocation: URL, to temporaryDirectory: URL, shards: Int,
additionalFiles: [String]
) throws {
for shard in 0..<shards {
let shardLocation = self.shardFile(
location: checkpointLocation, shard: shard, totalShards: shards)
try download(from: shardLocation, to: temporaryDirectory)
}
let checkpointDirectory = checkpointLocation.deletingLastPathComponent()
for file in additionalFiles {
let additionalFile = checkpointDirectory.appendingPathComponent(file)
try download(from: additionalFile, to: temporaryDirectory)
}
}
/// Builds the specific file name from a base URL for a given data shard, out of a total number
/// of shards.
static func shardFile(location: URL, shard: Int, totalShards: Int) -> URL {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumIntegerDigits = 5
formatter.maximumFractionDigits = 0
formatter.hasThousandSeparators = false
formatter.usesGroupingSeparator = false
let currentShard = formatter.string(from: shard as NSNumber)!
let totalShards = formatter.string(from: totalShards as NSNumber)!
return location.appendingPathExtension(
"data-\(currentShard)-of-\(totalShards)"
)
}
/// Returns `true` if the checkpoint contains a tensor with the provided name.
public func containsTensor(named name: String) -> Bool {
return metadata[name] != nil
}
/// Returns the shape of the tensor with the provided name stored in the checkpoint.
public func shapeOfTensor(named name: String) -> TensorShape {
guard let bundleEntry = metadata[name] else {
fatalError("No tensor named \(name) exists.")
}
guard bundleEntry.hasShape else {
fatalError("Bundle entry for \(name) is missing a shape parameter.")
}
return TensorShape(bundleEntry.shape.dim.map { Int($0.size) })
}
/// Returns the scalar type of the tensor with the provided name stored in the checkpoint.
public func scalarTypeOfTensor(named name: String) -> Any.Type {
guard let bundleEntry = metadata[name] else {
fatalError("No tensor named \(name) exists.")
}
switch bundleEntry.dtype {
case .dtBool: return Bool.self
case .dtInt8: return Int8.self
case .dtUint8: return UInt8.self
case .dtInt16: return Int16.self
case .dtUint16: return UInt16.self
case .dtInt32: return Int32.self
case .dtUint32: return UInt32.self
case .dtInt64: return Int64.self
case .dtUint64: return UInt64.self
case .dtBfloat16: return BFloat16.self
case .dtFloat: return Float.self
case .dtDouble: return Double.self
case .dtString: return String.self
default: fatalError("Unsupported tensor data type: \(bundleEntry.dtype)")
}
}
/// Loads and returns the value of the tensor with the provided name stored in the checkpoint.
public func loadTensor<Scalar: _TensorFlowDataTypeCompatible>(
named name: String
) -> ShapedArray<Scalar> {
guard let bundleEntry = metadata[name] else {
fatalError("No tensor named \(name) exists.")
}
guard bundleEntry.hasShape else {
fatalError("Bundle entry for \(name) is missing a shape parameter.")
}
let shape = bundleEntry.shape.dim.map { Int($0.size) }
let shard = Int(bundleEntry.shardID)
let shardFile = CheckpointReader.shardFile(
location: localCheckpointLocation, shard: shard, totalShards: Int(header.numShards))
let shardBytes = shardData(for: shardFile)
let tensorData = shardBytes.subdata(
in: Int(bundleEntry.offset)..<Int(bundleEntry.offset + bundleEntry.size))
if isCRCVerificationEnabled {
let readCRC32C = bundleEntry.crc32C
let calculatedCRC32C = tensorData.maskedCRC32C()
guard readCRC32C == calculatedCRC32C else {
fatalError(
"Tensor \(name) had a bad CRC, expected: \(calculatedCRC32C), read: \(readCRC32C)."
)
}
}
let scalarArray = tensorData.withUnsafeBytes { pointer in
Array(pointer.bindMemory(to: Scalar.self))
}
return ShapedArray<Scalar>(shape: shape, scalars: scalarArray)
}
func shardData(for file: URL) -> Data {
if let shardBytes = shardCache[file] {
return shardBytes
} else {
do {
// It is far too slow to read the shards in each time a tensor is accessed, so we
// read the entire shard into an in-memory cache on first access.
let shardFile = fileSystem.open(file.path)
let shardBytes = try shardFile.read()
shardCache[file] = shardBytes
return shardBytes
} catch {
fatalError("Could not read tensor from \(file.path).")
}
}
}
}
extension CheckpointReader {
static func recursivelyObtainTensorNames(
_ current: Any, scope: String? = nil, tensors: inout [String],
separator: String, ignoredTensorPaths: Set<String> = []
) {
CheckpointWriter.recursivelyVisitTensors(
current, scope: scope, separator: separator, ignoredTensorPaths: ignoredTensorPaths
) { child, path in
if child.value is Tensor<Float> {
tensors.append(path)
return false
} else {
return true
}
}
}
}
extension Tensorflow_TensorShapeProto {
var shapeArray: [Int] {
return self.dim.map { Int($0.size) }
}
}
extension Data {
static var crc32CLookupTable: [UInt32] = {
(0...255).map { index -> UInt32 in
var lookupValue = UInt32(index)
for _ in 0..<8 {
lookupValue =
(lookupValue % 2 == 0) ? (lookupValue >> 1) : (0x82F6_3B78 ^ (lookupValue >> 1))
}
return lookupValue
}
}()
func crc32C() -> UInt32 {
var crc32: UInt32 = 0xFFFF_FFFF
self.withUnsafeBytes { buffer in
let totalBytes = self.count
var index = 0
while index < totalBytes {
let byte = buffer[index]
let lookupIndex = Int((crc32 ^ (UInt32(byte) & 0xFF)) & 0xFF)
crc32 = (crc32 >> 8) ^ Data.crc32CLookupTable[lookupIndex]
index = index &+ 1
}
}
return crc32 ^ 0xFFFF_FFFF
}
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/hash/crc32c.h
func maskedCRC32C() -> UInt32 {
let crc32 = self.crc32C()
let maskDelta: UInt32 = 0xA282_EAD8
return ((crc32 &>> 15) | (crc32 &<< 17)) &+ maskDelta
}
}
extension URL {
var isArchive: Bool {
switch self.pathExtension {
case "gz", "zip", "tar.gz", "tgz": return true
default: return false
}
}
}
|
apache-2.0
|
96c891d9bff160d137ae91f8be8b2f55
| 41.387812 | 107 | 0.644752 | 4.899776 | false | false | false | false |
justinvyu/SwiftyDictionary
|
Pod/Classes/SwiftyDictionary.swift
|
1
|
868
|
//
// SwiftyDictionary.swift
// Pods
//
// Created by Justin Yu on 11/25/15.
//
//
import Foundation
import Alamofire
import AEXML
public enum SwiftyDictionaryType {
case Dictionary
case Thesaurus
}
public typealias DictionaryRequestCallback = (AEXMLDocument) -> Void
public typealias ArrayCallback = ([String]) -> Void
public typealias SeparatedArrayCallback = ([[String]]) -> Void
struct SwiftyDictionaryConstants {
static let API_ROOT_PATH = NSURL(string: "http://www.dictionaryapi.com/api/v1/references/")
static let OBSOLETE = "obsolete"
}
func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
|
mit
|
988924a09f23cfa4b251675fc5a3cb8a
| 22.486486 | 95 | 0.663594 | 3.773913 | false | false | false | false |
ra1028/FloatingActionSheetController
|
FloatingActionSheetController-Demo/FloatingActionSheetController-Demo/AppDelegate.swift
|
1
|
2813
|
//
// AppDelegate.swift
// FloatingActionSheetController-Demo
//
// Created by Ryo Aoyama on 10/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
configure()
return true
}
fileprivate func configure() {
UIApplication.shared.statusBarStyle = .lightContent
let nav = UINavigationController(rootViewController: ViewController())
let navBar = nav.navigationBar
navBar.tintColor = .white
navBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navBar.isTranslucent = false
navBar.shadowImage = UIImage()
navBar.barTintColor = UIColor(red:0.09, green:0.11, blue:0.13, alpha:1)
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = nav
window.makeKeyAndVisible()
self.window = window
}
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:.
}
}
|
mit
|
fd3b7c77d8db32462f58079ed9ba08a1
| 45.866667 | 285 | 0.733997 | 5.513725 | false | false | false | false |
AsyncNinja/AsyncNinja
|
Sources/AsyncNinja/EventSource_Merge2.swift
|
1
|
3571
|
//
// 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
/// Merges channels into one
public func merge<T: EventSource, U: EventSource>(
_ channelA: T,
_ channelB: U,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<T.Update, (T.Success, U.Success)> where T.Update == U.Update {
// Test: EventSource_Merge2Tests.testMergeInts
let bufferSize_ = bufferSize.bufferSize(channelA, channelB)
let producer = Producer<T.Update, (T.Success, U.Success)>(bufferSize: bufferSize_)
let weakProducer = WeakBox(producer)
let locking = makeLocking()
var successA: T.Success?
var successB: U.Success?
func makeHandlerBlock<V>(
_ successHandler: @escaping (V) -> (T.Success, U.Success)?
) -> (
_ event: ChannelEvent<T.Update, V>,
_ originalExecutor: Executor
) -> Void {
return { (event, originalExecutor) in
guard case .some = weakProducer.value else { return }
switch event {
case let .update(update):
weakProducer.value?.update(update, from: originalExecutor)
case let .completion(.failure(error)):
weakProducer.value?.fail(error, from: originalExecutor)
case let .completion(.success(localSuccess)):
locking.lock()
defer { locking.unlock() }
if let success = successHandler(localSuccess) {
weakProducer.value?.succeed(success, from: originalExecutor)
}
}
}
}
let handlerA = channelA.makeHandler(executor: .immediate,
makeHandlerBlock { (success: T.Success) in
successA = success
return successB.map { (success, $0) }
})
producer._asyncNinja_retainHandlerUntilFinalization(handlerA)
let handlerB = channelB.makeHandler(executor: .immediate,
makeHandlerBlock { (success: U.Success) in
successB = success
return successA.map { ($0, success) }
})
producer._asyncNinja_retainHandlerUntilFinalization(handlerB)
cancellationToken?.add(cancellable: producer)
return producer
}
/// Merges array of channels into one
public extension Array where Element: EventSource {
func mergeUpdates(
bufferSize: Int? = nil,
cancellationToken: CancellationToken? = nil
) -> Channel<Element.Update, Void> {
return producer(bufferSize: bufferSize ?? count) { producer in
for ch in self {
ch.bind(producer, cancellationToken: cancellationToken)
}
}
}
}
|
mit
|
444b1bce4aaa53f758e4d7f1a05ef24a
| 36.197917 | 84 | 0.694763 | 4.261337 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Content Display Logic/Controllers/CategoryTableViewController.swift
|
1
|
10958
|
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class CategoryTableViewController: UITableViewController {
/// The samples to display in the table. Searching adjusts this value
var displayedSamples = [Sample]() {
didSet {
guard isViewLoaded else { return }
updateDataSource()
}
}
/// All samples that could be displayed in the table
var allSamples = [Sample]() {
didSet {
displayedSamples = allSamples
}
}
var searchEngine: SampleSearchEngine?
/// Tracks whether or not it is the favorites category.
var isFavoritesCategory = false
/// The dynamic data source.
private var dataSource: UITableViewDiffableDataSource<Int, String>!
private var expandedRowIndexPaths: Set<IndexPath> = []
private var bundleResourceRequest: NSBundleResourceRequest?
private var downloadProgressView: DownloadProgressView?
private var downloadProgressObservation: NSKeyValueObservation?
/// Returns the index path for the given sample.
func indexPath(for sample: Sample) -> IndexPath {
IndexPath(row: displayedSamples.firstIndex(of: sample)!, section: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
// Initialize download progress view.
let downloadProgressView = DownloadProgressView()
downloadProgressView.delegate = self
self.downloadProgressView = downloadProgressView
dataSource = UITableViewDiffableDataSource(tableView: tableView, cellProvider: { [unowned self] tableView, indexPath, _ in
let sample = self.displayedSamples[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ContentTableCell", for: indexPath) as! ContentTableCell
cell.titleLabel.text = sample.name
cell.detailLabel.text = sample.description
cell.isExpanded = expandedRowIndexPaths.contains(indexPath)
return cell
})
updateDataSource()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
selectedSample = nil
if isFavoritesCategory {
displayedSamples = displayedSamples.filter(\.isFavorite)
}
}
// MARK: Sample Selection
/// The currently selected sample.
private(set) var selectedSample: Sample? {
didSet {
guard selectedSample != oldValue else { return }
selectedSampleDidChange()
}
}
/// Responds to the selected sample being changed.
private func selectedSampleDidChange() {
if let sample = selectedSample {
let indexPathForSample = indexPath(for: sample)
if tableView.indexPathForSelectedRow != indexPathForSample {
tableView.selectRow(at: indexPathForSample, animated: true, scrollPosition: .top)
}
if !sample.dependencies.isEmpty {
// Download on demand resources.
let bundleResourceRequest = NSBundleResourceRequest(tags: Set(sample.dependencies))
bundleResourceRequest.loadingPriority = NSBundleResourceRequestLoadingPriorityUrgent
self.bundleResourceRequest = bundleResourceRequest
// Conditionally begin accessing to know if we need to show download progress view or not.
bundleResourceRequest.conditionallyBeginAccessingResources { [weak self] (isResourceAvailable: Bool) in
DispatchQueue.main.async {
// If resource is already available then simply show the sample.
if isResourceAvailable {
self?.showSample(sample)
}
// Else download the resource.
else {
self?.downloadResource(for: sample)
}
}
}
} else {
if let bundleResourceRequest = bundleResourceRequest {
bundleResourceRequest.endAccessingResources()
self.bundleResourceRequest = nil
}
showSample(sample)
}
} else {
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Hide keyboard if visible.
view.endEditing(true)
selectedSample = displayedSamples[indexPath.row]
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
toggleExpansion(at: indexPath)
}
// MARK: - helpers
/// Update the data source if the table has changed.
private func updateDataSource() {
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
snapshot.appendSections([.zero])
let items = displayedSamples
.map(\.name)
snapshot.appendItems(items)
dataSource.apply(snapshot)
}
private func downloadResource(for sample: Sample) {
guard let bundleResourceRequest = bundleResourceRequest else {
return
}
// Show download progress view.
downloadProgressView?.show(withStatus: "Just a moment while we download data for this sample...", progress: 0)
// Add an observer to update the progress in download progress view.
downloadProgressObservation = bundleResourceRequest.progress.observe(\.fractionCompleted) { [weak self] (progress, _) in
DispatchQueue.main.async {
self?.downloadProgressView?.updateProgress(progress: CGFloat(progress.fractionCompleted), animated: true)
}
}
// Begin
bundleResourceRequest.beginAccessingResources { [weak self] (error: Error?) in
DispatchQueue.main.async {
guard let self = self else { return }
// Remove observation.
self.downloadProgressObservation = nil
// Dismiss download progress view.
self.downloadProgressView?.dismiss()
if let error = error {
self.bundleResourceRequest = nil
self.selectedSample = nil
if (error as NSError).code != NSUserCancelledError {
self.presentAlert(message: "Failed to download raster resource :: \(error.localizedDescription)")
}
} else {
if self.bundleResourceRequest?.progress.isCancelled == false {
// Show view controller.
self.showSample(sample)
}
}
}
}
}
private func showSample(_ sample: Sample) {
let storyboard = UIStoryboard(name: sample.storyboardName, bundle: .main)
let controller = storyboard.instantiateInitialViewController()!
controller.title = sample.name
// Must use the presenting controller when opening from search results or else splitViewController will be nil.
let presentingController: UIViewController? = searchEngine != nil ? presentingViewController : self
let navController = UINavigationController(rootViewController: controller)
// Don't use large titles on samples.
controller.navigationItem.largeTitleDisplayMode = .never
// Add the button on the left on the detail view controller.
controller.navigationItem.leftBarButtonItem = presentingController?.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
// Present the sample view controller.
presentingController?.showDetailViewController(navController, sender: self)
// Create and setup the info button.
let sourceCodeBarButtonItem = SourceCodeBarButtonItem()
sourceCodeBarButtonItem.readmeURL = sample.readmeURL
sourceCodeBarButtonItem.navController = navController
// Create and setup the favorite button.
let favoritesBarButtonItem = FavoritesBarButtonItem(sample: sample)
controller.navigationItem.rightBarButtonItems = [sourceCodeBarButtonItem, favoritesBarButtonItem]
}
private func toggleExpansion(at indexPath: IndexPath) {
// If same row selected then hide the detail view.
if expandedRowIndexPaths.contains(indexPath) {
expandedRowIndexPaths.remove(indexPath)
} else {
// Get the two cells and update.
expandedRowIndexPaths.update(with: indexPath)
}
// Reload the corresponding row.
let identifier = dataSource.itemIdentifier(for: indexPath)!
var snapshot = dataSource.snapshot()
snapshot.reloadItems([identifier])
dataSource.apply(snapshot)
}
}
extension CategoryTableViewController: DownloadProgressViewDelegate {
func downloadProgressViewDidCancel(_ downloadProgressView: DownloadProgressView) {
guard let bundleResourceRequest = bundleResourceRequest else {
return
}
bundleResourceRequest.progress.cancel()
self.bundleResourceRequest = nil
self.selectedSample = nil
}
}
extension CategoryTableViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchEngine = searchEngine else {
return
}
// Do not preserve cell expansion when loading new results.
expandedRowIndexPaths.removeAll()
if searchController.isActive,
let query = searchController.searchBar.text?.trimmingCharacters(in: .whitespacesAndNewlines),
!query.isEmpty {
displayedSamples = searchEngine.sortedSamples(matching: query)
} else {
displayedSamples = allSamples
}
}
}
|
apache-2.0
|
957da2206697203af7a8fba78c7a5d96
| 39.435424 | 130 | 0.629494 | 5.961915 | false | false | false | false |
kyouko-taiga/anzen
|
Sources/AST/ASTError.swift
|
1
|
475
|
/// An error associated with an AST node.
public struct ASTError: Error {
public init(cause: Any, node: Node) {
self.cause = cause
self.node = node
}
public let cause: Any
public let node: Node
}
public func < (lhs: ASTError, rhs: ASTError) -> Bool {
let lname = lhs.node.module.id?.qualifiedName ?? ""
let rname = rhs.node.module.id?.qualifiedName ?? ""
return lname == rname
? lhs.node.range.start < rhs.node.range.start
: lname < rname
}
|
apache-2.0
|
7ea0ad30b64b64ae536848bac91847c6
| 22.75 | 54 | 0.650526 | 3.368794 | false | false | false | false |
efeconirulez/be-focus
|
be #focused/Extensions.swift
|
1
|
747
|
//
// Extensions.swift
// be #focused
//
// Created by Efe Helvaci on 19.01.2017.
// Copyright © 2017 efehelvaci. All rights reserved.
//
import UIKit
extension UIView {
func rotateTimes(duration: CFTimeInterval = 0.6, times: Double = 1.0, completionDelegate: AnyObject? = nil) {
let roundTimes = times * 2
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * roundTimes)
rotateAnimation.duration = duration
if let delegate = completionDelegate as? CAAnimationDelegate{
rotateAnimation.delegate = delegate
}
self.layer.add(rotateAnimation, forKey: nil)
}
}
|
apache-2.0
|
3be340f0685a7d9e6bad731c71653507
| 30.083333 | 113 | 0.664879 | 4.312139 | false | false | false | false |
JimmyPeng4iOS/JMCarouselView
|
JMCarouselView/CollectionViewDemo/CollectionTestViewController.swift
|
1
|
3431
|
//
// CollectionTestViewController.swift
// JMCarouselView
//
// Created by JimmyPeng on 15/12/17.
// Copyright © 2015年 Jimmy. All rights reserved.
//
import UIKit
class CollectionTestViewController: UITableViewController
{
var headerView: JMCarouselCollection?
override func viewDidLoad()
{
super.viewDidLoad()
/**
初始化方法1,传入图片URL数组,以及pageControl的当前page点的颜色,特别注意需要SDWebImage框架支持
- parameter frame: frame
- parameter imgURLArray: 图片URL数组
- parameter pagePointColor: pageControl的当前page点的颜色
- parameter stepTime: 广告每一页停留时间
- returns: CollectionView图片轮播器
*/
headerView = JMCarouselCollection(
frame: CGRect(x: 0, y: 0, width:UIScreen.mainScreen().bounds.width, height: 220),
imageURLArray: urlStringArr(),
pagePointColor: UIColor.whiteColor(),
stepTime: 1.0)
/**
初始化方法2,传入图片数组,以及pageControl的当前page点的颜色,无需依赖第三方库
- parameter frame: frame
- parameter imgArray: 图片数组
- parameter pagePointColor: pageControl的当前page点的颜色
- parameter stepTime: 广告每一页停留时间
- returns: CollectionView图片轮播器
*/
// headerView = JMCarouselCollection(
// frame: CGRect(x: 0, y: 0, width:UIScreen.mainScreen().bounds.width, height: 220),
// imageArray: imgArr(),
// pagePointColor: UIColor.whiteColor(),
// stepTime: 2.0)
tableView.tableHeaderView = headerView
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
//获得图片数组
func imgArr() ->[UIImage]
{
var arr = [UIImage]()
for i in 0 ..< 5
{
let img = UIImage(named:"img_0\(i + 1)")
arr.append(img!)
}
return arr
}
//获得图片URL数组
func urlStringArr() ->[String]
{
var arr = [String]()
for i in 0 ..< 5
{
let urlStr = "http://7xpbws.com1.z0.glb.clouddn.com/JMCarouselViewimg_0\(i+1).png"
arr.append(urlStr)
}
return arr
}
//MARK: - 数据源
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 30
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = "CollectionTestViewController \(indexPath.row)"
return cell
}
//MARK:释放
override func viewWillDisappear(animated: Bool)
{
headerView?.stopTimer()
}
deinit
{
print("CollectionVC Deinit")
}
}
|
apache-2.0
|
63971a100c358f8407af0761ddc4ee86
| 25.483333 | 123 | 0.52769 | 5.092949 | false | false | false | false |
mxcl/PromiseKit
|
Tests/A+/2.2.6.swift
|
1
|
13046
|
import PromiseKit
import XCTest
class Test226: XCTestCase {
func test() {
describe("2.2.6: `then` may be called multiple times on the same promise.") {
describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the order of their originating calls to `then`.") {
describe("multiple boring fulfillment handlers") {
testFulfilled(withExpectationCount: 4) { promise, exes, sentinel -> Void in
var orderValidator = 0
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 1)
exes[0].fulfill()
}.silenceWarning()
promise.catch { _ in XCTFail() }
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 2)
exes[1].fulfill()
}.silenceWarning()
promise.catch { _ in XCTFail() }
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 3)
exes[2].fulfill()
}.silenceWarning()
promise.catch { _ in XCTFail() }
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 4)
exes[3].fulfill()
}.silenceWarning()
}
}
describe("multiple fulfillment handlers, one of which throws") {
testFulfilled(withExpectationCount: 4) { promise, exes, sentinel in
var orderValidator = 0
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 1)
exes[0].fulfill()
}.silenceWarning()
promise.catch { _ in XCTFail() }
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 2)
exes[1].fulfill()
}.silenceWarning()
promise.catch { _ in XCTFail() }
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 3)
exes[2].fulfill()
throw Error.dummy
}.silenceWarning()
promise.catch { value in XCTFail() }
promise.done {
XCTAssertEqual($0, sentinel)
XCTAssertEqual(++orderValidator, 4)
exes[3].fulfill()
}.silenceWarning()
}
}
describe("results in multiple branching chains with their own fulfillment values") {
testFulfilled(withExpectationCount: 3) { promise, exes, memo in
let sentinel1 = 671
let sentinel2: UInt32 = 672
let sentinel3 = 673
promise.map { _ in
return sentinel1
}.done { value in
XCTAssertEqual(sentinel1, value)
exes[0].fulfill()
}.silenceWarning()
promise.done { _ in
throw Error.sentinel(sentinel2)
}.catch { err in
switch err {
case Error.sentinel(let err) where err == sentinel2:
break
default:
XCTFail()
}
exes[1].fulfill()
}
promise.map { _ in
sentinel3
}.done {
XCTAssertEqual($0, sentinel3)
exes[2].fulfill()
}.silenceWarning()
}
}
describe("`onFulfilled` handlers are called in the original order") {
testFulfilled(withExpectationCount: 3) { promise, exes, memo in
var orderValidator = 0
promise.done { _ in
XCTAssertEqual(++orderValidator, 1)
exes[0].fulfill()
}.silenceWarning()
promise.done { _ in
XCTAssertEqual(++orderValidator, 2)
exes[1].fulfill()
}.silenceWarning()
promise.done { _ in
XCTAssertEqual(++orderValidator, 3)
exes[2].fulfill()
}.silenceWarning()
}
}
describe("even when one handler is added inside another handler") {
testFulfilled(withExpectationCount: 3) { promise, exes, memo in
var x = 0
promise.done { _ in
XCTAssertEqual(x, 0)
x += 1
exes[0].fulfill()
promise.done { _ in
XCTAssertEqual(x, 2)
x += 1
exes[1].fulfill()
}.silenceWarning()
}.silenceWarning()
promise.done { _ in
XCTAssertEqual(x, 1)
x += 1
exes[2].fulfill()
}.silenceWarning()
}
}
}
describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the order of their originating calls to `then`.") {
describe("multiple boring rejection handlers") {
testRejected(withExpectationCount: 4) { promise, exes, sentinel in
var ticket = 0
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++ticket, 1)
exes[0].fulfill()
}
promise.done { _ in XCTFail() }.silenceWarning()
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++ticket, 2)
exes[1].fulfill()
}
promise.done { _ in XCTFail() }.silenceWarning()
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++ticket, 3)
exes[2].fulfill()
}
promise.done { _ in XCTFail() }.silenceWarning()
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++ticket, 4)
exes[3].fulfill()
}
}
}
describe("multiple rejection handlers, one of which throws") {
testRejected(withExpectationCount: 4) { promise, exes, sentinel in
var orderValidator = 0
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++orderValidator, 1)
exes[0].fulfill()
}
promise.done { _ in XCTFail() }.silenceWarning()
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++orderValidator, 2)
exes[1].fulfill()
}
promise.done { _ in XCTFail() }.silenceWarning()
promise.recover { err -> Promise<UInt32> in
if case Error.sentinel(let x) = err {
XCTAssertEqual(x, sentinel)
} else {
XCTFail()
}
XCTAssertEqual(++orderValidator, 3)
exes[2].fulfill()
throw Error.dummy
}.silenceWarning()
promise.done { _ in XCTFail() }.silenceWarning()
promise.catch { err in
guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() }
XCTAssertEqual(++orderValidator, 4)
exes[3].fulfill()
}
}
}
describe("results in multiple branching chains with their own fulfillment values") {
testRejected(withExpectationCount: 3) { promise, exes, memo in
let sentinel1 = arc4random()
let sentinel2 = arc4random()
let sentinel3 = arc4random()
promise.recover { _ in
return .value(sentinel1)
}.done { value in
XCTAssertEqual(sentinel1, value)
exes[0].fulfill()
}
promise.recover { _ -> Promise<UInt32> in
throw Error.sentinel(sentinel2)
}.catch { err in
if case Error.sentinel(let x) = err, x == sentinel2 {
exes[1].fulfill()
}
}
promise.recover { _ in
.value(sentinel3)
}.done { value in
XCTAssertEqual(value, sentinel3)
exes[2].fulfill()
}
}
}
describe("`onRejected` handlers are called in the original order") {
testRejected(withExpectationCount: 3) { promise, exes, memo in
var x = 0
promise.catch { _ in
XCTAssertEqual(x, 0)
x += 1
exes[0].fulfill()
}
promise.catch { _ in
XCTAssertEqual(x, 1)
x += 1
exes[1].fulfill()
}
promise.catch { _ in
XCTAssertEqual(x, 2)
x += 1
exes[2].fulfill()
}
}
}
describe("even when one handler is added inside another handler") {
testRejected(withExpectationCount: 3) { promise, exes, memo in
var x = 0
promise.catch { _ in
XCTAssertEqual(x, 0)
x += 1
exes[0].fulfill()
promise.catch { _ in
XCTAssertEqual(x, 2)
x += 1
exes[1].fulfill()
}
}
promise.catch { _ in
XCTAssertEqual(x, 1)
x += 1
exes[2].fulfill()
}
}
}
}
}
}
}
|
mit
|
380e5204e9655d74f41af1573c8b986c
| 46.44 | 169 | 0.369462 | 6.468022 | false | true | false | false |
ja-mes/experiments
|
iOS/rainyshinycloudy/rainyshinycloudy/CurrentWeather.swift
|
1
|
2529
|
//
// CurrentWeather.swift
// rainyshinycloudy
//
// Created by James Brown on 8/20/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import Alamofire
class CurrentWeather {
var _cityName: String!
var _date: String!
var _weatherType: String!
var _currentTemp: Double!
var cityName: String {
if _cityName == nil {
_cityName = ""
}
return _cityName
}
var date: String {
if _date == nil {
_date = ""
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: Date())
self._date = "Today, \(currentDate)"
return _date
}
var weatherType: String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var currentTemp: Double {
if _currentTemp == nil {
_currentTemp = 0.0
}
return _currentTemp
}
func downloadWeatherDetails(completed: DownloadComplete) {
Alamofire.request(CURRENT_WEATHER_URL, withMethod: .get).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let name = dict["name"] as? String {
self._cityName = name.capitalized
print(self._cityName)
}
if let weather = dict["weather"] as? [Dictionary<String, AnyObject>] {
if let main = weather[0]["main"] as? String {
self._weatherType = main.capitalized
print(self._weatherType)
}
}
if let main = dict["main"] as? Dictionary<String, AnyObject> {
if let currentTemperature = main["temp"] as? Double {
let kelvinToFarenheitPreDivision = (currentTemperature * (9/5) - 459.67)
let kelvinToFarenheit = Double(round(10 * kelvinToFarenheitPreDivision / 10))
self._currentTemp = kelvinToFarenheit
print(self._currentTemp)
}
}
}
completed()
}
}
}
|
mit
|
8fe99e701823049a7cf8f00707f4cc4f
| 24.28 | 101 | 0.486551 | 5.255717 | false | false | false | false |
treejames/firefox-ios
|
Client/Frontend/Widgets/AutocompleteTextField.swift
|
6
|
8715
|
/* 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/. */
// This code is loosely based on https://github.com/Antol/APAutocompleteTextField
import UIKit
import Shared
/// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate,
/// callers must use this instead.
protocol AutocompleteTextFieldDelegate: class {
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String)
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField)
}
private struct AutocompleteTextFieldUX {
static let HighlightColor = UIColor(rgb: 0xccdded)
}
class AutocompleteTextField: UITextField, UITextFieldDelegate {
var autocompleteDelegate: AutocompleteTextFieldDelegate?
private var completionActive = false
private var canAutocomplete = true
private var enteredText = ""
private var previousSuggestion = ""
private var notifyTextChanged: (() -> ())? = nil
override var text: String! {
didSet {
// SELtextDidChange is not called when directly setting the text property, so fire it manually.
SELtextDidChange(self)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
super.delegate = self
super.addTarget(self, action: "SELtextDidChange:", forControlEvents: UIControlEvents.EditingChanged)
notifyTextChanged = debounce(0.1, {
if self.editing {
self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.enteredText)
}
})
}
func highlightAll() {
if !text.isEmpty {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(0, count(text)))
attributedText = attributedString
enteredText = ""
completionActive = true
}
selectedTextRange = textRangeFromPosition(beginningOfDocument, toPosition: beginningOfDocument)
}
/// Commits the completion by setting the text and removing the highlight.
private func applyCompletion() {
if completionActive {
self.attributedText = NSAttributedString(string: text)
enteredText = text
completionActive = false
previousSuggestion = ""
// This is required to notify the SearchLoader that some text has changed and previous
// cached query will get updated.
notifyTextChanged?()
}
}
/// Removes the autocomplete-highlighted text from the field.
private func removeCompletion() {
if completionActive {
// Workaround for stuck highlight bug.
if count(enteredText) == 0 {
attributedText = NSAttributedString(string: " ")
}
attributedText = NSAttributedString(string: enteredText)
completionActive = false
}
}
// `shouldChangeCharactersInRange` is called before the text changes, and SELtextDidChange is called after.
// Since the text has changed, remove the completion here, and SELtextDidChange will fire the callback to
// get the new autocompletion.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Accept autocompletions if we're adding characters.
canAutocomplete = !string.isEmpty
if completionActive {
if string.isEmpty {
// Characters are being deleted, so clear the autocompletion, but don't change the text.
removeCompletion()
return false
}
removeCompletionIfRequiredForEnteredString(string)
}
return true
}
private func removeCompletionIfRequiredForEnteredString(string: String) {
// If user-entered text does not start with previous suggestion then remove the completion.
let actualEnteredString = enteredText + string
if !previousSuggestion.startsWith(actualEnteredString) {
removeCompletion()
}
enteredText = actualEnteredString
}
func setAutocompleteSuggestion(suggestion: String?) {
// Setting the autocomplete suggestion during multi-stage input will break the session since the text
// is not fully entered. If `markedTextRange` is nil, that means the multi-stage input is complete, so
// it's safe to append the suggestion.
if let suggestion = suggestion where editing && canAutocomplete && markedTextRange == nil {
// Check that the length of the entered text is shorter than the length of the suggestion.
// This ensures that completionActive is true only if there are remaining characters to
// suggest (which will suppress the caret).
if suggestion.startsWith(enteredText) && count(enteredText) < count(suggestion) {
let endingString = suggestion.substringFromIndex(advance(suggestion.startIndex, count(enteredText)))
let completedAndMarkedString = NSMutableAttributedString(string: suggestion)
completedAndMarkedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(count(enteredText), count(endingString)))
attributedText = completedAndMarkedString
completionActive = true
previousSuggestion = suggestion
return
}
}
removeCompletion()
}
func textFieldDidBeginEditing(textField: UITextField) {
autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self)
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
applyCompletion()
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true
}
func textFieldShouldClear(textField: UITextField) -> Bool {
removeCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true
}
override func setMarkedText(markedText: String!, selectedRange: NSRange) {
// Clear the autocompletion if any provisionally inserted text has been
// entered (e.g., a partial composition from a Japanese keyboard).
removeCompletion()
super.setMarkedText(markedText, selectedRange: selectedRange)
}
func SELtextDidChange(textField: UITextField) {
if completionActive {
// Immediately reuse the previous suggestion if it's still valid.
setAutocompleteSuggestion(previousSuggestion)
} else {
// Updates entered text while completion is not active. If it is
// active, enteredText will already be updated from
// removeCompletionIfRequiredForEnteredString.
enteredText = text
}
notifyTextChanged?()
}
override func deleteBackward() {
removeCompletion()
super.deleteBackward()
}
override func caretRectForPosition(position: UITextPosition!) -> CGRect {
return completionActive ? CGRectZero : super.caretRectForPosition(position)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesBegan(touches, withEvent: event)
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesMoved(touches, withEvent: event)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if !completionActive {
super.touchesEnded(touches, withEvent: event)
} else {
applyCompletion()
// Set the current position to the end of the text.
selectedTextRange = textRangeFromPosition(endOfDocument, toPosition: endOfDocument)
}
}
}
|
mpl-2.0
|
03007be5fff51f1152ca30f8ba9cf4af
| 39.351852 | 193 | 0.677912 | 5.817757 | false | false | false | false |
remirobert/ProducthuntOSX
|
ProductHunt/ViewController.swift
|
1
|
2546
|
//
// ViewController.swift
// ProductHunt
//
// Created by Remi Robert on 11/06/15.
// Copyright (c) 2015 Remi Robert. All rights reserved.
//
import Foundation
import WebKit
import AppKit
import Cocoa
class ViewController: NSViewController, WKNavigationDelegate {
@IBOutlet var webView: WebView!
@IBOutlet var imageView: NSImageView!
let webUrl = "http://www.producthunt.com"
override func viewDidLoad() {
super.viewDidLoad()
webView.policyDelegate = self
webView.drawsBackground = false
webView.frameLoadDelegate = self
loadWebRequest()
}
func loadWebRequest() {
if let url = NSURL(string: webUrl) {
let request = NSMutableURLRequest(URL: url)
webView.mainFrame.loadRequest(request)
}
}
func webView(sender: WKWebView,
decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if sender == webView {
if let url = navigationAction.request.URL {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
}
override func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!) {
imageView.alphaValue = 0
imageView.hidden = true
}
override func webView(sender: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
listener.use()
}
override func webView(webView: WebView!, decidePolicyForNewWindowAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, newFrameName frameName: String!, decisionListener listener: WebPolicyDecisionListener!) {
if let linkUrl = actionInformation["WebActionOriginalURLKey"]?.absoluteString {
if let url = NSURL(string: linkUrl!) {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
listener.ignore()
}
override func webView(sender: WebView!, resource identifier: AnyObject!, willSendRequest request: NSURLRequest!, redirectResponse: NSURLResponse!, fromDataSource dataSource: WebDataSource!) -> NSURLRequest! {
if let url = request.URL {
return NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: request.timeoutInterval)
}
return nil
}
}
|
mit
|
1591ae7fe6c15c8364f12e37645bbb0e
| 35.371429 | 233 | 0.671642 | 5.382664 | false | false | false | false |
drmohundro/Nimble
|
Nimble/Matchers/BeginWith.swift
|
1
|
1902
|
import Foundation
public func beginWith<S: SequenceType, T: Equatable where S.Generator.Element == T>(startingElement: T) -> MatcherFunc<S> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
var actualGenerator = actualExpression.evaluate().generate()
return actualGenerator.next() == startingElement
}
}
public func beginWith(startingElement: AnyObject) -> MatcherFunc<NMBOrderedCollection?> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
let collection = actualExpression.evaluate()
return collection.hasValue && collection!.indexOfObject(startingElement) == 0
}
}
public func beginWith(startingSubstring: String) -> MatcherFunc<String> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingSubstring)>"
let actual = actualExpression.evaluate()
let range = actual.rangeOfString(startingSubstring)
return range.hasValue && range!.startIndex == actual.startIndex
}
}
extension NMBObjCMatcher {
public class func beginWithMatcher(expected: AnyObject) -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let actual = actualBlock()
if let actualString = actual as? String {
let expr = Expression(expression: ({ actualString }), location: location)
return beginWith(expected as NSString).matches(expr, failureMessage: failureMessage)
} else {
let expr = Expression(expression: ({ actual as? NMBOrderedCollection }), location: location)
return beginWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
|
apache-2.0
|
8b02b8ba08300d26ace943464d9aecf8
| 45.390244 | 123 | 0.693481 | 5.481268 | false | false | false | false |
Kekiiwaa/Localize
|
Source/Localize.swift
|
2
|
4967
|
//
// LocalizeSwift.swift
// Localize
//
// Copyright © 2019 @andresilvagomez.
//
import Foundation
/// Name for language change notification
public let localizeChangeNotification = "LocalizeChangeNotification"
/// Internal current language key
public let localizeStorageKey = "LocalizeDefaultLanguage"
/// Different types to localize your app, using json files or strings default by Apple.
public enum LocalizeType {
/// Custom localize protocol.
case json
/// Default Apple protocol.
case strings
// Custom provider
case custom(provider: LocalizeProtocol)
}
/// Is a pricipal class, contents all logic to localize your keys
/// read json and determinate all configurations.
public class Localize: NSObject {
// MARK: Properties
/// Shared instance
public static let shared: Localize = Localize()
/// Provider to localize your app.
private var provider: LocalizeProtocol = LocalizeStrings()
/// Show all aviable languajes whit criteria name
///
/// - returns: list with storaged languages code
public var availableLanguages: [String] {
return provider.availableLanguages
}
/// Return storaged language or default language in device
///
/// - returns: current used language
public var currentLanguage: String {
return provider.currentLanguage
}
// MARK: Public methods
/// Localize a string using your JSON File
/// If the key is not found return the same key
/// That prevent replace untagged values
///
/// - returns: localized key or same text
public func localize(key: String, tableName: String? = nil) -> String {
return provider.localize(key: key, tableName: tableName)
}
/// Localize a string using your JSON File
/// That replace all % character in your string with replace value.
///
/// - parameter value: The replacement value
///
/// - returns: localized key or same text
public func localize(
key: String,
replace: String,
tableName: String? = nil) -> String {
return provider.localize(key: key, replace: replace, tableName: tableName)
}
/// Localize a string using your JSON File
/// That replace each % character in your string with each replace value.
///
/// - parameter value: The replacement values
///
/// - returns: localized key or same text
public func localize(
key: String,
values: [Any],
tableName: String? = nil) -> String {
return provider.localize(key: key, values: values, tableName: tableName)
}
/// Localize string with dictionary values
/// Get properties in your key with rule :property
/// If property not exist in this string, not is used.
///
/// - parameter value: The replacement dictionary
///
/// - returns: localized key or same text
public func localize(
key: String,
dictionary: [String: String],
tableName: String? = nil) -> String {
return provider.localize(key: key, dictionary: dictionary, tableName: tableName)
}
// MARK: Config methods
/// Update default language, this stores a language key which can be retrieved the next time
public func update(language: String) {
provider.update(language: language)
}
/// Update base file name, searched in path.
public func update(fileName: String) {
provider.update(fileName: fileName)
}
/// Update the bundle used to load files from.
public func update(bundle: Bundle) {
provider.update(bundle: bundle)
}
/// Update default language
public func update(defaultLanguage: String) {
provider.update(defaultLanguage: defaultLanguage)
}
/// This remove the language key storaged.
public func resetLanguage() {
provider.resetLanguage()
}
/// Display name for current user language.
///
/// - return: String form language code in current user language
public func displayNameForLanguage(_ language: String) -> String {
return provider.displayNameForLanguage(language)
}
/// Determines whether a localized string exists for given key
///
/// - parameter key: localization key
/// - returns: boolean value determining whether a localized string exists for give key
public func localizeExists(forKey key: String, table: String? = nil) -> Bool {
guard let table = table else {
return key.localized != key
}
return key.localize(tableName: table) != key
}
// MARK: Config providers
/// Update provider to localize your app.
public func update(provider: LocalizeType) {
switch provider {
case .json:
self.provider = LocalizeJson()
case .strings:
self.provider = LocalizeStrings()
case .custom(let provider):
self.provider = provider
}
}
}
|
mit
|
3fb735a20357d5b51afa9d67bea338c6
| 29.280488 | 96 | 0.652235 | 4.826045 | false | false | false | false |
basheersubei/swift-t
|
stc/bench/dataflow/dataflow-2D.swift
|
4
|
371
|
#include <builtins.swift>
#include <random.swift>
#include "../util/bench.swift"
main {
int M = 3;
int N = 3;
// metadata("hello");
foreach i in [0:M-1] {
int A[];
foreach j in [0:N-1] {
int d;
if (j == 0) {
d = 0;
} else {
int r = randint(0, j);
d = A[r];
}
A[j] = set1_integer(d);
}
}
}
|
apache-2.0
|
de6735a0e57520131adb0f10da45d8cb
| 13.269231 | 30 | 0.431267 | 2.708029 | false | false | true | false |
ontouchstart/swift3-playground
|
Learn to Code 2.playgroundbook/Contents/Sources/GridWorld+Diff.swift
|
2
|
1511
|
//
// GridWorld+Diff.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import SceneKit
extension GridWorld {
// MARK: Diff Calculation
/**
Checks for the following:
- All gems in the final world have been removed.
- All switches in the final world are on.
*/
func calculateResults() -> GridWorldResults {
// Collect the results for any neglected gems or closed switches.
var missedActions = [DiffResult]()
//--- Search the world for gems that were not collected.
let gems = existingGems(at: allPossibleCoordinates)
for gem in gems {
let result = DiffResult(coordinate: gem.coordinate, type: .failedToPickUpGoal)
missedActions.append(result)
}
let pickupCount = commandQueue.collectedGemCount()
//--- Check on/off state for all switches in the current world
var openSwitchCount = 0
for switchNode in existingNodes(ofType: Switch.self, at: allPossibleCoordinates) {
if switchNode.isOn {
openSwitchCount += 1
}
else {
let result = DiffResult(coordinate: switchNode.coordinate, type: .incorrectSwitchState)
missedActions.append(result)
}
}
return GridWorldResults(criteria: successCriteria, missedActions: missedActions, collectedGems: pickupCount, openSwitches: openSwitchCount)
}
}
|
mit
|
0c1221584511513979c61abd8f352bd9
| 33.340909 | 147 | 0.614163 | 4.889968 | false | false | false | false |
mrdepth/EVEOnlineAPI
|
EVEAPI/EVEAPI/EVETitles.swift
|
1
|
3200
|
//
// EVETitles.swift
// EVEAPI
//
// Created by Artem Shimanski on 30.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVETitlesItem: EVEObject {
public var titleID: Int = 0
public var titleName: String = ""
public var roles: [EVETitlesRoleItem] = []
public var grantableRoles: [EVETitlesRoleItem] = []
public var rolesAtHQ: [EVETitlesRoleItem] = []
public var grantableRolesAtHQ: [EVETitlesRoleItem] = []
public var rolesAtBase: [EVETitlesRoleItem] = []
public var grantableRolesAtBase: [EVETitlesRoleItem] = []
public var rolesAtOther: [EVETitlesRoleItem] = []
public var grantableRolesAtOther: [EVETitlesRoleItem] = []
public override init() {
super.init()
}
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"titleID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"titleName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"roles":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"grantableRoles":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"rolesAtHQ":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"grantableRolesAtHQ":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"rolesAtBase":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"grantableRolesAtBase":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"rolesAtOther":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
"grantableRolesAtOther":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesRoleItem.self, transformer: nil),
]
}
}
public class EVETitlesRoleItem: EVEObject {
public var roleID: Int64 = 0
public var roleName: String = ""
public var roleDescription: String = ""
public override init() {
super.init()
}
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"roleID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"roleName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"roleDescription":EVESchemeElementType.String(elementName:nil, transformer:nil),
]
}
}
public class EVETitles: EVEResult {
public var titles: [EVETitlesItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"titles":EVESchemeElementType.Rowset(elementName: nil, type: EVETitlesItem.self, transformer: nil),
]
}
}
|
mit
|
99a26656adcfa57e582b9509e37518ea
| 32.673684 | 120 | 0.751172 | 3.594382 | false | false | false | false |
PjGeeroms/IOSRecipeDB
|
Pods/SearchTextField/SearchTextField/Classes/SearchTextField.swift
|
1
|
18597
|
//
// SearchTextField.swift
// SearchTextField
//
// Created by Alejandro Pasccon on 4/20/16.
// Copyright © 2016 Alejandro Pasccon. All rights reserved.
//
import UIKit
open class SearchTextField: UITextField {
////////////////////////////////////////////////////////////////////////
// Public interface
/// Maximum number of results to be shown in the suggestions list
open var maxNumberOfResults = 0
/// Maximum height of the results list
open var maxResultsListHeight = 0
/// Indicate if this field has been interacted with yet
open var interactedWith = false
/// Set your custom visual theme, or just choose between pre-defined SearchTextFieldTheme.lightTheme() and SearchTextFieldTheme.darkTheme() themes
open var theme = SearchTextFieldTheme.lightTheme() {
didSet {
tableView?.reloadData()
}
}
/// Show the suggestions list without filter when the text field is focused
open var startVisible = false
/// Set an array of SearchTextFieldItem's to be used for suggestions
open func filterItems(_ items: [SearchTextFieldItem]) {
filterDataSource = items
}
/// Set an array of strings to be used for suggestions
open func filterStrings(_ strings: [String]) {
var items = [SearchTextFieldItem]()
for value in strings {
items.append(SearchTextFieldItem(title: value))
}
filterDataSource = items
}
/// Closure to handle when the user pick an item
open var itemSelectionHandler: SearchTextFieldItemHandler?
/// Closure to handle when the user stops typing
open var userStoppedTypingHandler: ((Void) -> Void)?
/// Set your custom set of attributes in order to highlight the string found in each item
open var highlightAttributes: [String: AnyObject] = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 10)]
open func showLoadingIndicator() {
self.rightViewMode = .always
indicator.startAnimating()
}
open func stopLoadingIndicator() {
self.rightViewMode = .never
indicator.stopAnimating()
}
open var inlineMode = false
////////////////////////////////////////////////////////////////////////
// Private implementation
fileprivate var tableView: UITableView?
fileprivate var shadowView: UIView?
fileprivate var direction: Direction = .down
fileprivate var fontConversionRate: CGFloat = 0.7
fileprivate var keyboardFrame: CGRect?
fileprivate var timer: Timer? = nil
fileprivate var placeholderLabel: UILabel?
fileprivate static let cellIdentifier = "APSearchTextFieldCell"
fileprivate let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
fileprivate var filteredResults = [SearchTextFieldItem]()
fileprivate var filterDataSource = [SearchTextFieldItem]() {
didSet {
filter(false)
redrawSearchTableView()
}
}
fileprivate var currentInlineItem = ""
override open func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
self.addTarget(self, action: #selector(SearchTextField.textFieldDidChange), for: .editingChanged)
self.addTarget(self, action: #selector(SearchTextField.textFieldDidBeginEditing), for: .editingDidBegin)
self.addTarget(self, action: #selector(SearchTextField.textFieldDidEndEditing), for: .editingDidEnd)
self.addTarget(self, action: #selector(SearchTextField.textFieldDidEndEditingOnExit), for: .editingDidEndOnExit)
NotificationCenter.default.addObserver(self, selector: #selector(SearchTextField.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SearchTextField.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override open func layoutSubviews() {
super.layoutSubviews()
buildSearchTableView()
buildPlaceholderLabel()
// Create the loading indicator
indicator.hidesWhenStopped = true
self.rightView = indicator
}
override open func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var rightFrame = super.rightViewRect(forBounds: bounds)
rightFrame.origin.x -= 5
return rightFrame
}
// Create the filter table and shadow view
fileprivate func buildSearchTableView() {
if let tableView = tableView, let shadowView = shadowView {
tableView.layer.masksToBounds = true
tableView.layer.borderWidth = 0.5
tableView.dataSource = self
tableView.delegate = self
tableView.separatorInset = UIEdgeInsets.zero
shadowView.backgroundColor = UIColor.lightText
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize.zero
shadowView.layer.shadowOpacity = 1
self.window?.addSubview(tableView)
//self.window?.addSubview(shadowView)
//superview?.addSubview(tableView)
//superview?.addSubview(shadowView)
} else {
tableView = UITableView(frame: CGRect.zero)
shadowView = UIView(frame: CGRect.zero)
}
redrawSearchTableView()
}
fileprivate func buildPlaceholderLabel() {
var textRect = self.textRect(forBounds: self.bounds)
textRect.origin.y -= 1
if let placeholderLabel = placeholderLabel {
placeholderLabel.font = self.font
placeholderLabel.frame = textRect
} else {
placeholderLabel = UILabel(frame: textRect)
placeholderLabel?.font = self.font
placeholderLabel?.textColor = UIColor ( red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0 )
placeholderLabel?.backgroundColor = UIColor.clear
placeholderLabel?.lineBreakMode = .byClipping
self.addSubview(placeholderLabel!)
}
}
// Re-set frames and theme colors
fileprivate func redrawSearchTableView() {
if inlineMode {
tableView?.isHidden = true
return
}
if let tableView = tableView {
let positionGap: CGFloat = 0
if self.direction == .down {
var tableHeight = min((tableView.contentSize.height + positionGap), (UIScreen.main.bounds.size.height - frame.origin.y - theme.cellHeight))
if maxResultsListHeight > 0 {
tableHeight = min(tableHeight, CGFloat(self.maxResultsListHeight))
}
var tableViewFrame = CGRect(x: 0, y: 0, width: frame.size.width - 4, height: tableHeight)
tableViewFrame.origin = self.convert(tableViewFrame.origin, to: nil)
tableViewFrame.origin.x += 2
tableViewFrame.origin.y += frame.size.height + 2
tableView.frame = tableViewFrame
var shadowFrame = CGRect(x: 0, y: 0, width: frame.size.width - 6, height: 1)
shadowFrame.origin = self.convert(shadowFrame.origin, to: nil)
shadowFrame.origin.x += 3
shadowFrame.origin.y = tableView.frame.origin.y
shadowView!.frame = shadowFrame
} else {
let tableHeight = min((tableView.contentSize.height + positionGap), (UIScreen.main.bounds.size.height - frame.origin.y - theme.cellHeight * 2))
tableView.frame = CGRect(x: frame.origin.x + 2, y: (frame.origin.y - tableHeight + positionGap), width: frame.size.width - 4, height: tableHeight)
shadowView!.frame = CGRect(x: frame.origin.x + 3, y: (frame.origin.y + 3), width: frame.size.width - 6, height: 1)
}
superview?.bringSubview(toFront: tableView)
superview?.bringSubview(toFront: shadowView!)
if self.isFirstResponder {
superview?.bringSubview(toFront: self)
}
tableView.layer.borderColor = theme.borderColor.cgColor
tableView.separatorColor = theme.separatorColor
tableView.backgroundColor = theme.bgColor
tableView.reloadData()
}
}
// Handle keyboard events
open func keyboardWillShow(_ notification: Notification) {
keyboardFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
interactedWith = true
if let keyboardFrame = keyboardFrame {
var newFrame = frame
newFrame.size.height += theme.cellHeight
if keyboardFrame.intersects(newFrame) {
direction = .up
} else {
direction = .down
}
redrawSearchTableView()
}
}
open func keyboardWillHide(_ notification: Notification) {
direction = .down
redrawSearchTableView()
}
open func typingDidStop() {
if userStoppedTypingHandler != nil {
self.userStoppedTypingHandler!()
}
}
// Handle text field changes
open func textFieldDidChange() {
// Detect pauses while typing
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.8, target: self, selector: #selector(SearchTextField.typingDidStop), userInfo: self, repeats: false)
if text!.isEmpty {
clearResults()
tableView?.reloadData()
self.placeholderLabel?.text = ""
} else {
filter(false)
}
}
open func textFieldDidBeginEditing() {
if startVisible && text!.isEmpty {
clearResults()
filter(true)
}
placeholderLabel?.attributedText = nil
}
open func textFieldDidEndEditing() {
clearResults()
tableView?.reloadData()
placeholderLabel?.attributedText = nil
}
open func textFieldDidEndEditingOnExit() {
if let title = filteredResults.first?.title {
self.text = title
}
}
fileprivate func filter(_ addAll: Bool) {
clearResults()
for i in 0 ..< filterDataSource.count {
var item = filterDataSource[i]
if !inlineMode {
// Find text in title and subtitle
let titleFilterRange = (item.title as NSString).range(of: text!, options: .caseInsensitive)
let subtitleFilterRange = item.subtitle != nil ? (item.subtitle! as NSString).range(of: text!, options: .caseInsensitive) : NSMakeRange(NSNotFound, 0)
if titleFilterRange.location != NSNotFound || subtitleFilterRange.location != NSNotFound || addAll {
item.attributedTitle = NSMutableAttributedString(string: item.title)
item.attributedSubtitle = NSMutableAttributedString(string: (item.subtitle != nil ? item.subtitle! : ""))
item.attributedTitle!.setAttributes(highlightAttributes, range: titleFilterRange)
if subtitleFilterRange.location != NSNotFound {
item.attributedSubtitle!.setAttributes(highlightAttributesForSubtitle(), range: subtitleFilterRange)
}
filteredResults.append(item)
}
} else {
if item.title.lowercased().hasPrefix(text!.lowercased()) {
item.attributedTitle = NSMutableAttributedString(string: item.title)
item.attributedTitle?.addAttribute(NSForegroundColorAttributeName, value: UIColor.clear, range: NSRange(location:0, length:text!.characters.count))
filteredResults.append(item)
}
}
}
tableView?.reloadData()
if inlineMode {
handleInlineFiltering()
}
}
// Clean filtered results
fileprivate func clearResults() {
filteredResults.removeAll()
}
// Look for Font attribute, and if it exists, adapt to the subtitle font size
fileprivate func highlightAttributesForSubtitle() -> [String: AnyObject] {
var highlightAttributesForSubtitle = [String: AnyObject]()
for attr in highlightAttributes {
if attr.0 == NSFontAttributeName {
let fontName = (attr.1 as! UIFont).fontName
let pointSize = (attr.1 as! UIFont).pointSize * fontConversionRate
highlightAttributesForSubtitle[attr.0] = UIFont(name: fontName, size: pointSize)
} else {
highlightAttributesForSubtitle[attr.0] = attr.1
}
}
return highlightAttributesForSubtitle
}
// Handle inline behaviour
func handleInlineFiltering() {
if let text = self.text {
if text == "" {
self.placeholderLabel?.attributedText = nil
} else {
if let firstResult = filteredResults.first {
self.placeholderLabel?.attributedText = firstResult.attributedTitle
} else {
self.placeholderLabel?.attributedText = nil
}
}
}
}
}
extension SearchTextField: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.isHidden = !interactedWith || (filteredResults.count == 0)
shadowView?.isHidden = !interactedWith || (filteredResults.count == 0)
if maxNumberOfResults > 0 {
return min(filteredResults.count, maxNumberOfResults)
} else {
return filteredResults.count
}
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: SearchTextField.cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: SearchTextField.cellIdentifier)
}
cell!.backgroundColor = UIColor.clear
cell!.layoutMargins = UIEdgeInsets.zero
cell!.preservesSuperviewLayoutMargins = false
cell!.textLabel?.font = theme.font
cell!.detailTextLabel?.font = UIFont(name: theme.font.fontName, size: theme.font.pointSize * fontConversionRate)
cell!.textLabel?.textColor = theme.fontColor
cell!.detailTextLabel?.textColor = theme.fontColor
cell!.textLabel?.text = filteredResults[(indexPath as NSIndexPath).row].title
cell!.detailTextLabel?.text = filteredResults[(indexPath as NSIndexPath).row].subtitle
cell!.textLabel?.attributedText = filteredResults[(indexPath as NSIndexPath).row].attributedTitle
cell!.detailTextLabel?.attributedText = filteredResults[(indexPath as NSIndexPath).row].attributedSubtitle
cell!.imageView?.image = filteredResults[(indexPath as NSIndexPath).row].image
cell!.selectionStyle = .none
return cell!
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return theme.cellHeight
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if itemSelectionHandler == nil {
self.text = filteredResults[(indexPath as NSIndexPath).row].title
} else {
itemSelectionHandler!(filteredResults[(indexPath as NSIndexPath).row])
}
clearResults()
tableView.reloadData()
}
}
////////////////////////////////////////////////////////////////////////
// Search Text Field Theme
public struct SearchTextFieldTheme {
public var cellHeight: CGFloat
public var bgColor: UIColor
public var borderColor: UIColor
public var separatorColor: UIColor
public var font: UIFont
public var fontColor: UIColor
init(cellHeight: CGFloat, bgColor:UIColor, borderColor: UIColor, separatorColor: UIColor, font: UIFont, fontColor: UIColor) {
self.cellHeight = cellHeight
self.borderColor = borderColor
self.separatorColor = separatorColor
self.bgColor = bgColor
self.font = font
self.fontColor = fontColor
}
public static func lightTheme() -> SearchTextFieldTheme {
return SearchTextFieldTheme(cellHeight: 30, bgColor: UIColor (red: 1, green: 1, blue: 1, alpha: 0.6), borderColor: UIColor (red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0), separatorColor: UIColor.clear, font: UIFont.systemFont(ofSize: 10), fontColor: UIColor.black)
}
public static func darkTheme() -> SearchTextFieldTheme {
return SearchTextFieldTheme(cellHeight: 30, bgColor: UIColor (red: 0.8, green: 0.8, blue: 0.8, alpha: 0.6), borderColor: UIColor (red: 0.7, green: 0.7, blue: 0.7, alpha: 1.0), separatorColor: UIColor.clear, font: UIFont.systemFont(ofSize: 10), fontColor: UIColor.white)
}
}
////////////////////////////////////////////////////////////////////////
// Filter Item
public struct SearchTextFieldItem {
// Private vars
fileprivate var attributedTitle: NSMutableAttributedString?
fileprivate var attributedSubtitle: NSMutableAttributedString?
// Public interface
public var title: String
public var subtitle: String?
public var image: UIImage?
public init(title: String, subtitle: String?, image: UIImage?) {
self.title = title
self.subtitle = subtitle
self.image = image
}
public init(title: String, subtitle: String?) {
self.title = title
self.subtitle = subtitle
}
public init(title: String) {
self.title = title
}
}
public typealias SearchTextFieldItemHandler = (_ item: SearchTextFieldItem) -> Void
////////////////////////////////////////////////////////////////////////
// Suggestions List Direction
enum Direction {
case down
case up
}
|
mit
|
80f7efaefdb41fe2d0a1488c77050e63
| 37.342268 | 277 | 0.611798 | 5.450176 | false | false | false | false |
TheDarkCode/Example-Swift-Apps
|
Exercises and Basic Principles/pokedex-exercise/pokedex-exercise/AppDelegate.swift
|
1
|
6119
|
//
// AppDelegate.swift
// pokedex-exercise
//
// Created by Mark Hamilton on 3/12/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.dryverless.pokedex_exercise" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("pokedex_exercise", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
1526df35fd85e54bf822c2db947152d6
| 54.117117 | 291 | 0.720333 | 5.882692 | false | false | false | false |
arnaudbenard/my-npm
|
Pods/Charts/Charts/Classes/Charts/CombinedChartView.swift
|
23
|
6079
|
//
// CombinedChartView.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
import CoreGraphics
/// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area.
public class CombinedChartView: BarLineChartViewBase
{
/// the fill-formatter used for determining the position of the fill-line
internal var _fillFormatter: ChartFillFormatter!
/// enum that allows to specify the order in which the different data objects for the combined-chart are drawn
@objc
public enum CombinedChartDrawOrder: Int
{
case Bar
case Bubble
case Line
case Candle
case Scatter
}
public override func initialize()
{
super.initialize()
_fillFormatter = BarLineChartFillFormatter(chart: self)
renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
override func calcMinMax()
{
super.calcMinMax()
if (self.barData !== nil || self.candleData !== nil || self.bubbleData !== nil)
{
_chartXMin = -0.5
_chartXMax = Double(_data.xVals.count) - 0.5
if (self.bubbleData !== nil)
{
for set in self.bubbleData.dataSets as! [BubbleChartDataSet]
{
let xmin = set.xMin
let xmax = set.xMax
if (xmin < chartXMin)
{
_chartXMin = xmin
}
if (xmax > chartXMax)
{
_chartXMax = xmax
}
}
}
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
}
}
public override var data: ChartData?
{
get
{
return super.data
}
set
{
super.data = newValue
(renderer as! CombinedChartRenderer?)!.createRenderers()
}
}
public var fillFormatter: ChartFillFormatter
{
get
{
return _fillFormatter
}
set
{
_fillFormatter = newValue
if (_fillFormatter === nil)
{
_fillFormatter = BarLineChartFillFormatter(chart: self)
}
}
}
public var lineData: LineChartData!
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).lineData
}
}
public var barData: BarChartData!
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).barData
}
}
public var scatterData: ScatterChartData!
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).scatterData
}
}
public var candleData: CandleChartData!
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).candleData
}
}
public var bubbleData: BubbleChartData!
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).bubbleData
}
}
// MARK: Accessors
/// flag that enables or disables the highlighting arrow
public var drawHighlightArrowEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; }
set { (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled = newValue; }
}
/// if set to true, all values are drawn above their bars, instead of below their top
public var drawValueAboveBarEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; }
set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue; }
}
/// if set to true, a grey area is darawn behind each bar that indicates the maximum value
public var drawBarShadowEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; }
set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue; }
}
/// returns true if drawing the highlighting arrow is enabled, false if not
public var isDrawHighlightArrowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; }
/// returns true if drawing values above bars is enabled, false if not
public var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; }
/// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not
public var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; }
/// the order in which the provided data objects should be drawn.
/// The earlier you place them in the provided array, the further they will be in the background.
/// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines.
public var drawOrder: [Int]
{
get
{
return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue }
}
set
{
(renderer as! CombinedChartRenderer!).drawOrder = newValue.map { CombinedChartDrawOrder(rawValue: $0)! }
}
}
}
|
mit
|
9b35655dfdcdf2b2e3483622904492ec
| 27.952381 | 124 | 0.553709 | 5.422837 | false | false | false | false |
sora0077/qiita-app-infra
|
QiitaInfra/src/Repository/ItemRepository.swift
|
1
|
3242
|
//
// ItemRepository.swift
// QiitaInfra
//
// Created by 林達也 on 2015/11/30.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
import RealmSwift
import QiitaKit
import BrightFutures
import QueryKit
import QiitaDomainInterface
extension QiitaRepositoryImpl {
final class Item: ItemRepository {
private let listCache: NSCache = NSCache()
private let session: QiitaSession
init(session: QiitaSession) {
self.session = session
}
}
}
extension QiitaRepositoryImpl.Item {
func cache(id: String) throws -> ItemProtocol? {
return try realm_sync {
let realm = try GetRealm()
return realm.objects(ItemEntity)(key: id)
}
}
func get(id: String) -> Future<ItemProtocol?, QiitaInfraError> {
func get(_: ItemProtocol? = nil) -> Future<ItemProtocol?, QiitaInfraError> {
return Realm.read(Queue.main.context).map { realm in
realm.objects(ItemEntity)
.filter(ItemEntity.id == id)
.filter(ItemEntity.ttl > ItemEntity.ttlLimit)
.first
}.mapError(QiitaInfraError.RealmError)
}
func fetch() -> Future<ItemProtocol?, QiitaInfraError> {
return session.request(GetItem(id: id))
.mapError(QiitaInfraError.QiitaAPIError)
.flatMap { res in
realm {
let realm = try GetRealm()
let entity = ItemEntity.create(realm, res)
realm.beginWrite()
realm.add(entity, update: true)
try realm.commitWrite()
return entity
}
}
}
return get() ?? fetch().flatMap(get)
}
}
extension QiitaRepositoryImpl.Item {
func create(body: String, title: String, coediting: Bool = false, gist: Bool = false, tweet: Bool = false, `private`: Bool = false, tags: [String]) -> Future<ItemProtocol?, QiitaInfraError> {
return session.request(
CreateItem(
body: body,
coediting: coediting,
gist: gist,
`private`: `private`,
tags: tags.map { Tagging(name: $0) },
title: title,
tweet: tweet
)
)
.mapError(QiitaInfraError.QiitaAPIError)
.flatMap { res in
realm {
let realm = try GetRealm()
let entity = ItemEntity.create(realm, res)
realm.beginWrite()
realm.add(entity, update: true)
try realm.commitWrite()
return entity
}
}
}
func update(item: ItemProtocol, body: String? = nil, title: String? = nil) {
}
}
|
mit
|
1678730c2ff639e4b4b20d684b28ea7d
| 28.66055 | 195 | 0.476956 | 5.352649 | false | false | false | false |
tryolabs/TLSphinx
|
TLSphinx/Config.swift
|
1
|
1465
|
//
// Config.swift
// TLSphinx
//
// Created by Bruno Berisso on 5/29/15.
// Copyright (c) 2015 Bruno Berisso. All rights reserved.
//
import Foundation
import Sphinx.Base
public final class Config {
var cmdLnConf: OpaquePointer?
fileprivate var cArgs: [UnsafeMutablePointer<Int8>?]
public init?(args: (String,String)...) {
// Create [UnsafeMutablePointer<Int8>].
cArgs = args.flatMap { (name, value) -> [UnsafeMutablePointer<Int8>?] in
//strdup move the strings to the heap and return a UnsageMutablePointer<Int8>
return [strdup(name),strdup(value)]
}
cmdLnConf = cmd_ln_parse_r(nil, ps_args(), CInt(cArgs.count), &cArgs, STrue32)
if cmdLnConf == nil {
return nil
}
}
deinit {
for cString in cArgs {
free(cString)
}
cmd_ln_free_r(cmdLnConf)
}
public var showDebugInfo: Bool {
get {
if cmdLnConf != nil {
return cmd_ln_str_r(cmdLnConf, "-logfn") == nil
} else {
return false
}
}
set {
if cmdLnConf != nil {
if newValue {
cmd_ln_set_str_r(cmdLnConf, "-logfn", nil)
} else {
cmd_ln_set_str_r(cmdLnConf, "-logfn", "/dev/null")
}
}
}
}
}
|
mit
|
5d642428645343a6ae3c3c427093e293
| 23.830508 | 89 | 0.493515 | 3.917112 | false | false | false | false |
Noobish1/BrightFutures
|
Sources/BrightFutures/Async.swift
|
2
|
4863
|
//
// Async.swift
// BrightFutures
//
// Created by Thomas Visser on 09/07/15.
// Copyright © 2015 Thomas Visser. All rights reserved.
//
import Foundation
/// Implementation of the `AsyncType` protocol
/// `Async` represents the result of an asynchronous operation
/// and is typically returned from a method that initiates that
/// asynchronous operation.
/// Clients of that method receive the `Async` and can use it
/// to register a callback for when the result of the asynchronous
/// operation comes in.
///
/// This class is often not used directly. Instead, its subclass
/// `Future` is used.
open class Async<Value>: AsyncType {
typealias CompletionCallback = (Value) -> Void
/// The actual result of the operation that the receiver represents or
/// `.None` if the operation is not yet completed.
public fileprivate(set) var result: Value? {
willSet {
assert(result == nil)
}
didSet {
assert(result != nil)
runCallbacks()
}
}
/// This queue is used for all callback related administrative tasks
/// to prevent that a callback is added to a completed future and never
/// executed or perhaps excecuted twice.
fileprivate let queue = DispatchQueue(label: "Internal Async Queue")
/// Upon completion of the future, all callbacks are asynchronously scheduled to their
/// respective execution contexts (which is either given by the client or returned from
/// DefaultThreadingModel). Inside the context, this semaphore will be used
/// to make sure that all callbacks are executed serially.
fileprivate let callbackExecutionSemaphore = DispatchSemaphore(value: 1);
fileprivate var callbacks = [CompletionCallback]()
/// Creates an uncompleted `Async`
public required init() {
}
/// Creates an `Async` that is completed with the given result
public required init(result: Value) {
self.result = result
}
/// Creates an `Async` that will be completed with the given result after the specified delay
public required init(result: Value, delay: DispatchTimeInterval) {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + delay) {
self.complete(result)
}
}
/// Creates an `Async` that is completed when the given other `Async` is completed
public required init<A: AsyncType>(other: A) where A.Value == Value {
completeWith(other)
}
/// Creates an `Async` that can be completed by calling the `result` closure passed to
/// the `resolver`. Example:
///
/// Async { res in
/// Queue.async {
/// // do some work
/// res(42) // complete the async with result '42'
/// }
/// }
///
public required init(resolver: (_ result: @escaping (Value) -> Void) -> Void) {
resolver { val in
self.complete(val)
}
}
private func runCallbacks() {
guard let result = self.result else {
assert(false, "can only run callbacks on a completed future")
return
}
for callback in self.callbacks {
callback(result)
}
self.callbacks.removeAll()
}
/// Adds the given closure as a callback for when the Async completes. The closure is executed on the given context.
/// If no context is given, the behavior is defined by the default threading model (see README.md)
/// Returns self
@discardableResult
open func onComplete(_ context: @escaping ExecutionContext = DefaultThreadingModel(), callback: @escaping (Value) -> Void) -> Self {
let wrappedCallback : (Value) -> Void = { [weak self] value in
let s = self
context {
s?.callbackExecutionSemaphore.context {
callback(value)
}
return
}
}
queue.sync {
if let value = self.result {
wrappedCallback(value)
} else {
self.callbacks.append(wrappedCallback)
}
}
return self
}
}
extension Async: MutableAsyncType {
@discardableResult
func tryComplete(_ value: Value) -> Bool{
return queue.sync {
guard self.result == nil else {
return false
}
self.result = value
return true
}
}
}
extension Async: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "Async<\(Value.self)>(\(String(describing: self.result)))"
}
public var debugDescription: String {
return description
}
}
|
mit
|
07d68abd9ad72ecbb6cc164f52b3f723
| 30.986842 | 136 | 0.601193 | 4.97137 | false | false | false | false |
dasdom/Swiftandpainless
|
SwiftAndPainless_2.playground/Resources/Functions - Basics III.xcplaygroundpage/Contents.swift
|
2
|
515
|
import Foundation
/*:
[⬅️](@previous) [➡️](@next)
# Functions: Basics III
## Returning Tuples
*/
func minMax(numbers: Int...) -> (min: Int, max: Int) {
precondition(numbers.count > 0)
var min = Int.max
var max = Int.min
for number in numbers {
if number <= min {
min = number
}
if number >= max {
max = number
}
}
return (min, max)
}
let result = minMax(23, 3, 42, 5, 666)
let min = result.min
let max = result.max
print("min: \(result.0), max: \(result.1)")
|
mit
|
3e0d7c16995f6bdb4be621012095562c
| 17.814815 | 54 | 0.573964 | 3.188679 | false | false | false | false |
drmohundro/Nimble
|
NimbleTests/Matchers/BeGreaterThanOrEqualToTest.swift
|
1
|
1209
|
import XCTest
import Nimble
class BeGreaterThanOrEqualToTest: XCTestCase {
func testGreaterThanOrEqualTo() {
expect(10).to(beGreaterThanOrEqualTo(10))
expect(10).to(beGreaterThanOrEqualTo(2))
expect(1).toNot(beGreaterThanOrEqualTo(2))
expect(NSNumber.numberWithInt(1)).toNot(beGreaterThanOrEqualTo(2))
expect(NSNumber.numberWithInt(2)).to(beGreaterThanOrEqualTo(NSNumber.numberWithInt(2)))
expect(1).to(beGreaterThanOrEqualTo(NSNumber.numberWithInt(0)))
failsWithErrorMessage("expected <0> to be greater than or equal to <2>") {
expect(0).to(beGreaterThanOrEqualTo(2))
return
}
failsWithErrorMessage("expected <1> to not be greater than or equal to <1>") {
expect(1).toNot(beGreaterThanOrEqualTo(1))
return
}
}
func testGreaterThanOrEqualToOperator() {
expect(0) >= 0
expect(1) >= 0
expect(NSNumber.numberWithInt(1)) >= 1
expect(NSNumber.numberWithInt(1)) >= NSNumber.numberWithInt(1)
failsWithErrorMessage("expected <1> to be greater than or equal to <2>") {
expect(1) >= 2
return
}
}
}
|
apache-2.0
|
b0de07a8a5a86ed85b281b65963634d3
| 33.542857 | 95 | 0.63689 | 4.65 | false | true | false | false |
mortenjust/nocturnal-traffic
|
nocturnal/AppDelegate.swift
|
1
|
6145
|
//
// AppDelegate.swift
// nocturnal
//
// Created by Morten Just Petersen on 1/6/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.mortenjust.nocturnal" 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("nocturnal", 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("nocturnal.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
|
338069a676dff8922925973e4c05ac8c
| 54.36036 | 290 | 0.716843 | 5.748363 | false | false | false | false |
dimakura/SwanKit
|
Tests/SwanKitTests/Tensor/TensorSpec.swift
|
1
|
3861
|
import SSpec
import SwanKit
private func spec_creation() {
describe("Create tensor 5x3") {
var tensor: SWKIntTensor!
before {
tensor = SWKIntTensor(5, 3)
}
it("has size 5x3") {
expect(tensor.size.dimensions).to.eq([5, 3])
}
it("has stride [3, 1]") {
expect(tensor.stride.dimensions).to.eq([3, 1])
}
it("has storage of size 15") {
expect(tensor.storage.size).to.eq(15)
}
it("is contiguous") {
expect(tensor.isContiguous()).to.beTrue
}
it("is not transposed") {
expect(tensor.isTransposed()).to.beFalse
}
}
}
private func spec_subscript() {
describe("Subscript") {
var tensor: SWKIntTensor!
before {
tensor = SWKIntTensor(2, 2)
// 1 3
// 2 4
tensor[0, 0] = 1
tensor[1, 0] = 2
tensor[0, 1] = 3
tensor[1, 1] = 4
}
it("has 1 at (0, 0)") {
expect(tensor[0, 0]).to.eq(1)
}
it("has 2 at (1, 0)") {
expect(tensor[1, 0]).to.eq(2)
}
it("has 3 at (0, 1)") {
expect(tensor[0, 1]).to.eq(3)
}
it("has 4 at (1, 1)") {
expect(tensor[1, 1]).to.eq(4)
}
it("has storage [1, 3, 2, 4]") {
let storage = tensor.storage
expect(storage[0]).to.eq(1)
expect(storage[1]).to.eq(3)
expect(storage[2]).to.eq(2)
expect(storage[3]).to.eq(4)
}
}
}
private func spec_initFrom1DArray() {
describe("init from 1D array") {
let data: [SWKInt] = [1, 2, 3]
var tensor: SWKIntTensor!
before {
tensor = SWKIntTensor(data: data)
}
it("has size \(data.count)") {
expect(tensor.size.dimensions).to.eq([data.count])
}
it("contains all elements from array") {
for (i, value) in data.enumerated() {
expect(tensor[i]).to.eq(value)
}
}
}
}
private func spec_initFrom2DArray() {
describe("init from 2D array") {
let data: [[SWKInt]] = [[1, 2, 3], [4, 5, 6]]
var tensor: SWKIntTensor!
before {
tensor = SWKIntTensor(data: data)
}
it("has size 2x3") {
expect(tensor.size.dimensions).to.eq([2, 3])
}
it("contains all elements from array") {
for (i, arr1) in data.enumerated() {
for (j, value) in arr1.enumerated() {
expect(tensor[i, j]).to.eq(value)
}
}
}
}
}
private func spec_initFrom3DArray() {
describe("init from 3D array") {
let data: [[[SWKInt]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
var tensor: SWKIntTensor!
before {
tensor = SWKIntTensor(data: data)
}
it("has size 2x2x2") {
expect(tensor.size.dimensions).to.eq([2, 2, 2])
}
it("contains all elements from array") {
for (i, arr2) in data.enumerated() {
for (j, arr1) in arr2.enumerated() {
for (k, value) in arr1.enumerated() {
expect(tensor[i, j, k]).to.eq(value)
}
}
}
}
}
}
private func spec_transpose() {
describe("#transpose") {
var tensor: SWKIntTensor!
before {
tensor = SWKIntTensor(data: [[1, 2, 3], [4, 5, 6]])
tensor.transpose()
}
it("has size 3x2") {
expect(tensor.size.dimensions).to.eq([3, 2])
}
it("column[0] is [1, 2, 3]") {
expect(tensor[0, 0]).to.eq(1)
expect(tensor[1, 0]).to.eq(2)
expect(tensor[2, 0]).to.eq(3)
}
it("column[1] is [4, 5, 6]") {
expect(tensor[0, 1]).to.eq(4)
expect(tensor[1, 1]).to.eq(5)
expect(tensor[2, 1]).to.eq(6)
}
it("is not contiguous") {
expect(tensor.isContiguous()).to.beFalse
}
it("is transposed") {
expect(tensor.isTransposed()).to.beTrue
}
}
}
func spec_SWKTensor() {
describe("SWKTensor") {
spec_creation()
spec_subscript()
spec_initFrom1DArray()
spec_initFrom2DArray()
spec_initFrom3DArray()
spec_transpose()
}
}
|
mit
|
701ad48ed5acc7294bec0d55f9f99d6a
| 19.647059 | 65 | 0.534059 | 3.023493 | false | false | false | false |
ra1028/VueFlux
|
Example/Sources/CounterActions.swift
|
1
|
1027
|
import Foundation
import VueFlux
enum CounterAction {
case increment
case decrement
case reset
case openGitHub
case update(interval: TimeInterval)
}
extension Actions where State == CounterState {
func incrementAcync(after interval: TimeInterval = 0) {
DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + interval) {
self.dispatch(action: .increment)
}
}
func decrementAcync(after interval: TimeInterval = 0) {
DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + interval) {
self.dispatch(action: .decrement)
}
}
func resetAcync(after interval: TimeInterval = 0) {
DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + interval) {
self.dispatch(action: .reset)
}
}
func openGitHub() {
dispatch(action: .openGitHub)
}
func update(interval: TimeInterval) {
dispatch(action: .update(interval: interval))
}
}
|
mit
|
6e2d159d0a93b9bd2e681d1fc27fc96b
| 26.026316 | 85 | 0.629017 | 4.370213 | false | false | false | false |
atrick/swift
|
stdlib/public/Distributed/LocalTestingDistributedActorSystem.swift
|
1
|
9927
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import WinSDK
#endif
/// A `DistributedActorSystem` designed for local only testing.
///
/// It will crash on any attempt of remote communication, but can be useful
/// for learning about `distributed actor` isolation, as well as early
/// prototyping stages of development where a real system is not necessary yet.
@available(SwiftStdlib 5.7, *)
public final class LocalTestingDistributedActorSystem: DistributedActorSystem, @unchecked Sendable {
public typealias ActorID = LocalTestingActorAddress
public typealias ResultHandler = LocalTestingInvocationResultHandler
public typealias InvocationEncoder = LocalTestingInvocationEncoder
public typealias InvocationDecoder = LocalTestingInvocationDecoder
public typealias SerializationRequirement = Codable
private var activeActors: [ActorID: any DistributedActor] = [:]
private let activeActorsLock = _Lock()
private var idProvider: ActorIDProvider = ActorIDProvider()
private var assignedIDs: Set<ActorID> = []
private let assignedIDsLock = _Lock()
public init() {}
public func resolve<Act>(id: ActorID, as actorType: Act.Type)
throws -> Act? where Act: DistributedActor {
guard let anyActor = self.activeActorsLock.withLock({ self.activeActors[id] }) else {
throw LocalTestingDistributedActorSystemError(message: "Unable to locate id '\(id)' locally")
}
guard let actor = anyActor as? Act else {
throw LocalTestingDistributedActorSystemError(message: "Failed to resolve id '\(id)' as \(Act.Type.self)")
}
return actor
}
public func assignID<Act>(_ actorType: Act.Type) -> ActorID
where Act: DistributedActor {
let id = self.idProvider.next()
self.assignedIDsLock.withLock {
self.assignedIDs.insert(id)
}
return id
}
public func actorReady<Act>(_ actor: Act)
where Act: DistributedActor,
Act.ID == ActorID {
guard self.assignedIDsLock.withLock({ self.assignedIDs.contains(actor.id) }) else {
fatalError("Attempted to mark an unknown actor '\(actor.id)' ready")
}
self.activeActorsLock.withLock {
self.activeActors[actor.id] = actor
}
}
public func resignID(_ id: ActorID) {
self.activeActorsLock.withLock {
self.activeActors.removeValue(forKey: id)
}
}
public func makeInvocationEncoder() -> InvocationEncoder {
.init()
}
public func remoteCall<Act, Err, Res>(
on actor: Act,
target: RemoteCallTarget,
invocation: inout InvocationEncoder,
throwing errorType: Err.Type,
returning returnType: Res.Type
) async throws -> Res
where Act: DistributedActor,
Act.ID == ActorID,
Err: Error,
Res: SerializationRequirement {
fatalError("Attempted to make remote call to \(target) on actor \(actor) using a local-only actor system")
}
public func remoteCallVoid<Act, Err>(
on actor: Act,
target: RemoteCallTarget,
invocation: inout InvocationEncoder,
throwing errorType: Err.Type
) async throws
where Act: DistributedActor,
Act.ID == ActorID,
Err: Error {
fatalError("Attempted to make remote call to \(target) on actor \(actor) using a local-only actor system")
}
private struct ActorIDProvider {
private var counter: Int = 0
private let counterLock = _Lock()
init() {}
mutating func next() -> LocalTestingActorAddress {
let id: Int = self.counterLock.withLock {
self.counter += 1
return self.counter
}
return LocalTestingActorAddress(parse: "\(id)")
}
}
}
@available(SwiftStdlib 5.7, *)
public struct LocalTestingActorAddress: Hashable, Sendable, Codable {
public let address: String
public init(parse address: String) {
self.address = address
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.address = try container.decode(String.self)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.address)
}
}
@available(SwiftStdlib 5.7, *)
public struct LocalTestingInvocationEncoder: DistributedTargetInvocationEncoder {
public typealias SerializationRequirement = Codable
public mutating func recordGenericSubstitution<T>(_ type: T.Type) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func recordArgument<Value: SerializationRequirement>(_ argument: RemoteCallArgument<Value>) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func recordErrorType<E: Error>(_ type: E.Type) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func recordReturnType<R: SerializationRequirement>(_ type: R.Type) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func doneRecording() throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
}
@available(SwiftStdlib 5.7, *)
public final class LocalTestingInvocationDecoder: DistributedTargetInvocationDecoder {
public typealias SerializationRequirement = Codable
public func decodeGenericSubstitutions() throws -> [Any.Type] {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func decodeNextArgument<Argument: SerializationRequirement>() throws -> Argument {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func decodeErrorType() throws -> Any.Type? {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func decodeReturnType() throws -> Any.Type? {
fatalError("Attempted to call decoder method in a local-only actor system")
}
}
@available(SwiftStdlib 5.7, *)
public struct LocalTestingInvocationResultHandler: DistributedTargetInvocationResultHandler {
public typealias SerializationRequirement = Codable
public func onReturn<Success: SerializationRequirement>(value: Success) async throws {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func onReturnVoid() async throws {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func onThrow<Err: Error>(error: Err) async throws {
fatalError("Attempted to call decoder method in a local-only actor system")
}
}
// === errors ----------------------------------------------------------------
@available(SwiftStdlib 5.7, *)
public struct LocalTestingDistributedActorSystemError: DistributedActorSystemError {
public let message: String
public init(message: String) {
self.message = message
}
}
// === lock ----------------------------------------------------------------
@available(SwiftStdlib 5.7, *)
fileprivate class _Lock {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
private let underlying: UnsafeMutablePointer<os_unfair_lock>
#elseif os(Windows)
private let underlying: UnsafeMutablePointer<SRWLOCK>
#elseif os(WASI)
// pthread is currently not available on WASI
#elseif os(Cygwin) || os(FreeBSD) || os(OpenBSD)
private let underlying: UnsafeMutablePointer<pthread_mutex_t?>
#else
private let underlying: UnsafeMutablePointer<pthread_mutex_t>
#endif
deinit {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
// `os_unfair_lock`s do not need to be explicitly destroyed
#elseif os(Windows)
// `SRWLOCK`s do not need to be explicitly destroyed
#elseif os(WASI)
// WASI environment has only a single thread
#else
guard pthread_mutex_destroy(self.underlying) == 0 else {
fatalError("pthread_mutex_destroy failed")
}
#endif
#if !os(WASI)
self.underlying.deinitialize(count: 1)
self.underlying.deallocate()
#endif
}
init() {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
self.underlying = UnsafeMutablePointer.allocate(capacity: 1)
#elseif os(Windows)
self.underlying = UnsafeMutablePointer.allocate(capacity: 1)
InitializeSRWLock(self.underlying)
#elseif os(WASI)
// WASI environment has only a single thread
#else
self.underlying = UnsafeMutablePointer.allocate(capacity: 1)
guard pthread_mutex_init(self.underlying, nil) == 0 else {
fatalError("pthread_mutex_init failed")
}
#endif
}
@discardableResult
func withLock<T>(_ body: () -> T) -> T {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
os_unfair_lock_lock(self.underlying)
#elseif os(Windows)
AcquireSRWLockExclusive(self.underlying)
#elseif os(WASI)
// WASI environment has only a single thread
#else
guard pthread_mutex_lock(self.underlying) == 0 else {
fatalError("pthread_mutex_lock failed")
}
#endif
defer {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
os_unfair_lock_unlock(self.underlying)
#elseif os(Windows)
ReleaseSRWLockExclusive(self.underlying)
#elseif os(WASI)
// WASI environment has only a single thread
#else
guard pthread_mutex_unlock(self.underlying) == 0 else {
fatalError("pthread_mutex_unlock failed")
}
#endif
}
return body()
}
}
|
apache-2.0
|
c6b72cde4dd85cd864e7892145939846
| 31.980066 | 118 | 0.688828 | 4.35777 | false | false | false | false |
Corey2121/the-oakland-post
|
The Oakland Post/Valid.swift
|
3
|
2001
|
//
// Valid.swift
// The Oakland Post
//
// User input validation to be called before registering a new user. Not meant to be comprehensive,
// just meant to catch common mistakes.
//
// Created by Andrew Clissold on 8/27/14.
// Copyright (c) 2014 Andrew Clissold. All rights reserved.
//
func valid(user: PFUser, confirmPassword: String) -> Bool {
if count(user.username!) < 6 {
return error("Your username must be at least six characters. Please choose a new one and try again.")
}
if user.username!.containsWhitespace {
return error("Usernames cannot contain spaces. Please choose a new one and try again.")
}
if count(user.password!) < 6 {
return error("Your password must be at least six characters. Please choose a new one and try again.")
}
if user.password!.containsWhitespace {
return error("Passwords cannot contain spaces. Please choose a new one and try again.")
}
if user.password! != confirmPassword {
return error("Your passwords must match. Please retype them and try again.")
}
if !validEmail(user.email!) {
return error("Your email address appears to be invalid. Please correct any typos and try again.")
}
return true
}
private extension NSString {
var containsWhitespace: Bool {
let range = NSMakeRange(0, self.length)
let whitespaceRange = self.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet(),
options: .RegularExpressionSearch, range: range)
return whitespaceRange.location != NSNotFound
}
}
private func validEmail(email: String) -> Bool {
let regex = "[^\\s]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluateWithObject(email)
}
private func error(message: String) -> Bool {
UIAlertView(title: "Error",
message: message,
delegate: nil,
cancelButtonTitle: "OK").show()
return false
}
|
bsd-3-clause
|
c3470813a0165beffd4c3e2857d447c6
| 34.732143 | 109 | 0.671664 | 4.266525 | false | false | false | false |
austinzheng/swift
|
test/decl/protocol/special/Error.swift
|
53
|
1268
|
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/Error_other.swift
enum ClericalErrorDomain: Error {
case MisplacedDocument(name: String)
case AccidentallyErasedTape(fromMinute: Double, toMinute: Double)
}
let error
= ClericalErrorDomain.AccidentallyErasedTape(fromMinute: 5, toMinute: 23.5)
let domain: String = error._domain
let code: Int = error._code
struct UseEnumBeforeDeclaration {
let errorDomain: String = EnumToUseBeforeDeclaration.A._domain
let errorCode: Int = EnumToUseBeforeDeclaration.A._code
}
enum EnumToUseBeforeDeclaration: Error {
case A
}
let domainFromOtherFile: String = FromOtherFile.A._domain
let codeFromOtherFile: Int = AlsoFromOtherFile.A._code
enum NotAnError { case A }
let notAnErrorDomain: String = NotAnError.A._domain // expected-error{{value of type 'NotAnError' has no member '_domain'}}
let notAnErrorCode: Int = NotAnError.A._code // expected-error{{value of type 'NotAnError' has no member '_code'}}
enum EmptyErrorDomain: Error {}
struct ErrorStruct : Error {
}
class ErrorClass : Error {
}
struct ErrorStruct2 { }
extension ErrorStruct2 : Error { }
class ErrorClass2 { }
extension ErrorClass2 : Error { }
|
apache-2.0
|
dc2c5a7c2354cf364469c789dfaf0b87
| 26.565217 | 123 | 0.753155 | 3.541899 | false | false | false | false |
RevenueCat/purchases-ios
|
Sources/LocalReceiptParsing/Builders/ASN1ContainerBuilder.swift
|
1
|
6104
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ASN1ContainerBuilder.swift
//
// Created by Andrés Boedo on 7/29/20.
//
import Foundation
class ASN1ContainerBuilder {
func build(fromPayload payload: ArraySlice<UInt8>) throws -> ASN1Container {
guard payload.count >= 2,
let firstByte = payload.first else {
throw ReceiptReadingError.asn1ParsingError(description: "payload needs to be at least 2 bytes long")
}
let containerClass = try extractClass(byte: firstByte)
let encodingType = try extractEncodingType(byte: firstByte)
let containerIdentifier = try extractIdentifier(byte: firstByte)
let isConstructed = encodingType == .constructed
let (length, internalContainers) = try extractLengthAndInternalContainers(data: payload.dropFirst(),
isConstructed: isConstructed)
let bytesUsedForIdentifier = 1
let bytesUsedForMetadata = bytesUsedForIdentifier + length.bytesUsedForLength
guard payload.count - bytesUsedForMetadata >= length.value else {
throw ReceiptReadingError.asn1ParsingError(description: "payload is shorter than length value")
}
let internalPayload = payload.dropFirst(bytesUsedForMetadata).prefix(length.value)
return ASN1Container(containerClass: containerClass,
containerIdentifier: containerIdentifier,
encodingType: encodingType,
length: length,
internalPayload: internalPayload,
internalContainers: internalContainers)
}
}
// @unchecked because:
// - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe.
extension ASN1ContainerBuilder: @unchecked Sendable {}
private extension ASN1ContainerBuilder {
func buildInternalContainers(payload: ArraySlice<UInt8>) throws -> [ASN1Container] {
var internalContainers = [ASN1Container]()
var currentPayload = payload
while currentPayload.count > 0 {
let internalContainer = try build(fromPayload: currentPayload)
internalContainers.append(internalContainer)
if internalContainer.containerIdentifier == .endOfContent {
break
}
currentPayload = currentPayload.dropFirst(internalContainer.totalBytesUsed)
}
return internalContainers
}
func extractClass(byte: UInt8) throws -> ASN1Class {
let firstTwoBits = try byte.valueInRange(from: 0, to: 1)
guard let asn1Class = ASN1Class(rawValue: firstTwoBits) else {
throw ReceiptReadingError.asn1ParsingError(description: "couldn't determine asn1 class")
}
return asn1Class
}
func extractEncodingType(byte: UInt8) throws -> ASN1EncodingType {
let thirdBit = try byte.bitAtIndex(2)
guard let encodingType = ASN1EncodingType(rawValue: thirdBit) else {
throw ReceiptReadingError.asn1ParsingError(description: "couldn't determine encoding type")
}
return encodingType
}
func extractIdentifier(byte: UInt8) throws -> ASN1Identifier {
let lastFiveBits = try byte.valueInRange(from: 3, to: 7)
guard let asn1Identifier = ASN1Identifier(rawValue: lastFiveBits) else {
throw ReceiptReadingError.asn1ParsingError(description: "couldn't determine identifier")
}
return asn1Identifier
}
func extractLengthAndInternalContainers(data: ArraySlice<UInt8>,
isConstructed: Bool) throws -> (ASN1Length, [ASN1Container]) {
guard let firstByte = data.first else {
throw ReceiptReadingError.asn1ParsingError(description: "length needs to be at least one byte")
}
let lengthBit = try firstByte.bitAtIndex(0)
let isShortLength = lengthBit == 0
let firstByteValue = Int(try firstByte.valueInRange(from: 1, to: 7))
var bytesUsedForLength = 1
var lengthValue: Int
if isShortLength {
lengthValue = firstByteValue
} else {
let totalLengthBytes = firstByteValue
bytesUsedForLength += totalLengthBytes
let lengthBytes = data.dropFirst().prefix(totalLengthBytes)
lengthValue = lengthBytes.toInt()
}
var innerContainers: [ASN1Container] = []
// StoreKitTest receipts report a length of zero for Constructed elements.
// This is called indefinite-length in ASN1 containers.
// When length == 0, the element's contents end when there's a container with .endOfContent identifier
// To get the length, we build the internal containers until we run into .endOfContent and sum up the bytes used
let lengthDefinition: ASN1Length.LengthDefinition = (isConstructed && lengthValue == 0)
? .indefinite : .definite
if lengthDefinition == .indefinite {
innerContainers = try buildInternalContainers(payload: data.dropFirst(bytesUsedForLength))
let innerContainersOverallLength = innerContainers.map { $0.totalBytesUsed }.reduce(0, +)
lengthValue = innerContainersOverallLength
} else if isConstructed {
let innerContainerData = data.dropFirst(bytesUsedForLength).prefix(lengthValue)
innerContainers = try buildInternalContainers(payload: innerContainerData)
}
let length = ASN1Length(value: lengthValue,
bytesUsedForLength: bytesUsedForLength,
definition: lengthDefinition)
return (length, innerContainers)
}
}
|
mit
|
718d1927d8d31c1e22ac2a13d244ae91
| 43.547445 | 120 | 0.651974 | 4.96987 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Media/MediaLibraryViewController.swift
|
1
|
25812
|
import UIKit
import Gridicons
import SVProgressHUD
import WordPressShared
import WPMediaPicker
import MobileCoreServices
/// Displays the user's media library in a grid
///
class MediaLibraryViewController: WPMediaPickerViewController {
fileprivate static let restorationIdentifier = "MediaLibraryViewController"
@objc let blog: Blog
fileprivate let pickerDataSource: MediaLibraryPickerDataSource
fileprivate var isLoading: Bool = false
fileprivate let noResultsView = NoResultsViewController.controller()
fileprivate var selectedAsset: Media? = nil
fileprivate var capturePresenter: WPMediaCapturePresenter?
// After 99% progress, we'll count a media item as being uploaded, and we'll
// show an indeterminate spinner as the server processes it.
fileprivate static let uploadCompleteProgress: Double = 0.99
fileprivate var uploadObserverUUID: UUID?
fileprivate lazy var mediaPickingCoordinator: MediaLibraryMediaPickingCoordinator = {
return MediaLibraryMediaPickingCoordinator(delegate: self)
}()
// MARK: - Initializers
@objc init(blog: Blog) {
WPMediaCollectionViewCell.appearance().placeholderTintColor = .neutral(.shade5)
WPMediaCollectionViewCell.appearance().placeholderBackgroundColor = .neutral(.shade70)
WPMediaCollectionViewCell.appearance().loadingBackgroundColor = .listBackground
self.blog = blog
self.pickerDataSource = MediaLibraryPickerDataSource(blog: blog)
self.pickerDataSource.includeUnsyncedMedia = true
super.init(options: MediaLibraryViewController.pickerOptions())
registerClass(forReusableCellOverlayViews: CircularProgressView.self)
super.restorationIdentifier = MediaLibraryViewController.restorationIdentifier
restorationClass = MediaLibraryViewController.self
self.dataSource = pickerDataSource
self.mediaPickerDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
unregisterChangeObserver()
unregisterUploadCoordinatorObserver()
}
private class func pickerOptions() -> WPMediaPickerOptions {
let options = WPMediaPickerOptions()
options.showMostRecentFirst = true
options.filter = [.all]
options.allowMultipleSelection = false
options.allowCaptureOfMedia = false
options.showSearchBar = true
options.showActionBar = false
options.badgedUTTypes = [String(kUTTypeGIF)]
options.preferredStatusBarStyle = WPStyleGuide.preferredStatusBarStyle
return options
}
// MARK: - View Loading
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Media", comment: "Title for Media Library section of the app.")
registerChangeObserver()
registerUploadCoordinatorObserver()
noResultsView.configureForNoAssets(userCanUploadMedia: blog.userCanUploadMedia)
noResultsView.delegate = self
updateViewState(for: pickerDataSource.totalAssetCount)
if let collectionView = collectionView {
WPStyleGuide.configureColors(view: view, collectionView: collectionView)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectedAsset = nil
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if searchBar?.isFirstResponder == true {
searchBar?.resignFirstResponder()
}
}
// MARK: - Update view state
fileprivate func updateViewState(for assetCount: Int) {
updateNavigationItemButtons(for: assetCount)
updateNoResultsView(for: assetCount)
updateSearchBar(for: assetCount)
}
private func updateNavigationItemButtons(for assetCount: Int) {
if isEditing {
navigationItem.setLeftBarButton(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(editTapped)), animated: false)
let trashButton = UIBarButtonItem(image: .gridicon(.trash), style: .plain, target: self, action: #selector(trashTapped))
navigationItem.setRightBarButtonItems([trashButton], animated: true)
navigationItem.rightBarButtonItem?.isEnabled = false
} else {
navigationItem.setLeftBarButton(nil, animated: false)
var barButtonItems = [UIBarButtonItem]()
if blog.userCanUploadMedia && assetCount > 0 {
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
barButtonItems.append(addButton)
}
if blog.supports(.mediaDeletion) && assetCount > 0 {
let editButton = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editTapped))
barButtonItems.append(editButton)
navigationItem.setRightBarButtonItems(barButtonItems, animated: false)
} else {
navigationItem.setRightBarButtonItems(barButtonItems, animated: false)
}
}
}
fileprivate func updateNoResultsView(for assetCount: Int) {
guard assetCount == 0 else { return }
if isLoading {
noResultsView.configureForFetching()
} else {
noResultsView.removeFromView()
if hasSearchQuery {
noResultsView.configureForNoSearchResult()
} else {
noResultsView.configureForNoAssets(userCanUploadMedia: blog.userCanUploadMedia)
}
}
}
private func updateSearchBar(for assetCount: Int) {
let shouldShowBar = hasSearchQuery || assetCount > 0
if shouldShowBar {
showSearchBar()
if let searchBar = self.searchBar {
WPStyleGuide.configureSearchBar(searchBar)
}
} else {
hideSearchBar()
}
}
private func reloadCell(for media: Media) {
visibleCells(for: media).forEach { cell in
cell.overlayView = nil
cell.asset = media
}
}
private func updateCellProgress(_ progress: Double, for media: Media) {
visibleCells(for: media).forEach { cell in
if let overlayView = cell.overlayView as? CircularProgressView {
if progress < MediaLibraryViewController.uploadCompleteProgress {
overlayView.state = .progress(progress)
} else {
overlayView.state = .indeterminate
}
configureAppearance(for: overlayView, with: media)
}
}
}
private func configureAppearance(for overlayView: CircularProgressView, with media: Media) {
if media.localThumbnailURL != nil {
overlayView.backgroundColor = overlayView.backgroundColor?.withAlphaComponent(0.5)
} else {
overlayView.backgroundColor = overlayView.backgroundColor?.withAlphaComponent(1)
}
}
private func showUploadingStateForCell(for media: Media) {
visibleCells(for: media).forEach { cell in
if let overlayView = cell.overlayView as? CircularProgressView {
overlayView.state = .indeterminate
}
}
}
private func showFailedStateForCell(for media: Media) {
visibleCells(for: media).forEach { cell in
if let overlayView = cell.overlayView as? CircularProgressView {
overlayView.state = .retry
configureAppearance(for: overlayView, with: media)
}
}
}
private func visibleCells(for media: Media) -> [WPMediaCollectionViewCell] {
guard let cells = collectionView?.visibleCells as? [WPMediaCollectionViewCell] else {
return []
}
return cells.filter({ ($0.asset as? Media) == media })
}
private var hasSearchQuery: Bool {
return (pickerDataSource.searchQuery ?? "").count > 0
}
// MARK: - Actions
@objc fileprivate func addTapped() {
showOptionsMenu()
}
private func showOptionsMenu() {
let pickingContext: MediaPickingContext
if pickerDataSource.totalAssetCount > 0 {
pickingContext = MediaPickingContext(origin: self, view: view, barButtonItem: navigationItem.rightBarButtonItem, blog: blog)
} else {
pickingContext = MediaPickingContext(origin: self, view: noResultsView.actionButton, blog: blog)
}
mediaPickingCoordinator.present(context: pickingContext)
}
@objc private func editTapped() {
isEditing = !isEditing
}
@objc private func trashTapped() {
let message: String
if selectedAssets.count == 1 {
message = NSLocalizedString("Are you sure you want to permanently delete this item?", comment: "Message prompting the user to confirm that they want to permanently delete a media item. Should match Calypso.")
} else {
message = NSLocalizedString("Are you sure you want to permanently delete these items?", comment: "Message prompting the user to confirm that they want to permanently delete a group of media items.")
}
let alertController = UIAlertController(title: nil,
message: message,
preferredStyle: .alert)
alertController.addCancelActionWithTitle(NSLocalizedString("Cancel", comment: "Verb. Button title. Tapping cancels an action."))
alertController.addDestructiveActionWithTitle(NSLocalizedString("Delete", comment: "Title for button that permanently deletes one or more media items (photos / videos)"), handler: { action in
self.deleteSelectedItems()
})
present(alertController, animated: true)
}
private func deleteSelectedItems() {
guard selectedAssets.count > 0 else { return }
guard let assets = selectedAssets as? [Media] else { return }
let deletedItemsCount = assets.count
let updateProgress = { (progress: Progress?) in
let fractionCompleted = progress?.fractionCompleted ?? 0
SVProgressHUD.showProgress(Float(fractionCompleted), status: NSLocalizedString("Deleting...", comment: "Text displayed in HUD while a media item is being deleted."))
}
SVProgressHUD.setDefaultMaskType(.clear)
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
// Initialize the progress HUD before we start
updateProgress(nil)
isEditing = false
MediaCoordinator.shared.delete(media: assets,
onProgress: updateProgress,
success: { [weak self] in
WPAppAnalytics.track(.mediaLibraryDeletedItems, withProperties: ["number_of_items_deleted": deletedItemsCount], with: self?.blog)
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Deleted!", comment: "Text displayed in HUD after successfully deleting a media item"))
},
failure: {
SVProgressHUD.showError(withStatus: NSLocalizedString("Unable to delete all media items.", comment: "Text displayed in HUD if there was an error attempting to delete a group of media items."))
})
}
fileprivate func presentRetryOptions(for media: Media) {
let style: UIAlertController.Style = UIDevice.isPad() ? .alert : .actionSheet
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: style)
alertController.addDestructiveActionWithTitle(NSLocalizedString("Cancel Upload", comment: "Media Library option to cancel an in-progress or failed upload.")) { _ in
MediaCoordinator.shared.delete(media: [media])
}
if media.remoteStatus == .failed {
if let error = media.error {
alertController.message = error.localizedDescription
}
if media.absoluteLocalURL != nil {
alertController.addDefaultActionWithTitle(NSLocalizedString("Retry Upload", comment: "User action to retry media upload.")) { _ in
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.wpMediaLibrary))
MediaCoordinator.shared.retryMedia(media, analyticsInfo: info)
}
} else {
alertController.addDefaultActionWithTitle(NSLocalizedString("Delete", comment: "User action to delete media.")) { _ in
MediaCoordinator.shared.delete(media: [media])
}
}
}
alertController.addCancelActionWithTitle(NSLocalizedString("Dismiss", comment: "Verb. Button title. Tapping dismisses a prmopt."))
present(alertController, animated: true)
}
override var isEditing: Bool {
didSet {
updateNavigationItemButtons(for: pickerDataSource.totalAssetCount)
let options = self.options.copy() as! WPMediaPickerOptions
options.allowMultipleSelection = isEditing
self.options = options
clearSelectedAssets(false)
}
}
// MARK: - Media Library Change Observer
private var mediaLibraryChangeObserverKey: NSObjectProtocol? = nil
private func registerChangeObserver() {
assert(mediaLibraryChangeObserverKey == nil)
mediaLibraryChangeObserverKey = pickerDataSource.registerChangeObserverBlock({ [weak self] _, removed, inserted, _, _ in
guard let strongSelf = self else { return }
guard removed.count > 0 || inserted.count > 0 else { return }
strongSelf.updateViewState(for: strongSelf.pickerDataSource.numberOfAssets())
if strongSelf.pickerDataSource.totalAssetCount > 0 {
strongSelf.updateNavigationItemButtonsForCurrentAssetSelection()
} else {
strongSelf.isEditing = false
}
// If we're presenting an item and it's been deleted, pop the
// detail view off the stack
if let navigationController = strongSelf.navigationController,
navigationController.topViewController != strongSelf,
let asset = strongSelf.selectedAsset,
asset.isDeleted {
_ = strongSelf.navigationController?.popToViewController(strongSelf, animated: true)
}
})
}
private func unregisterChangeObserver() {
if let mediaLibraryChangeObserverKey = mediaLibraryChangeObserverKey {
pickerDataSource.unregisterChangeObserver(mediaLibraryChangeObserverKey)
}
}
// MARK: - Upload Coordinator Observer
private func registerUploadCoordinatorObserver() {
uploadObserverUUID = MediaCoordinator.shared.addObserver({ [weak self] (media, state) in
switch state {
case .progress(let progress):
if media.remoteStatus == .failed {
self?.showFailedStateForCell(for: media)
} else {
self?.updateCellProgress(progress, for: media)
}
case .processing, .uploading:
self?.showUploadingStateForCell(for: media)
case .ended:
self?.reloadCell(for: media)
case .failed:
self?.showFailedStateForCell(for: media)
case .thumbnailReady:
if media.remoteStatus == .failed {
self?.showFailedStateForCell(for: media)
} else {
self?.showUploadingStateForCell(for: media)
}
}
}, for: nil)
}
private func unregisterUploadCoordinatorObserver() {
if let uuid = uploadObserverUUID {
MediaCoordinator.shared.removeObserver(withUUID: uuid)
}
}
}
// MARK: - UIDocumentPickerDelegate
extension MediaLibraryViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
for documentURL in urls as [NSURL] {
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.otherApps), selectionMethod: .documentPicker)
MediaCoordinator.shared.addMedia(from: documentURL, to: blog, analyticsInfo: info)
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true)
}
}
// MARK: - NoResultsViewControllerDelegate
extension MediaLibraryViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
addTapped()
}
}
// MARK: - WPMediaPickerViewControllerDelegate
extension MediaLibraryViewController: WPMediaPickerViewControllerDelegate {
func emptyViewController(forMediaPickerController picker: WPMediaPickerViewController) -> UIViewController? {
return noResultsView
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didUpdateSearchWithAssetCount assetCount: Int) {
updateNoResultsView(for: assetCount)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) {
// We're only interested in the upload picker
guard picker != self else { return }
pickerDataSource.searchCancelled()
dismiss(animated: true)
guard ReachabilityUtils.isInternetReachable() else {
ReachabilityUtils.showAlertNoInternetConnection()
return
}
guard let assets = assets as? [PHAsset],
assets.count > 0 else { return }
for asset in assets {
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.deviceLibrary), selectionMethod: .fullScreenPicker)
MediaCoordinator.shared.addMedia(from: asset, to: blog, analyticsInfo: info)
}
}
func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) {
pickerDataSource.searchCancelled()
dismiss(animated: true)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, willShowOverlayView overlayView: UIView, forCellFor asset: WPMediaAsset) {
guard let overlayView = overlayView as? CircularProgressView,
let media = asset as? Media else {
return
}
WPStyleGuide.styleProgressViewForMediaCell(overlayView)
switch media.remoteStatus {
case .processing:
if let progress = MediaCoordinator.shared.progress(for: media) {
overlayView.state = .progress(progress.fractionCompleted)
} else {
overlayView.state = .indeterminate
}
case .pushing:
if let progress = MediaCoordinator.shared.progress(for: media) {
overlayView.state = .progress(progress.fractionCompleted)
}
case .failed:
overlayView.state = .retry
default: break
}
configureAppearance(for: overlayView, with: media)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, shouldShowOverlayViewForCellFor asset: WPMediaAsset) -> Bool {
if let media = asset as? Media {
return media.remoteStatus != .sync
}
return false
}
func mediaPickerController(_ picker: WPMediaPickerViewController, previewViewControllerFor asset: WPMediaAsset) -> UIViewController? {
guard picker == self else { return WPAssetViewController(asset: asset) }
guard let media = asset as? Media,
media.remoteStatus == .sync else {
return nil
}
WPAppAnalytics.track(.mediaLibraryPreviewedItem, with: blog)
return mediaItemViewController(for: asset)
}
func mediaPickerController(_ picker: WPMediaPickerViewController, shouldSelect asset: WPMediaAsset) -> Bool {
guard picker == self else {
return true
}
guard let media = asset as? Media else {
return false
}
guard !isEditing else {
return media.remoteStatus == .sync || media.remoteStatus == .failed
}
switch media.remoteStatus {
case .failed, .pushing, .processing:
presentRetryOptions(for: media)
case .sync:
if let viewController = mediaItemViewController(for: asset) {
WPAppAnalytics.track(.mediaLibraryPreviewedItem, with: blog)
navigationController?.pushViewController(viewController, animated: true)
}
default: break
}
return false
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didSelect asset: WPMediaAsset) {
guard picker == self else { return }
updateNavigationItemButtonsForCurrentAssetSelection()
}
func mediaPickerController(_ picker: WPMediaPickerViewController, didDeselect asset: WPMediaAsset) {
guard picker == self else { return }
updateNavigationItemButtonsForCurrentAssetSelection()
}
@objc func updateNavigationItemButtonsForCurrentAssetSelection() {
if isEditing {
// Check that our selected items haven't been deleted – we're notified
// of changes to the data source before the collection view has
// updated its selected assets.
guard let assets = (selectedAssets as? [Media]) else { return }
let existingAssets = assets.filter({ !$0.isDeleted })
navigationItem.rightBarButtonItem?.isEnabled = (existingAssets.count > 0)
}
}
private func mediaItemViewController(for asset: WPMediaAsset) -> UIViewController? {
if isEditing { return nil }
guard let asset = asset as? Media else {
return nil
}
selectedAsset = asset
return MediaItemViewController(media: asset)
}
func mediaPickerControllerWillBeginLoadingData(_ picker: WPMediaPickerViewController) {
guard picker == self else { return }
isLoading = true
updateNoResultsView(for: pickerDataSource.numberOfAssets())
}
func mediaPickerControllerDidEndLoadingData(_ picker: WPMediaPickerViewController) {
guard picker == self else { return }
isLoading = false
updateViewState(for: pickerDataSource.numberOfAssets())
}
func mediaPickerController(_ picker: WPMediaPickerViewController, handleError error: Error) -> Bool {
let nserror = error as NSError
if let mediaLibrary = self.blog.media, !mediaLibrary.isEmpty {
let title = NSLocalizedString("Unable to Sync", comment: "Title of error prompt shown when a sync the user initiated fails.")
WPError.showNetworkingNotice(title: title, error: nserror)
}
return true
}
}
// MARK: - State restoration
extension MediaLibraryViewController: UIViewControllerRestoration {
enum EncodingKey {
static let blogURL = "blogURL"
}
static func viewController(withRestorationIdentifierPath identifierComponents: [String],
coder: NSCoder) -> UIViewController? {
guard let identifier = identifierComponents.last,
identifier == MediaLibraryViewController.restorationIdentifier else {
return nil
}
guard let blogURL = coder.decodeObject(forKey: EncodingKey.blogURL) as? URL else {
return nil
}
let context = ContextManager.sharedInstance().mainContext
guard let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: blogURL),
let object = try? context.existingObject(with: objectID),
let blog = object as? Blog else {
return nil
}
return MediaLibraryViewController(blog: blog)
}
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
coder.encode(blog.objectID.uriRepresentation(), forKey: EncodingKey.blogURL)
}
}
fileprivate extension Blog {
var userCanUploadMedia: Bool {
// Self-hosted non-Jetpack blogs have no capabilities, so we'll just assume that users can post media
return capabilities != nil ? isUploadingFilesAllowed() : true
}
}
// MARK: Stock Photos Picker Delegate
extension MediaLibraryViewController: StockPhotosPickerDelegate {
func stockPhotosPicker(_ picker: StockPhotosPicker, didFinishPicking assets: [StockPhotosMedia]) {
guard assets.count > 0 else {
return
}
let mediaCoordinator = MediaCoordinator.shared
assets.forEach { stockPhoto in
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.stockPhotos), selectionMethod: .fullScreenPicker)
mediaCoordinator.addMedia(from: stockPhoto, to: blog, analyticsInfo: info)
WPAnalytics.track(.stockMediaUploaded)
}
}
}
// MARK: Tenor Picker Delegate
extension MediaLibraryViewController: TenorPickerDelegate {
func tenorPicker(_ picker: TenorPicker, didFinishPicking assets: [TenorMedia]) {
guard assets.count > 0 else {
return
}
let mediaCoordinator = MediaCoordinator.shared
assets.forEach { tenorMedia in
let info = MediaAnalyticsInfo(origin: .mediaLibrary(.tenor), selectionMethod: .fullScreenPicker)
mediaCoordinator.addMedia(from: tenorMedia, to: blog, analyticsInfo: info)
WPAnalytics.track(.tenorUploaded)
}
}
}
|
gpl-2.0
|
7ae504f33c9c1136ddabb6e3f1b163c1
| 36.844575 | 220 | 0.65525 | 5.655127 | false | false | false | false |
tianbinbin/DouYuShow
|
DouYuShow/DouYuShow/Classes/Home/Controller/HomeViewController.swift
|
1
|
3756
|
//
// HomeViewController.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/5/30.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
private let kTitleViewH:CGFloat = 40
class HomeViewController: UIViewController {
// 懒加载TitleView
fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kStatusBarH+kNavgationBarH, width: kSCREENW, height: kTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate = self
return titleView
}()
// 懒加载PageContentView
fileprivate lazy var pageContentView:PageContentView = {[weak self] in
// 1.确定内容的frame
let contenHight = kSCREENH - (kStatusBarH+kNavgationBarH+kTitleViewH+kTabBarH)
let contentframe = CGRect(x: 0, y: kStatusBarH+kNavgationBarH+kTitleViewH, width: kSCREENW, height: contenHight)
//2. 确定控制器
var childVCS = [UIViewController]()
childVCS.append(RecommdViewController())
childVCS.append(GameViewController())
childVCS.append(AmuseViewController())
childVCS.append(FunnyViewController())
let pageContentView = PageContentView(frame: contentframe, childVCS: childVCS, parentViewController: self)
pageContentView.delegate = self
return pageContentView
}()
override func viewDidLoad() {
super.viewDidLoad()
//0.不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
//1.设置UI界面
setupUI()
//2.添加titleView
view.addSubview(pageTitleView)
//3.添加contentview
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.orange
}
}
// Mark-- 设置UI
extension HomeViewController{
fileprivate func setupUI(){
// 1.设置导航栏
SetupNavgationBar()
}
private func SetupNavgationBar(){
navigationController?.navigationBar.setBackgroundImage(UIImage(named: "dym_browser_nav_loading"), for: .default)
// 1. 设置左侧item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "homeLogoIcon")
// 2. 设置右侧item
let size = CGSize(width: 30, height: 30)
/* 这种是通过类的扩展的封装
let historyItem = UIBarButtonItem.CreateItem(imageName: "viewHistoryIcon", hightImageName: "viewHistoryIconHL", Size: size)
let gameItem = UIBarButtonItem.CreateItem(imageName: "home_newGameicon", hightImageName: "home_newGameicon", Size: size)
*/
// 这种是重写写了一个构造函数
let historyItem = UIBarButtonItem(imageName: "viewHistoryIcon", hightImageName: "viewHistoryIcon", Size: size)
let gameItem = UIBarButtonItem(imageName: "home_newGameicon", hightImageName: "home_newGameicon", Size: size)
navigationItem.rightBarButtonItems = [historyItem,gameItem]
}
}
//mark:遵守PageTitleViewdelegate
extension HomeViewController:PageTitleViewDelegate{
func pageTitle(titleView: PageTitleView, selectindex index: Int) {
pageContentView.SetCurrentIndex(currentIndex: index)
}
}
//mark:遵守PageContentViewdelegate
extension HomeViewController:PageContentViewDelegate{
func PageContenView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, TargetIndex: Int) {
pageTitleView.SetTitleViewProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: TargetIndex)
}
}
|
mit
|
3185c64264487adb29b3694ff9492a84
| 28.512397 | 131 | 0.673481 | 4.851902 | false | false | false | false |
bugcoding/macOSCalendar
|
MacCalendar/SettingMenu.swift
|
1
|
2022
|
//
// SettingMenu.swift
// StatebarCalendar
//
// Created by bugcode on 2016/12/10.
// Copyright © 2016年 bugcode. All rights reserved.
//
import Cocoa
class SettingMenu: NSMenu {
init() {
super.init(title: "Setting")
// 设置项
let set = self.insertItem(withTitle: "设置", action: #selector(SettingMenu.setting(_:)), keyEquivalent: "", at: 0)
set.target = self
// 工具
let tool = self.insertItem(withTitle: "工具", action: #selector(SettingMenu.tools(_:)), keyEquivalent: "", at: 1)
tool.target = self
// 关于
let ab = self.insertItem(withTitle: "关于", action: #selector(SettingMenu.about(_:)), keyEquivalent: "", at: 2)
ab.target = self
// 退出
let qt = self.insertItem(withTitle: "退出", action: #selector(SettingMenu.quit(_:)), keyEquivalent: "", at: 3)
qt.target = self
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 设置界面回调
@objc func setting(_ sender: NSMenuItem){
(NSApp.delegate as! AppDelegate).openSettingWindow()
}
// 工具菜单回调
@objc func tools(_ sender: NSMenuItem){
(NSApp.delegate as! AppDelegate).openToolsWindow();
}
// 关于页面回调
@objc func about(_ sender: NSMenuItem) {
let style = NSMutableParagraphStyle()
style.alignment = .center
let abbr = [ NSAttributedStringKey.foregroundColor: NSColor.black , NSAttributedStringKey.paragraphStyle : style, NSAttributedStringKey.font : NSFont.systemFont(ofSize: 11.0)]
let infoAttributedStr = NSAttributedString(string: "report: [email protected]", attributes: abbr)
NSApp.orderFrontStandardAboutPanel(options: [NSApplication.AboutPanelOptionKey(rawValue: "Credits"):infoAttributedStr])
}
// 退出回调
@objc func quit(_ sender: NSMenuItem) {
NSApp.terminate(nil)
}
}
|
gpl-2.0
|
433fb4538806b91e18b93a2479c49b27
| 33.052632 | 183 | 0.626481 | 4.174194 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock
|
Pods/Charts/Charts/Classes/Utils/ChartSelectionDetail.swift
|
6
|
2738
|
//
// ChartSelectionDetail.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ChartSelectionDetail: NSObject
{
private var _y = CGFloat.nan
private var _value = Double(0)
private var _dataIndex = Int(0)
private var _dataSetIndex = Int(0)
private var _dataSet: IChartDataSet!
public override init()
{
super.init()
}
public init(y: CGFloat, value: Double, dataIndex: Int, dataSetIndex: Int, dataSet: IChartDataSet)
{
super.init()
_y = y
_value = value
_dataIndex = dataIndex
_dataSetIndex = dataSetIndex
_dataSet = dataSet
}
public convenience init(y: CGFloat, value: Double, dataSetIndex: Int, dataSet: IChartDataSet)
{
self.init(y: y, value: value, dataIndex: 0, dataSetIndex: dataSetIndex, dataSet: dataSet)
}
public convenience init(value: Double, dataSetIndex: Int, dataSet: IChartDataSet)
{
self.init(y: CGFloat.nan, value: value, dataIndex: 0, dataSetIndex: dataSetIndex, dataSet: dataSet)
}
open var y: CGFloat
{
return _y
}
open var value: Double
{
return _value
}
open var dataIndex: Int
{
return _dataIndex
}
open var dataSetIndex: Int
{
return _dataSetIndex
}
open var dataSet: IChartDataSet?
{
return _dataSet
}
// MARK: NSObject
open override func isEqual(_ object: Any?) -> Bool
{
if (object == nil)
{
return false
}
let object = object as AnyObject
if (!object.isKind(of: type(of: self)))
{
return false
}
if (object.value != _value)
{
return false
}
if (object.dataSetIndex != _dataSetIndex)
{
return false
}
if (object.dataSet !== _dataSet)
{
return false
}
return true
}
}
public func ==(lhs: ChartSelectionDetail, rhs: ChartSelectionDetail) -> Bool
{
if (lhs === rhs)
{
return true
}
if (!lhs.isKind(of: type(of: rhs)))
{
return false
}
if (lhs.value != rhs.value)
{
return false
}
if (lhs.dataSetIndex != rhs.dataSetIndex)
{
return false
}
if (lhs.dataSet !== rhs.dataSet)
{
return false
}
return true
}
|
mit
|
57383da92b42404d7cb022b6a4ae9e22
| 18.697842 | 107 | 0.537619 | 4.473856 | false | false | false | false |
corujautx/Announce
|
Tests/ViewTests/ThemeSpec.swift
|
1
|
6436
|
//
// ThemeSpec.swift
// Announce
//
// Created by Vitor Travain on 5/25/17.
// Copyright © 2017 Vitor Travain. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Announce
final class ThemeSpec: QuickSpec {
override func spec() {
describe("A theme") {
context("success") {
let theme = Theme.success
it("creates message appearance") {
let appearance = theme.appearanceForMessage()
expect(appearance.font).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.successBackgroundColor))
}
it("creates message with title appearance") {
let appearance = theme.appearanceForMessageWithTitle()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.successBackgroundColor))
}
it("creates message with image appearance") {
let appearance = theme.appearanceForMessageWithImage()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.successBackgroundColor))
}
}
context("info") {
let theme = Theme.info
it("creates message appearance") {
let appearance = theme.appearanceForMessage()
expect(appearance.font).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.infoBackgroundColor))
}
it("creates message with title appearance") {
let appearance = theme.appearanceForMessageWithTitle()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.infoBackgroundColor))
}
it("creates message with image appearance") {
let appearance = theme.appearanceForMessageWithImage()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.infoBackgroundColor))
}
}
context("warning") {
let theme = Theme.warning
it("creates message appearance") {
let appearance = theme.appearanceForMessage()
expect(appearance.font).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.warningBackgroundColor))
}
it("creates message with title appearance") {
let appearance = theme.appearanceForMessageWithTitle()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.warningBackgroundColor))
}
it("creates message with image appearance") {
let appearance = theme.appearanceForMessageWithImage()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.warningBackgroundColor))
}
}
context("danger") {
let theme = Theme.danger
it("creates message appearance") {
let appearance = theme.appearanceForMessage()
expect(appearance.font).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.dangerBackgroundColor))
}
it("creates message with title appearance") {
let appearance = theme.appearanceForMessageWithTitle()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.dangerBackgroundColor))
}
it("creates message with image appearance") {
let appearance = theme.appearanceForMessageWithImage()
expect(appearance.titleFont).to(equal(UIFont.boldSystemFont(ofSize: 14.0)))
expect(appearance.messageFont).to(equal(UIFont.systemFont(ofSize: 12.0)))
expect(appearance.foregroundColor).to(equal(UIColor.white))
expect(appearance.backgroundColor).to(equal(Theme.dangerBackgroundColor))
}
}
}
}
}
|
mit
|
483dd7ba056e91245248845bf850ea80
| 45.294964 | 95 | 0.5885 | 5.371452 | false | false | false | false |
lorentey/swift
|
test/SILGen/inlinable_attribute.swift
|
6
|
7928
|
// RUN: %target-swift-emit-silgen -module-name inlinable_attribute -emit-verbose-sil -warnings-as-errors %s | %FileCheck %s
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute15fragileFunctionyyF : $@convention(thin) () -> ()
@inlinable public func fragileFunction() {
}
public struct MySt {
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV6methodyyF : $@convention(method) (MySt) -> ()
@inlinable public func method() {}
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV8propertySivg : $@convention(method) (MySt) -> Int
@inlinable public var property: Int {
return 5
}
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStVyS2icig : $@convention(method) (Int, MySt) -> Int
@inlinable public subscript(x: Int) -> Int {
return x
}
}
public class MyCls {
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyClsCfD : $@convention(method) (@owned MyCls) -> ()
@inlinable deinit {}
// Allocating entry point is [serialized]
// CHECK-LABEL: sil [serialized] [exact_self_class] [ossa] @$s19inlinable_attribute5MyClsC14designatedInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls
public init(designatedInit: ()) {}
// Note -- convenience init is intentionally not [serialized]
// CHECK-LABEL: sil [ossa] @$s19inlinable_attribute5MyClsC15convenienceInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls
public convenience init(convenienceInit: ()) {
self.init(designatedInit: ())
}
}
// Make sure enum case constructors for public and versioned enums are
// [serialized].
@usableFromInline enum MyEnum {
case c(MySt)
}
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] [ossa] @$s19inlinable_attribute6MyEnumO1cyAcA0C2StVcACmFTc : $@convention(thin) (@thin MyEnum.Type) -> @owned @callee_guaranteed (MySt) -> MyEnum
@inlinable public func referencesMyEnum() {
_ = MyEnum.c
}
// CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1xSivpfi : $@convention(thin) () -> Int
// CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1ySivpfi : $@convention(thin) () -> Int
@frozen
public struct HasInitializers {
public let x = 1234
internal let y = 4321
@inlinable public init() {}
}
public class Horse {
public func gallop() {}
}
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tF : $@convention(thin) (@guaranteed Horse) -> () {
// CHECK: function_ref @$s19inlinable_attribute5HorseC6gallopyyFTc
// CHECK: return
// CHECK: }
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute5HorseC6gallopyyFTc : $@convention(thin) (@guaranteed Horse) -> @owned @callee_guaranteed () -> () {
// CHECK: class_method
// CHECK: return
// CHECK: }
@inlinable public func talkAboutAHorse(h: Horse) {
_ = h.gallop
}
@_fixed_layout
public class PublicBase {
@inlinable
public init(horse: Horse) {}
}
@usableFromInline
@_fixed_layout
class UFIBase {
@usableFromInline
@inlinable
init(horse: Horse) {}
}
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0Cfd : $@convention(method) (@guaranteed PublicDerivedFromPublic) -> @owned Builtin.NativeObject
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0CfD : $@convention(method) (@owned PublicDerivedFromPublic) -> ()
// Make sure the synthesized delegating initializer is inlinable also
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0C5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PublicDerivedFromPublic) -> @owned PublicDerivedFromPublic
@_fixed_layout
public class PublicDerivedFromPublic : PublicBase {
// Allow @inlinable deinits
@inlinable deinit {}
}
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute20UFIDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromPublic) -> @owned UFIDerivedFromPublic
@usableFromInline
@_fixed_layout
class UFIDerivedFromPublic : PublicBase {
}
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute17UFIDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromUFI) -> @owned UFIDerivedFromUFI
@usableFromInline
@_fixed_layout
class UFIDerivedFromUFI : UFIBase {
// Allow @inlinable deinits
@inlinable deinit {}
}
// CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute25InternalDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromPublic) -> @owned InternalDerivedFromPublic
class InternalDerivedFromPublic : PublicBase {}
// CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute22InternalDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromUFI) -> @owned InternalDerivedFromUFI
class InternalDerivedFromUFI : UFIBase {}
// CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute24PrivateDerivedFromPublic{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromPublic) -> @owned PrivateDerivedFromPublic
private class PrivateDerivedFromPublic : PublicBase {}
// CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute21PrivateDerivedFromUFI{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromUFI) -> @owned PrivateDerivedFromUFI
private class PrivateDerivedFromUFI : UFIBase {}
// Make sure that nested functions are also serializable.
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute3basyyF
@inlinable
public func bas() {
// CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF
func zim() {
// CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF4zangL_yyF
func zang() { }
}
// CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3bas{{[_0-9a-zA-Z]*}}U_
let _ = {
// CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute3basyyFyycfU_7zippityL_yyF
func zippity() { }
}
}
// CHECK-LABEL: sil [ossa] @$s19inlinable_attribute6globalyS2iF : $@convention(thin) (Int) -> Int
public func global(_ x: Int) -> Int { return x }
// CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF : $@convention(thin) () -> ()
@inlinable func cFunctionPointer() {
// CHECK: function_ref @$s19inlinable_attribute6globalyS2iFTo
let _: @convention(c) (Int) -> Int = global
// CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To
let _: @convention(c) (Int) -> Int = { return $0 }
func local(_ x: Int) -> Int {
return x
}
// CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo
let _: @convention(c) (Int) -> Int = local
}
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute6globalyS2iFTo : $@convention(c) (Int) -> Int
// CHECK: function_ref @$s19inlinable_attribute6globalyS2iF
// CHECK: return
// CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ : $@convention(thin) (Int) -> Int {
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To : $@convention(c) (Int) -> Int {
// CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_
// CHECK: return
// CHECK-LABEL: sil shared [serializable] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF : $@convention(thin) (Int) -> Int {
// CHECK-LABEL: sil shared [serializable] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo : $@convention(c) (Int) -> Int {
// CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF
// CHECK: return
|
apache-2.0
|
9fd62f2e10cff3eb99c6ba7b62be9eb5
| 42.086957 | 221 | 0.740288 | 3.512627 | false | false | false | false |
vector-im/vector-ios
|
DesignKit/Variants/Fonts/ElementFonts.swift
|
1
|
8968
|
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
/// Fonts at https://www.figma.com/file/X4XTH9iS2KGJ2wFKDqkyed/Compound?node-id=1362%3A0
@objcMembers
public class ElementFonts {
// MARK: - Types
/// A wrapper to provide both a `UIFont` and a SwiftUI `Font` in the same type.
/// The need for this comes from `Font` not adapting for dynamic type until the app
/// is restarted (or working at all in Xcode Previews) when initialised from a `UIFont`
/// (even if that font was created with the appropriate metrics).
public struct SharedFont {
public let uiFont: UIFont
/// The underlying font for the `font` property. This is stored
/// as an optional `Any` due to unavailability on iOS 12.
private let _font: Any?
@available(iOS 13.0, *)
public var font: Font {
_font as! Font
}
@available(iOS, deprecated: 13.0, message: "Use init(uiFont:font:) instead and remove this initialiser.")
init(uiFont: UIFont) {
self.uiFont = uiFont
self._font = nil
}
@available(iOS 13.0, *)
init(uiFont: UIFont, font: Font) {
self.uiFont = uiFont
self._font = font
}
}
// MARK: - Setup
public init() {
}
// MARK: - Private
/// Returns an instance of the font associated with the text style and scaled appropriately for the content size category defined in the trait collection.
/// Keep this method private method at the moment and create a DesignKit.Fonts.TextStyle if needed.
fileprivate func font(forTextStyle textStyle: UIFont.TextStyle, compatibleWith traitCollection: UITraitCollection? = nil) -> UIFont {
return UIFont.preferredFont(forTextStyle: textStyle, compatibleWith: traitCollection)
}
}
// MARK: - Fonts protocol
extension ElementFonts: Fonts {
public var largeTitle: SharedFont {
let uiFont = self.font(forTextStyle: .largeTitle)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .largeTitle)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var largeTitleB: SharedFont {
let uiFont = self.largeTitle.uiFont.vc_bold
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .largeTitle.bold())
} else {
return SharedFont(uiFont: uiFont)
}
}
public var title1: SharedFont {
let uiFont = self.font(forTextStyle: .title1)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .title)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var title1B: SharedFont {
let uiFont = self.title1.uiFont.vc_bold
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .title.bold())
} else {
return SharedFont(uiFont: uiFont)
}
}
public var title2: SharedFont {
let uiFont = self.font(forTextStyle: .title2)
if #available(iOS 14.0, *) {
return SharedFont(uiFont: uiFont, font: .title2)
} else if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: Font(uiFont))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var title2B: SharedFont {
let uiFont = self.title2.uiFont.vc_bold
if #available(iOS 14.0, *) {
return SharedFont(uiFont: uiFont, font: .title2.bold())
} else if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: Font(uiFont))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var title3: SharedFont {
let uiFont = self.font(forTextStyle: .title3)
if #available(iOS 14.0, *) {
return SharedFont(uiFont: uiFont, font: .title3)
} else if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: Font(uiFont))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var title3SB: SharedFont {
let uiFont = self.title3.uiFont.vc_semiBold
if #available(iOS 14.0, *) {
return SharedFont(uiFont: uiFont, font: .title3.weight(.semibold))
} else if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: Font(uiFont))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var headline: SharedFont {
let uiFont = self.font(forTextStyle: .headline)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .headline)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var subheadline: SharedFont {
let uiFont = self.font(forTextStyle: .subheadline)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .subheadline)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var body: SharedFont {
let uiFont = self.font(forTextStyle: .body)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .body)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var bodySB: SharedFont {
let uiFont = self.body.uiFont.vc_semiBold
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .body.weight(.semibold))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var callout: SharedFont {
let uiFont = self.font(forTextStyle: .callout)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .callout)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var calloutSB: SharedFont {
let uiFont = self.callout.uiFont.vc_semiBold
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .callout.weight(.semibold))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var footnote: SharedFont {
let uiFont = self.font(forTextStyle: .footnote)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .footnote)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var footnoteSB: SharedFont {
let uiFont = self.footnote.uiFont.vc_semiBold
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .footnote.weight(.semibold))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var caption1: SharedFont {
let uiFont = self.font(forTextStyle: .caption1)
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .caption)
} else {
return SharedFont(uiFont: uiFont)
}
}
public var caption1SB: SharedFont {
let uiFont = self.caption1.uiFont.vc_semiBold
if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: .caption.weight(.semibold))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var caption2: SharedFont {
let uiFont = self.font(forTextStyle: .caption2)
if #available(iOS 14.0, *) {
return SharedFont(uiFont: uiFont, font: .caption2)
} else if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: Font(uiFont))
} else {
return SharedFont(uiFont: uiFont)
}
}
public var caption2SB: SharedFont {
let uiFont = self.caption2.uiFont.vc_semiBold
if #available(iOS 14.0, *) {
return SharedFont(uiFont: uiFont, font: .caption2.weight(.semibold))
} else if #available(iOS 13.0, *) {
return SharedFont(uiFont: uiFont, font: Font(uiFont))
} else {
return SharedFont(uiFont: uiFont)
}
}
}
|
apache-2.0
|
f9ce3ae95ec8142dbd4b80311f7c7a70
| 30.914591 | 158 | 0.572257 | 4.008941 | false | false | false | false |
felipedemetrius/AppSwift3
|
AppSwift3/TaskDetailViewModel.swift
|
1
|
1273
|
//
// TaskDetalModel.swift
// AppSwift3
//
// Created by Felipe Silva on 3/30/17.
// Copyright © 2017 Felipe Silva . All rights reserved.
//
import Foundation
import Alamofire
class TaskDetailViewModel : TaskDetailViewDataSource {
var task: Dynamic<TaskModel?>
var title : Dynamic<String?>
var isLoadingDatasource: Dynamic<Bool>
var service = TaskService()
init(id: String) {
self.task = Dynamic(nil)
self.isLoadingDatasource = Dynamic(false)
self.title = Dynamic(nil)
self.setTask(id: id)
}
}
extension TaskDetailViewModel : TaskDetailViewDelegate {
func setTask(id: String) {
isLoadingDatasource.value = true
service.getTask(id: id, completionHandler: handler)
}
func handler(result: Result<TaskModel>){
switch result {
case .success(let value):
self.task.value = value
self.title.value = (value.city ?? "") + " - " + (value.neighborhood ?? "")
case .failure(let error):
print(error)
}
self.isLoadingDatasource.value = false
}
func favoriteTask(){
print("Botão Favoritos: não faz nada.")
}
}
|
mit
|
f2d78c68215f7608bd4825fda35e94ac
| 20.896552 | 86 | 0.58189 | 4.261745 | false | false | false | false |
Reggian/IOS-Pods-DFU-Library
|
iOSDFULibrary/Classes/Implementation/SecureDFU/Peripheral/SecureDFUPeripheral.swift
|
1
|
19585
|
/*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal class SecureDFUPeripheral: NSObject, CBPeripheralDelegate, CBCentralManagerDelegate {
/// Bluetooth Central Manager used to scan for the peripheral.
fileprivate let centralManager:CBCentralManager
/// The DFU Target peripheral.
fileprivate var peripheral:CBPeripheral?
/// The optional logger delegate.
fileprivate var logger:LoggerHelper
/// The peripheral delegate.
internal var delegate:SecureDFUPeripheralDelegate?
/// Selector used to find the advertising peripheral in DFU Bootloader mode.
fileprivate var peripheralSelector:DFUPeripheralSelector?
// MARK: - DFU properties
/// The DFU Service instance. Not nil when found on the peripheral.
fileprivate var dfuService:SecureDFUService?
/// A flag set when upload has been paused.
fileprivate var paused = false
/// A flag set when upload has been aborted.
fileprivate var aborted = false
/// Maxmimum length reported by peripheral
fileprivate var maxWtireLength : UInt32 = 0
/// Resetting flag, when the peripheral disconnects to reconncet
internal var isResetting = false
// MARK: - Initialization
init(_ initiator:SecureDFUServiceInitiator) {
self.centralManager = initiator.centralManager
self.peripheral = initiator.target
self.logger = LoggerHelper(initiator.logger)
super.init()
// self.peripheral.delegate = self // this is set when device got connected
self.centralManager.delegate = self
}
// MARK: - Peripheral API
/**
Connects to the peripheral, performs service discovery and reads the DFU Version characteristic if such exists.
When done, the `onDeviceReady()` callback is called. Errors are reported with `didErrorOccurred(error:withMessage)`.
*/
func connect() {
let name = peripheral!.name ?? "Unknown device"
logger.v("Connecting to \(name)...")
logger.d("centralManager.connectPeripheral(peripheral, options:nil)")
centralManager.connect(peripheral!, options: nil)
}
/**
Disconnects the target device.
*/
func disconnect() {
if peripheral != nil {
logger.v("Disconnecting...")
logger.d("centralManager.cancelPeripheralConnection(peripheral)")
centralManager.cancelPeripheralConnection(peripheral!)
}
}
func pause() -> Bool {
if !paused && dfuService != nil {
paused = true
dfuService!.pause()
return true
}
return false
}
func resume() -> Bool {
if paused && dfuService != nil {
paused = false
dfuService!.resume()
return true
}
return false
}
func abort() {
if dfuService != nil {
logger.w("Upload aborted")
aborted = true
paused = false
dfuService!.abort()
disconnect()
}
}
/**
Returns whether the Init Packet is required by the target DFU device.
- returns: true if init packet is required, false if not. Init packet is required
since DFU Bootloader version 0.5 (SDK 7.0.0).
*/
func isInitPacketRequired() -> Bool {
return false
}
/**
Enables notifications on DFU Control Point characteristic.
*/
func enableControlPoint() {
dfuService?.enableControlPoint(onSuccess: {_ in
self.delegate?.onControlPointEnabled()
}, onError: { (error, message) in
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Reads object info command to get max write size
*/
func ReadObjectInfoCommand() {
dfuService?.readObjectInfoCommand(onSuccess: { (responseData) in
//Parse response data
let count = (responseData?.count)! / MemoryLayout<UInt32>.size
var array = [UInt32](repeating: 0, count: count)
let range = count * MemoryLayout<UInt32>.size
(responseData as NSData?)?.getBytes(&array, length: range)
self.logger.i("Read Object Info Command : received data : MaxLen:\(array[0]), Offset:\(array[1]), CRC: \(array[2]))")
self.delegate?.objectInfoReadCommandCompleted(array[0], offset: array[1], crc: array[2])
}, onError: { (error, message) in
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Reads object info data to get max write size
*/
func ReadObjectInfoData() {
dfuService?.readObjectInfoData(onSuccess: { (responseData) in
//Parse resonpes data
let count = (responseData?.count)! / MemoryLayout<UInt32>.size
var array = [UInt32](repeating: 0, count: count)
let range = count * MemoryLayout<UInt32>.size
(responseData as NSData?)?.getBytes(&array, length: range)
self.logger.i("Read Object Info Data : received data : MaxLen:\(array[0]), Offset:\(array[1]), CRC: \(array[2]))")
self.delegate?.objectInfoReadDataCompleted(array[0], offset: array[1], crc: array[2])
}, onError: { (error, message) in
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Reads Extended error
*/
func readExtendedError() {
self.dfuService?.readError(onSuccess: { (responseData) in
self.logger.e("Read extended error data: \(responseData!)")
}, onError: { (error, message) in
self.logger.e("Failed to read extended error: \(message)")
})
}
/**
ExtendedError completion
*/
func readExtendedErrorCompleted(_ message : String) {
//TODO: implement
}
/**
Send firmware data
*/
func sendFirmwareChunk(_ firmware: DFUFirmware, andChunkRange aRange : Range<Int>, andPacketCount aCount : UInt16, andProgressDelegate aProgressDelegate : DFUProgressDelegate) {
self.dfuService?.sendFirmwareChunk(aRange, inFirmware: firmware, andPacketReceiptCount: aCount, andProgressDelegate: aProgressDelegate, andCompletionHandler: { (responseData) in
self.delegate?.firmwareChunkSendcomplete()
}, andErrorHandler: { (error, message) in
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Creates object data
*/
func createObjectData(withLength length: UInt32) {
dfuService?.createObjectData(withLength: length, onSuccess: { (responseData) in
self.delegate?.objectCreateDataCompleted(responseData)
}, onError: { (error, message) in
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Creates an object command
*/
func createObjectCommand(_ length: UInt32) {
dfuService?.createObjectCommand(withLength: length, onSuccess: { (responseData) in
self.delegate?.objectCreateCommandCompleted(responseData)
}, onError: { (error, message) in
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Set PRN Value
*/
func setPRNValue(_ aValue : UInt16 = 0) {
dfuService?.setPacketReceiptNotificationValue(aValue, onSuccess: { (responseData) in
self.delegate?.setPRNValueCompleted()
}, onError: { (error, message) in
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Send Init packet
*/
func sendInitpacket(_ packetData : Data){
dfuService?.sendInitPacket(withdata: packetData)
self.delegate?.initPacketSendCompleted()
}
/**
Send calculate Checksum comand
*/
func sendCalculateChecksumCommand() {
dfuService?.calculateChecksumCommand(onSuccess: { (responseData) in
//Parse resonpse data
let count = (responseData?.count)! / MemoryLayout<UInt32>.size
var array = [UInt32](repeating: 0, count: count)
let range = count * MemoryLayout<UInt32>.size
(responseData as NSData?)?.getBytes(&array, length: range)
self.delegate?.calculateChecksumCompleted(array[0], CRC: array[1])
}, onError: { (error, message) in
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
})
}
/**
Send execute command
*/
func sendExecuteCommand() {
dfuService?.executeCommand(onSuccess: { (responseData) in
self.delegate?.executeCommandCompleted()
}, onError: { (error, message) in
if error == SecureDFUError.extendedError {
self.logger.e("Extended error occured, attempting to read.")
self.readExtendedError()
}else{
self.logger.e("Error occured: \(error), \(message)")
self.delegate?.onErrorOccured(withError: error, andMessage: message)
}
})
}
/**
Checks whether the target device is in application mode and must be switched to the DFU mode.
- parameter forceDfu: should the service assume the device is in DFU Bootloader mode when
DFU Version characteristic does not exist and at least one other service has been found on the device.
- returns: true if device needs buttonless jump to DFU Bootloader mode
*/
func isInApplicationMode(_ forceDfu:Bool) -> Bool {
let applicationMode = dfuService!.isInApplicationMode() ?? !forceDfu
if applicationMode {
logger.w("Application with buttonless update found")
}
return applicationMode
}
/**
Scans for a next device to connect to. When device is found and selected, it connects to it.
After updating the Softdevice the device may start advertising with an address incremented by 1.
A BLE scan needs to be done to find this new peripheral (it's the same device, but as it
advertises with a new address, from iOS point of view it completly different device).
- parameter selector: a selector used to select a device in DFU Bootloader mode
*/
func switchToNewPeripheralAndConnect(_ selector:DFUPeripheralSelector) {
// Release the previous peripheral
self.peripheral!.delegate = nil
self.peripheral = nil
self.peripheralSelector = selector
logger.v("Scanning for the DFU Bootloader...")
centralManager.scanForPeripherals(withServices: selector.filterBy(), options: nil)
}
/**
This method breaks the cyclic reference and both DFUExecutor and DFUPeripheral may be released.
*/
func destroy() {
centralManager.delegate = nil
peripheral!.delegate = nil
peripheral = nil
delegate = nil
}
// MARK: - Central Manager methods
func centralManagerDidUpdateState(_ central: CBCentralManager) {
logCentralManagerState(CBCentralManagerState(rawValue: central.state.rawValue)!)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
cleanUp()
logger.d("[Callback] Central Manager did connect peripheral")
let name = peripheral.name ?? "Unknown device"
logger.i("Connected to \(name)")
// Discover all device services. In case there is no DFU Version characteristic the service
// will determine whether to jump to the DFU Bootloader mode, or not, based on number of services.
logger.v("Discovering services...")
logger.d("periphera.discoverServices(nil)")
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
cleanUp()
if let error = error {
logger.d("[Callback] Central Manager did fail to connect peripheral")
logger.e(error)
} else {
logger.d("[Callback] Central Manager did fail to connect peripheral without error")
}
logger.e("Device failed to connect")
delegate?.didDeviceFailToConnect()
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
if isResetting == true {
if error != nil {
logger.i("Resetting peripheral")
logger.d("[Callback] Central Manager did disconnect peripheral with error while resetting")
} else {
logger.i("Resetting peripheral")
logger.d("[Callback] Central Manager did disconnect peripheral without error")
}
return
}
if aborted == true {
delegate?.onAborted()
aborted = false
return
}
if error != nil {
if let anError = error as? CBError {
if anError.code == CBError.Code.peripheralDisconnected ||
anError.code == CBError.Code.connectionTimeout {
logger.i("Disconnected by the remote device")
}else{
logger.d("[Callback] Central Manager did disconnect peripheral without error")
delegate?.peripheralDisconnected()
return
}
}
//Unable to cast error
logger.d("[Callback] Central Manager did disconnect peripheral")
logger.i("Disconnected")
logger.e(error!)
delegate?.peripheralDisconnected(withError: error! as NSError)
} else {
logger.d("[Callback] Central Manager did disconnect peripheral without error")
logger.i("Disconnected")
delegate?.peripheralDisconnected()
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let peripheralSelector = peripheralSelector {
// Is this a device we are looking for?
if peripheralSelector.select(peripheral, advertisementData: advertisementData as [String : AnyObject], RSSI: RSSI) {
// Hurray!
centralManager.stopScan()
if let name = peripheral.name {
logger.i("DFU Bootloader found with name \(name)")
} else {
logger.i("DFU Bootloader found")
}
self.peripheral = peripheral
self.peripheralSelector = nil
connect()
}
} else {
// Don't use central manager while DFU is in progress!
print("DFU in progress, don't use this CentralManager instance!")
centralManager.stopScan()
}
}
// MARK: - Peripheral Delegate methods
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if error != nil {
logger.e("Services discovery failed")
logger.e(error!)
delegate?.onErrorOccured(withError: SecureDFUError.serviceDiscoveryFailed, andMessage: "Service discovery failed")
} else {
logger.i("Services discovered")
// Find the DFU Service
let services = peripheral.services!
for service in services {
if SecureDFUService.matches(service) {
logger.v("Secure DFU Service found")
// DFU Service has been found. Discover characteristics...
dfuService = SecureDFUService(service, logger)
dfuService!.discoverCharacteristics(
onSuccess: { (data) -> () in self.delegate?.onDeviceReady() },
onError: { (error, message) -> () in self.delegate?.onErrorOccured(withError: error, andMessage: message) }
)
}
}
if dfuService == nil {
logger.e("Secure DFU Service not found")
// The device does not support DFU, nor buttonless jump
delegate?.onErrorOccured(withError:SecureDFUError.deviceNotSupported, andMessage: "Secure DFU Service not found")
}
}
}
// MARK: - Private methods
fileprivate func cleanUp() {
dfuService = nil
}
fileprivate func logCentralManagerState(_ state:CBCentralManagerState) {
var stateAsString:String
switch (state) {
case .poweredOn:
stateAsString = "Powered ON"
break
case .poweredOff:
stateAsString = "Powered OFF"
break
case .resetting:
stateAsString = "Resetting"
break
case .unauthorized:
stateAsString = "Unauthorized"
break
case .unsupported:
stateAsString = "Unsupported"
break
case .unknown:
stateAsString = "Unknown"
break
}
logger.d("[Callback] Central Manager did update state to: \(stateAsString)")
}
}
|
mit
|
adc15a0af61e9723668b92cd1113dfc7
| 38.887984 | 185 | 0.61399 | 5.243641 | false | false | false | false |
seifolahi/HPersianUtil
|
source/HPUDate.swift
|
1
|
2358
|
//
// PersianConfig.swift
// Larzenegar
//
// Created by hamid reza seifolahi on 1/7/16.
// Copyright © 2016 Hero App Design Studio. All rights reserved.
//
import Foundation
public extension NSDate {
// If these formats does not fulfill your needs check this out for making custom formats
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
public enum SampleFormats:String{
case UltraLongDateAndTime = "eeee d MMMM *maah* yyyy *saat* hh:mm:ss a"
case LongDateTime = "eeee d MMMM yyyy *saat* hh:mm:ss a"
case LongDate = "eeee d MMMM yyyy"
case MediumDate = "d MMMM yyyy"
case ShortDate = "yyyy/MM/d"
case UltraShortDate = "yy/MM/dd"
case LongTime = "*saat* hh:mm:ss a"
case MediumTime = "hh:mm:ss"
case ShortTime = "hh:mm"
}
//convert timestamp in seconds from 1970 to shamsidate
public static func convertTimestampToShamsi(timestamp : Double,with format: String, persianNumbers : Bool = true) -> String {
let translatedFormat = format.stringByReplacingOccurrencesOfString("*saat*", withString: HPUConsts.saat)
.stringByReplacingOccurrencesOfString("*maah*", withString: HPUConsts.maah)
let date = NSDate(timeIntervalSince1970: timestamp)
let shamsiCal = NSCalendar(calendarIdentifier: NSCalendarIdentifierPersian)
let dateFormatter = NSDateFormatter()
dateFormatter.AMSymbol = HPUConsts.AMSymbol
dateFormatter.PMSymbol = HPUConsts.PMSymbol
dateFormatter.weekdaySymbols = HPUConsts.weekdaySymbols
dateFormatter.monthSymbols = HPUConsts.monthSymbols
dateFormatter.dateFormat = translatedFormat
dateFormatter.calendar = shamsiCal
if(persianNumbers){
return (String.convertEasternNumbersToPersian(dateFormatter.stringFromDate(date)))
}else{
return (dateFormatter.stringFromDate(date))
}
}
public static func getNowInShamsi(with format: String, persianNumbers : Bool = true)->String{
let nowTimestamp = NSDate().timeIntervalSince1970
return convertTimestampToShamsi(nowTimestamp, with: format, persianNumbers: persianNumbers)
}
}
|
mit
|
36d946cfab212a7a4cc8a8d6b8ae7345
| 31.736111 | 129 | 0.663555 | 4.438795 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Presentation/User Stories/Home/Router/HomeRouter.swift
|
1
|
2671
|
//
// HomeHomeRouter.swift
// AsciiArtPlayer
//
// Created by Sergey Teryokhin on 19/12/2016.
// Copyright © 2016 iMacDev. All rights reserved.
//
import QorumLogs
import Swinject
import UIKit
import ViperMcFlurry
import AVFoundation
class HomeRouter: NSObject, HomeRouterInput {
fileprivate let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
fileprivate let segueIdentifier = "ShowPlayer"
fileprivate let moduleID = "PlayerViewControllerID"
var transitionHandler: RamblerViperModuleTransitionHandlerProtocol!
/// Player with local file
var moduleFactory: RamblerViperModuleFactory {
let factory = RamblerViperModuleFactory(storyboard: mainStoryBoard, andRestorationId: moduleID)
return factory!
}
func showPlayer(delegate: RamblerViperModuleOutput?, avAsset: AVAsset) {
self.transitionHandler.openModule!(usingFactory: moduleFactory) { sourceModuleTransitionHandler, destinationModuleTransitionHandler in
let sourceVC = sourceModuleTransitionHandler as! UIViewController
let destinationVC = destinationModuleTransitionHandler as! UIViewController
sourceVC.navigationController?.pushViewController(destinationVC, animated: true)
}.thenChain { moduleInput in
guard let myModuleInput = moduleInput as? PlayerModuleInput else {
fatalError("invalid module type")
}
myModuleInput.configure(withAVAsset: avAsset)
return delegate
}
}
///MARK: Asset Picker
var assetModuleFactory: AssetLoaderTransitionFactory {
let factory = ApplicationAssembly.assembler.resolver.resolve(AssetLoaderTransitionFactory.self)
return factory!
}
func showAssetLoader(delegate: RamblerViperModuleOutput?) {
self.transitionHandler.openModule!(usingFactory: assetModuleFactory) { sourceModuleTransitionHandler, destinationModuleTransitionHandler in
let sourceVC = sourceModuleTransitionHandler as! UIViewController
let destinationVC = destinationModuleTransitionHandler as! UIViewController
sourceVC.present(destinationVC, animated: true, completion: nil)
}.thenChain { moduleInput in
guard let myModuleInput = moduleInput as? AssetLoaderModuleInput else {
fatalError("invalid module type")
}
myModuleInput.configureVideoPicker()
return delegate
}
}
func showCameraRecorder(delegate: RamblerViperModuleOutput?) {
}
}
|
mit
|
d00e46bea022f7ef7478964febe0ae7e
| 35.081081 | 147 | 0.692509 | 5.621053 | false | false | false | false |
lemberg/connfa-ios
|
Pods/SwiftDate/Sources/SwiftDate/TimePeriod/Groups/TimePeriodCollection.swift
|
1
|
8220
|
//
// TimePeriodCollection.swift
// SwiftDate
//
// Created by Daniele Margutti on 14/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
/// Sort type
///
/// - ascending: sort in ascending order
/// - descending: sort in descending order
public enum SortMode {
case ascending
case descending
}
/// Sorting type
///
/// - start: sort by start date
/// - end: sort by end date
/// - duration: sort by duration
/// - custom: sort using custom function
public enum SortType {
case start(_: SortMode)
case end(_: SortMode)
case duration(_: SortMode)
case custom(_: ((TimePeriodProtocol, TimePeriodProtocol) -> Bool))
}
/// Time period collections serve as loose sets of time periods.
/// They are unorganized unless you decide to sort them, and have their own characteristics
/// like a `start` and `end` that are extrapolated from the time periods within.
/// Time period collections allow overlaps within their set of time periods.
open class TimePeriodCollection: TimePeriodGroup {
// MARK: - Collection Manipulation
/// Append a TimePeriodProtocol to the periods array and check if the Collection's start and end should change.
///
/// - Parameter period: TimePeriodProtocol to add to the collection
public func append(_ period: TimePeriodProtocol) {
periods.append(period)
updateExtremes(period: period)
}
/// Append a TimePeriodProtocol array to the periods array and check if the Collection's
/// start and end should change.
///
/// - Parameter periodArray: TimePeriodProtocol list to add to the collection
public func append(_ periodArray: [TimePeriodProtocol]) {
for period in periodArray {
periods.append(period)
updateExtremes(period: period)
}
}
/// Append a TimePeriodGroup's periods array to the periods array of self and check if the Collection's
/// start and end should change.
///
/// - Parameter newPeriods: TimePeriodGroup to merge periods arrays with
public func append<C: TimePeriodGroup>(contentsOf newPeriods: C) {
for period in newPeriods as TimePeriodGroup {
periods.append(period)
updateExtremes(period: period)
}
}
/// Insert period into periods array at given index.
///
/// - Parameters:
/// - newElement: The period to insert
/// - index: Index to insert period at
public func insert(_ newElement: TimePeriodProtocol, at index: Int) {
periods.insert(newElement, at: index)
updateExtremes(period: newElement)
}
/// Remove from period array at the given index.
///
/// - Parameter at: The index in the collection to remove
public func remove(at: Int) {
periods.remove(at: at)
updateExtremes()
}
/// Remove all periods from period array.
public func removeAll() {
periods.removeAll()
updateExtremes()
}
// MARK: - Sorting
/// Sort elements in place using given method.
///
/// - Parameter type: sorting method
public func sort(by type: SortType) {
switch type {
case .duration(let mode): self.periods.sort(by: sortFuncDuration(mode))
case .start(let mode): self.periods.sort(by: sortFunc(byStart: true, type: mode))
case .end(let mode): self.periods.sort(by: sortFunc(byStart: false, type: mode))
case .custom(let f): self.periods.sort(by: f)
}
}
/// Generate a new `TimePeriodCollection` where items are sorted with specified method.
///
/// - Parameters:
/// - type: sorting method
/// - Returns: collection ordered by given function
public func sorted(by type: SortType) -> TimePeriodCollection {
var sortedList: [TimePeriodProtocol]!
switch type {
case .duration(let mode): sortedList = self.periods.sorted(by: sortFuncDuration(mode))
case .start(let mode): sortedList = self.periods.sorted(by: sortFunc(byStart: true, type: mode))
case .end(let mode): sortedList = self.periods.sorted(by: sortFunc(byStart: false, type: mode))
case .custom(let f): sortedList = self.periods.sorted(by: f)
}
return TimePeriodCollection(sortedList)
}
// MARK: - Collection Relationship
/// Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s
/// whose start and end dates fall completely inside the interval of the given `TimePeriod`.
///
/// - Parameter period: The period to compare each other period against
/// - Returns: Collection of periods inside the given period
public func periodsInside(period: TimePeriodProtocol) -> TimePeriodCollection {
return TimePeriodCollection(self.periods.filter({ $0.isInside(period) }))
}
// Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s containing the given date.
///
/// - Parameter date: The date to compare each period to
/// - Returns: Collection of periods intersected by the given date
public func periodsIntersected(by date: DateInRegion) -> TimePeriodCollection {
return TimePeriodCollection(self.periods.filter({ $0.contains(date: date, interval: .closed) }))
}
/// Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s
/// containing either the start date or the end date--or both--of the given `TimePeriod`.
///
/// - Parameter period: The period to compare each other period to
/// - Returns: Collection of periods intersected by the given period
public func periodsIntersected(by period: TimePeriodProtocol) -> TimePeriodCollection {
return TimePeriodCollection(self.periods.filter({ $0.intersects(with: period) }))
}
/// Returns an instance of DTTimePeriodCollection with all the time periods in the receiver that overlap a given time period.
/// Overlap with the given time period does NOT include other time periods that simply touch it.
/// (i.e. one's start date is equal to another's end date)
///
/// - Parameter period: The time period to check against the receiver's time periods.
/// - Returns: Collection of periods overlapped by the given period
public func periodsOverlappedBy(_ period: TimePeriodProtocol) -> TimePeriodCollection {
return TimePeriodCollection(self.periods.filter({ $0.overlaps(with: period) }))
}
// MARK: - Map
public func map(_ transform: (TimePeriodProtocol) throws -> TimePeriodProtocol) rethrows -> TimePeriodCollection {
var mappedArray = [TimePeriodProtocol]()
mappedArray = try periods.map(transform)
let mappedCollection = TimePeriodCollection()
for period in mappedArray {
mappedCollection.periods.append(period)
mappedCollection.updateExtremes(period: period)
}
return mappedCollection
}
// MARK: - Helpers
private func sortFuncDuration(_ type: SortMode) -> ((TimePeriodProtocol, TimePeriodProtocol) -> Bool) {
switch type {
case .ascending: return { $0.duration < $1.duration }
case .descending: return { $0.duration > $1.duration }
}
}
private func sortFunc(byStart start: Bool = true, type: SortMode) -> ((TimePeriodProtocol, TimePeriodProtocol) -> Bool) {
return {
let date0 = (start ? $0.start : $0.end)
let date1 = (start ? $1.start : $1.end)
if date0 == nil && date1 == nil {
return false
} else if date0 == nil {
return true
} else if date1 == nil {
return false
} else {
return (type == .ascending ? date1! < date0! : date0! > date1!)
}
}
}
private func updateExtremes(period: TimePeriodProtocol) {
//Check incoming period against previous start and end date
guard self.count != 1 else {
self.start = period.start
self.end = period.end
return
}
self.start = nilOrEarlier(date1: self.start, date2: period.start)
self.end = nilOrLater(date1: self.end, date2: period.end)
}
private func updateExtremes() {
guard periods.count > 0 else {
self.start = nil
self.end = nil
return
}
self.start = periods.first!.start
self.end = periods.first!.end
for i in 1..<periods.count {
self.start = nilOrEarlier(date1: self.start, date2: periods[i].start)
self.end = nilOrEarlier(date1: self.end, date2: periods[i].end)
}
}
private func nilOrEarlier(date1: DateInRegion?, date2: DateInRegion?) -> DateInRegion? {
guard date1 != nil && date2 != nil else { return nil }
return date1!.earlierDate(date2!)
}
private func nilOrLater(date1: DateInRegion?, date2: DateInRegion?) -> DateInRegion? {
guard date1 != nil && date2 != nil else { return nil }
return date1!.laterDate(date2!)
}
}
|
apache-2.0
|
ccba893acd71e2f8f10ae14a08a5307e
| 33.679325 | 126 | 0.714685 | 3.542672 | false | false | false | false |
cwwise/CWWeChat
|
CWWeChat/Expand/Extension/UIView+Frame.swift
|
2
|
2630
|
//
// UIView+Frame.swift
// CWXMPPChat
//
// Created by chenwei on 16/5/28.
// Copyright © 2016 Hilen. All rights reserved.
//
import UIKit
extension UIView {
var width: CGFloat {
get { return self.frame.size.width }
set {
var frame = self.frame
frame.size.width = newValue
self.frame = frame
}
}
var height: CGFloat {
get { return self.frame.size.height }
set {
var frame = self.frame
frame.size.height = newValue
self.frame = frame
}
}
var size: CGSize {
get { return self.frame.size }
set {
var frame = self.frame
frame.size = newValue
self.frame = frame
}
}
var origin: CGPoint {
get { return self.frame.origin }
set {
var frame = self.frame
frame.origin = newValue
self.frame = frame
}
}
var x: CGFloat {
get { return self.frame.origin.x }
set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
var y: CGFloat {
get { return self.frame.origin.y }
set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
var centerX: CGFloat {
get { return self.center.x }
set {
self.center = CGPoint(x: newValue, y: self.center.y)
}
}
var centerY: CGFloat {
get { return self.center.y }
set {
self.center = CGPoint(x: self.center.x, y: newValue)
}
}
var top : CGFloat {
get { return self.frame.origin.y }
set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
var bottom : CGFloat {
get { return frame.origin.y + frame.size.height }
set {
var frame = self.frame
frame.origin.y = newValue - self.frame.size.height
self.frame = frame
}
}
var right : CGFloat {
get { return self.frame.origin.x + self.frame.size.width }
set {
var frame = self.frame
frame.origin.x = newValue - self.frame.size.width
self.frame = frame
}
}
var left : CGFloat {
get { return self.frame.origin.x }
set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
}
|
mit
|
74a7bcff6cfac2a54f531ceda86025d8
| 22.061404 | 66 | 0.480791 | 4.226688 | false | false | false | false |
amosavian/FileProvider
|
Sources/DropboxFileProvider.swift
|
2
|
25057
|
//
// DropboxFileProvider.swift
// FileProvider
//
// Created by Amir Abbas Mousavian.
// Copyright © 2016 Mousavian. Distributed under MIT license.
//
import Foundation
#if os(macOS) || os(iOS) || os(tvOS)
import CoreGraphics
#endif
/**
Allows accessing to Dropbox stored files. This provider doesn't cache or save files internally, however you can
set `useCache` and `cache` properties to use Foundation `NSURLCache` system.
- Note: You can pass file id or rev instead of file path, e.g `"id:1234abcd"` or `"rev:1234abcd"`, to point to a file or folder by ID.
- Note: Uploading files and data are limited to 150MB, for now.
*/
open class DropboxFileProvider: HTTPFileProvider, FileProviderSharing {
override open class var type: String { return "Dropbox" }
/// Dropbox RPC API URL, which is equal with [https://api.dropboxapi.com/2/](https://api.dropboxapi.com/2/)
public let apiURL: URL
/// Dropbox contents download/upload API URL, which is equal with [https://content.dropboxapi.com/2/](https://content.dropboxapi.com/2/)
public let contentURL: URL
/**
Initializer for Dropbox provider with given client ID and Token.
These parameters must be retrieved via [OAuth2 API of Dropbox](https://www.dropbox.com/developers/reference/oauth-guide).
There are libraries like [p2/OAuth2](https://github.com/p2/OAuth2) or [OAuthSwift](https://github.com/OAuthSwift/OAuthSwift) which can facilate the procedure to retrieve token. The latter is easier to use and prefered.
- Parameter credential: a `URLCredential` object with Client ID set as `user` and Token set as `password`.
- Parameter cache: A URLCache to cache downloaded files and contents.
*/
public init(credential: URLCredential?, cache: URLCache? = nil) {
self.apiURL = URL(string: "https://api.dropboxapi.com/2/")!
self.contentURL = URL(string: "https://content.dropboxapi.com/2/")!
super.init(baseURL: nil, credential: credential, cache: cache)
}
public required convenience init?(coder aDecoder: NSCoder) {
self.init(credential: aDecoder.decodeObject(of: URLCredential.self, forKey: "credential"))
self.useCache = aDecoder.decodeBool(forKey: "useCache")
self.validatingCache = aDecoder.decodeBool(forKey: "validatingCache")
}
override open func copy(with zone: NSZone? = nil) -> Any {
let copy = DropboxFileProvider(credential: self.credential, cache: self.cache)
copy.delegate = self.delegate
copy.fileOperationDelegate = self.fileOperationDelegate
copy.useCache = self.useCache
copy.validatingCache = self.validatingCache
return copy
}
/**
Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler.
If the directory contains no entries or an error is occured, this method will return the empty array.
- Parameters:
- path: path to target directory. If empty, root will be iterated.
- completionHandler: a closure with result of directory entries or error.
- contents: An array of `FileObject` identifying the the directory entries.
- error: Error returned by system.
*/
open override func contentsOfDirectory(path: String, completionHandler: @escaping (_ contents: [FileObject], _ error: Error?) -> Void) {
let query = NSPredicate(format: "TRUEPREDICATE")
_ = searchFiles(path: path, recursive: false, query: query, foundItemHandler: nil, completionHandler: completionHandler)
}
/**
Returns a `FileObject` containing the attributes of the item (file, directory, symlink, etc.) at the path in question via asynchronous completion handler.
If the directory contains no entries or an error is occured, this method will return the empty `FileObject`.
- Parameters:
- path: path to target directory. If empty, attributes of root will be returned.
- completionHandler: a closure with result of directory entries or error.
- attributes: A `FileObject` containing the attributes of the item.
- error: Error returned by system.
*/
open override func attributesOfItem(path: String, completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) {
let url = URL(string: "files/get_metadata", relativeTo: apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .json)
let requestDictionary: [String: Any] = ["path": correctPath(path)!]
request.httpBody = Data(jsonDictionary: requestDictionary)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
var serverError: FileProviderHTTPError?
var fileObject: DropboxFileObject?
if let response = response as? HTTPURLResponse, response.statusCode >= 400 {
let code = FileProviderHTTPErrorCode(rawValue: response.statusCode)
serverError = code.flatMap { self.serverError(with: $0, path: path, data: data) }
}
if let json = data?.deserializeJSON(), let file = DropboxFileObject(json: json) {
fileObject = file
}
completionHandler(fileObject, serverError ?? error)
})
task.resume()
}
/// Returns volume/provider information asynchronously.
/// - Parameter volumeInfo: Information of filesystem/Provider returned by system/server.
open override func storageProperties(completionHandler: @escaping (_ volumeInfo: VolumeObject?) -> Void) {
let url = URL(string: "users/get_space_usage", relativeTo: apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
guard let json = data?.deserializeJSON() else {
completionHandler(nil)
return
}
let volume = VolumeObject(allValues: [:])
volume.totalCapacity = ((json["allocation"] as? NSDictionary)?["allocated"] as? NSNumber)?.int64Value ?? -1
volume.usage = (json["used"] as? NSNumber)?.int64Value ?? 0
completionHandler(volume)
})
task.resume()
}
/**
Search files inside directory using query asynchronously.
Sample predicates:
```
NSPredicate(format: "(name CONTAINS[c] 'hello') && (fileSize >= 10000)")
NSPredicate(format: "(modifiedDate >= %@)", Date())
NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder")
```
- Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate.
- Important: A file name criteria should be provided for Dropbox.
- Parameters:
- path: location of directory to start search
- recursive: Searching subdirectories of path
- query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`.
- foundItemHandler: Closure which is called when a file is found
- completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured.
- files: all files meat the `query` criteria.
- error: `Error` returned by server if occured.
- Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items.
*/
@discardableResult
open override func searchFiles(path: String, recursive: Bool, query: NSPredicate, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? {
let queryStr: String?
if query.predicateFormat == "TRUEPREDICATE" {
queryStr = nil
} else {
queryStr = query.findValue(forKey: "name", operator: .beginsWith) as? String
}
let requestHandler = self.listRequest(path: path, queryStr: queryStr, recursive: recursive)
let queryIsTruePredicate = query.predicateFormat == "TRUEPREDICATE"
return paginated(path, requestHandler: requestHandler,
pageHandler: { [weak self] (data, progress) -> (files: [FileObject], error: Error?, newToken: String?) in
guard let json = data?.deserializeJSON(), let entries = (json["entries"] ?? json["matches"]) as? [Any] else {
let err = URLError(.badServerResponse, url: self?.url(of: path))
return ([], err, nil)
}
var files = [FileObject]()
for entry in entries {
if let entry = entry as? [String: Any], let file = DropboxFileObject(json: entry), queryIsTruePredicate || query.evaluate(with: file.mapPredicate()) {
files.append(file)
progress.completedUnitCount += 1
foundItemHandler?(file)
}
}
let ncursor: String?
if let hasmore = (json["has_more"] as? NSNumber)?.boolValue, hasmore {
ncursor = json["cursor"] as? String
} else if let hasmore = (json["more"] as? NSNumber)?.boolValue, hasmore {
ncursor = (json["start"] as? Int).flatMap(String.init)
} else {
ncursor = nil
}
return (files, nil, ncursor)
}, completionHandler: completionHandler)
}
override func request(for operation: FileOperationType, overwrite: Bool = false, attributes: [URLResourceKey : Any] = [:]) -> URLRequest {
func uploadRequest(to path: String) -> URLRequest {
var requestDictionary = [String: Any]()
let url: URL = URL(string: "files/upload", relativeTo: contentURL)!
requestDictionary["path"] = correctPath(path)
requestDictionary["mode"] = (overwrite ? "overwrite" : "add")
//requestDictionary["client_modified"] = (attributes[.contentModificationDateKey] as? Date)?.format(with: .rfc3339)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .stream)
request.setValue(dropboxArgKey: requestDictionary)
return request
}
func downloadRequest(from path: String) -> URLRequest {
let url = URL(string: "files/download", relativeTo: contentURL)!
var request = URLRequest(url: url)
request = URLRequest(url: url)
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(dropboxArgKey: ["path": correctPath(path)!])
return request
}
// content operations
switch operation {
case .copy(source: let source, destination: let dest) where dest.lowercased().hasPrefix("file://"):
return downloadRequest(from: source)
case .fetch(let path):
return downloadRequest(from: path)
case .copy(source: let source, destination: let dest) where source.lowercased().hasPrefix("file://"):
return uploadRequest(to: dest)
case .modify(let path):
return uploadRequest(to: path)
default:
return self.apiRequest(for: operation, overwrite: overwrite)
}
}
func apiRequest(for operation: FileOperationType, overwrite: Bool = false) -> URLRequest {
let url: String
let sourcePath = operation.source
let destPath = operation.destination
var requestDictionary = [String: Any]()
switch operation {
case .create:
url = "files/create_folder_v2"
case .copy:
url = "files/copy_v2"
requestDictionary["allow_shared_folder"] = NSNumber(value: true)
case .move:
url = "files/move_v2"
requestDictionary["allow_shared_folder"] = NSNumber(value: true)
case .remove:
url = "files/delete_v2"
default: // modify, link, fetch
fatalError("Unimplemented operation \(operation.description) in \(#file)")
}
var request = URLRequest(url: URL(string: url, relativeTo: apiURL)!)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .json)
if let dest = correctPath(destPath) {
requestDictionary["from_path"] = correctPath(sourcePath)
requestDictionary["to_path"] = dest
} else {
requestDictionary["path"] = correctPath(sourcePath)
}
request.httpBody = Data(jsonDictionary: requestDictionary)
return request
}
override func serverError(with code: FileProviderHTTPErrorCode, path: String?, data: Data?) -> FileProviderHTTPError {
let errorDesc: String?
if let response = data?.deserializeJSON() {
errorDesc = (response["user_message"] as? String) ?? ((response["error"] as? [String: Any])?["tag"] as? String)
} else {
errorDesc = data.flatMap({ String(data: $0, encoding: .utf8) })
}
return FileProviderDropboxError(code: code, path: path ?? "", serverDescription: errorDesc)
}
override var maxUploadSimpleSupported: Int64 {
return 157_286_400 // 150MB
}
/*
fileprivate func registerNotifcation(path: String, eventHandler: (() -> Void)) {
/* There is two ways to monitor folders changing in Dropbox. Either using webooks
* which means you have to implement a server to translate it to push notifications
* or using apiv2 list_folder/longpoll method. The second one is implemeted here.
* Tough webhooks are much more efficient, longpoll is much simpler to implement!
* You can implemnt your own webhook service and replace this method accordingly.
*/
NotImplemented()
}
fileprivate func unregisterNotifcation(path: String) {
NotImplemented()
}
*/
// TODO: Implement /get_account & /get_current_account
open func publicLink(to path: String, completionHandler: @escaping ((_ link: URL?, _ attribute: FileObject?, _ expiration: Date?, _ error: Error?) -> Void)) {
let url = URL(string: "files/get_temporary_link", relativeTo: apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .json)
let requestDictionary: [String: Any] = ["path": correctPath(path)!]
request.httpBody = Data(jsonDictionary: requestDictionary)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
var serverError: FileProviderHTTPError?
var link: URL?
var fileObject: DropboxFileObject?
if let response = response as? HTTPURLResponse {
let code = FileProviderHTTPErrorCode(rawValue: response.statusCode)
serverError = code.flatMap { self.serverError(with: $0, path: path, data: data) }
if let json = data?.deserializeJSON() {
link = (json["link"] as? String).flatMap(URL.init(string:))
fileObject = (json["metadata"] as? [String: Any]).flatMap(DropboxFileObject.init(json:))
}
}
let expiration: Date? = link != nil ? Date(timeIntervalSinceNow: 4 * 60 * 60) : nil
completionHandler(link, fileObject, expiration, serverError ?? error)
})
task.resume()
}
/**
Downloads a file from remote url to designated path asynchronously.
- Parameters:
- remoteURL: a valid remote url to file.
- to: Destination path of file, including file/directory name.
- completionHandler: a closure with result of directory entries or error.
- `jobId`: Job ID returned by Dropbox to monitor the copy/download progress.
- `attribute`: A `FileObject` containing the attributes of the item.
- `error`: Error returned by Dropbox.
*/
open func copyItem(remoteURL: URL, to toPath: String, completionHandler: @escaping ((_ jobId: String?, _ attribute: DropboxFileObject?, _ error: Error?) -> Void)) {
if remoteURL.isFileURL {
completionHandler(nil, nil, URLError(.badURL, url: remoteURL))
return
}
let url = URL(string: "files/save_url", relativeTo: apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .json)
let requestDictionary: [String: Any] = ["path": correctPath(toPath)!, "url" : remoteURL.absoluteString]
request.httpBody = Data(jsonDictionary: requestDictionary)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
var serverError: FileProviderHTTPError?
var jobId: String?
var fileObject: DropboxFileObject?
if let response = response as? HTTPURLResponse {
let code = FileProviderHTTPErrorCode(rawValue: response.statusCode)
serverError = code.flatMap { self.serverError(with: $0, path: toPath, data: data) }
if let json = data?.deserializeJSON() {
jobId = json["async_job_id"] as? String
fileObject = (json["metadata"] as? [String: Any]).flatMap(DropboxFileObject.init(json:))
}
}
completionHandler(jobId, fileObject, serverError ?? error)
})
task.resume()
}
/**
Copys a file from another user Dropbox storage to designated path asynchronously.
- Parameters:
- reference: a valid reference string from another user via `copy_reference/get` REST method.
- to: Destination path of file, including file/directory name.
- completionHandler: If an error parameter was provided, a presentable `Error` will be returned.
*/
open func copyItem(reference: String, to toPath: String, completionHandler: SimpleCompletionHandler) {
let url = URL(string: "files/copy_reference/save", relativeTo: apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .json)
let requestDictionary: [String: Any] = ["path": correctPath(toPath)!, "copy_reference" : reference ]
request.httpBody = Data(jsonDictionary: requestDictionary)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
var serverError: FileProviderHTTPError?
if let response = response as? HTTPURLResponse {
let code = FileProviderHTTPErrorCode(rawValue: response.statusCode)
serverError = code.flatMap { self.serverError(with: $0, path: toPath, data: data) }
}
completionHandler?(serverError ?? error)
})
task.resume()
}
}
extension DropboxFileProvider: ExtendedFileProvider {
open func propertiesOfFileSupported(path: String) -> Bool {
let fileExt = path.pathExtension.lowercased()
switch fileExt {
case "jpg", "jpeg", "bmp", "gif", "png", "tif", "tiff":
return true
/*case "mp3", "aac", "m4a":
return true*/
case "mp4", "mpg", "3gp", "mov", "avi":
return true
default:
return false
}
}
@discardableResult
open func propertiesOfFile(path: String, completionHandler: @escaping ((_ propertiesDictionary: [String : Any], _ keys: [String], _ error: Error?) -> Void)) -> Progress? {
let url = URL(string: "files/get_metadata", relativeTo: apiURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(authentication: credential, with: .oAuth2)
request.setValue(contentType: .json)
let requestDictionary: [String: Any] = ["path": correctPath(path)!, "include_media_info": NSNumber(value: true)]
request.httpBody = Data(jsonDictionary: requestDictionary)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
var serverError: FileProviderHTTPError?
var dic = [String: Any]()
var keys = [String]()
if let response = response as? HTTPURLResponse {
let code = FileProviderHTTPErrorCode(rawValue: response.statusCode)
serverError = code.flatMap { self.serverError(with: $0, path: path, data: data) }
if let json = data?.deserializeJSON(), let properties = (json["media_info"] as? [String: Any])?["metadata"] as? [String: Any] {
(dic, keys) = self.mapMediaInfo(properties)
}
}
completionHandler(dic, keys, serverError ?? error)
})
task.resume()
return nil
}
#if os(macOS) || os(iOS) || os(tvOS)
open func thumbnailOfFileSupported(path: String) -> Bool {
switch path.pathExtension.lowercased() {
case "jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff":
return true
case "doc", "docx", "docm", "xls", "xlsx", "xlsm":
return false
case "ppt", "pps", "ppsx", "ppsm", "pptx", "pptm":
return false
case "rtf":
return false
default:
return false
}
}
/// Default value for dimension is 64x64, according to Dropbox documentation
@discardableResult
open func thumbnailOfFile(path: String, dimension: CGSize?, completionHandler: @escaping ((_ image: ImageClass?, _ error: Error?) -> Void)) -> Progress? {
let url: URL
let thumbAPI: Bool
switch path.pathExtension.lowercased() {
case "jpg", "jpeg", "gif", "bmp", "png", "tif", "tiff":
url = URL(string: "files/get_thumbnail", relativeTo: contentURL)!
thumbAPI = true
case "doc", "docx", "docm", "xls", "xlsx", "xlsm":
fallthrough
case "ppt", "pps", "ppsx", "ppsm", "pptx", "pptm":
fallthrough
case "rtf":
url = URL(string: "files/get_preview", relativeTo: contentURL)!
thumbAPI = false
default:
return nil
}
var request = URLRequest(url: url)
request.setValue(authentication: credential, with: .oAuth2)
var requestDictionary: [String: Any] = ["path": path]
if thumbAPI {
requestDictionary["format"] = "jpeg"
let size: String
switch dimension?.height ?? 64 {
case 0...32: size = "w32h32"
case 33...64: size = "w64h64"
case 65...128: size = "w128h128"
case 129...480: size = "w640h480"
default: size = "w1024h768"
}
requestDictionary["size"] = size
}
request.setValue(dropboxArgKey: requestDictionary)
let task = self.session.dataTask(with: request, completionHandler: { (data, response, error) in
var image: ImageClass? = nil
if let r = response as? HTTPURLResponse, let result = r.allHeaderFields["Dropbox-API-Result"] as? String, let jsonResult = result.deserializeJSON() {
if jsonResult["error"] != nil {
completionHandler(nil, URLError(.cannotDecodeRawData, url: self.url(of: path)))
}
}
if let data = data {
if data.isPDF, let pageImage = DropboxFileProvider.convertToImage(pdfData: data, maxSize: dimension) {
image = pageImage
} else if let contentType = (response as? HTTPURLResponse)?.allHeaderFields["Content-Type"] as? String, contentType.contains("text/html") {
// TODO: Implement converting html returned type of get_preview to image
} else {
if let dimension = dimension {
image = DropboxFileProvider.scaleDown(data: data, toSize: dimension)
} else {
}
}
}
completionHandler(image, error)
})
task.resume()
return nil
}
#endif
}
|
mit
|
77e635d3d78affcdc87f383af232cd01
| 48.129412 | 223 | 0.618534 | 4.709774 | false | false | false | false |
tjw/swift
|
test/stdlib/UIKit.swift
|
1
|
9026
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -swift-version 3 %s -o %t/a.out3 && %target-run %t/a.out3
// RUN: %target-build-swift -swift-version 4 %s -o %t/a.out4 && %target-run %t/a.out4
// REQUIRES: executable_test
// UNSUPPORTED: OS=macosx
// REQUIRES: objc_interop
import UIKit
import StdlibUnittest
import StdlibUnittestFoundationExtras
#if swift(>=4)
let UIKitTests = TestSuite("UIKit_Swift4")
#else
let UIKitTests = TestSuite("UIKit_Swift3")
#endif
#if !os(watchOS) && !os(tvOS)
private func printDevice(_ o: UIDeviceOrientation) -> String {
var s = "\(o.isPortrait) \(UIDeviceOrientationIsPortrait(o)), "
s += "\(o.isLandscape) \(UIDeviceOrientationIsLandscape(o)), "
s += "\(o.isFlat), \(o.isValidInterfaceOrientation) "
s += "\(UIDeviceOrientationIsValidInterfaceOrientation(o))"
return s
}
private func printInterface(_ o: UIInterfaceOrientation) -> String {
return "\(o.isPortrait) \(UIInterfaceOrientationIsPortrait(o)), " +
"\(o.isLandscape) \(UIInterfaceOrientationIsLandscape(o))"
}
UIKitTests.test("UIDeviceOrientation") {
expectEqual("false false, false false, false, false false",
printDevice(.unknown))
expectEqual("true true, false false, false, true true",
printDevice(.portrait))
expectEqual("true true, false false, false, true true",
printDevice(.portraitUpsideDown))
expectEqual("false false, true true, false, true true",
printDevice(.landscapeLeft))
expectEqual("false false, true true, false, true true",
printDevice(.landscapeRight))
expectEqual("false false, false false, true, false false",
printDevice(.faceUp))
expectEqual("false false, false false, true, false false",
printDevice(.faceDown))
}
UIKitTests.test("UIInterfaceOrientation") {
expectEqual("false false, false false",
printInterface(.unknown))
expectEqual("true true, false false",
printInterface(.portrait))
expectEqual("true true, false false",
printInterface(.portraitUpsideDown))
expectEqual("false false, true true",
printInterface(.landscapeLeft))
expectEqual("false false, true true",
printInterface(.landscapeRight))
}
#endif
UIKitTests.test("UIEdgeInsets") {
let insets = [
UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.0, right: 4.0),
UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.1, right: 4.0),
UIEdgeInsets.zero
]
checkEquatable(insets, oracle: { $0 == $1 })
}
UIKitTests.test("UIOffset") {
let offsets = [
UIOffset(horizontal: 1.0, vertical: 2.0),
UIOffset(horizontal: 1.0, vertical: 3.0),
UIOffset.zero
]
checkEquatable(offsets, oracle: { $0 == $1 })
}
UIKitTests.test("UIFont.Weight") {
guard #available(iOS 8.2, *) else { return }
#if swift(>=4) // Swift 4
let regularFontWeight: UIFont.Weight = .regular
expectTrue(regularFontWeight == .regular)
expectTrue(regularFontWeight > .light)
expectTrue(regularFontWeight < .heavy)
expectTrue(regularFontWeight + 0.1 == 0.1 + regularFontWeight)
#else // Swift 3
let regularFontWeight: UIFontWeight = UIFontWeightRegular
expectTrue(regularFontWeight == UIFontWeightRegular)
expectTrue(regularFontWeight > UIFontWeightLight)
expectTrue(regularFontWeight < UIFontWeightHeavy)
expectTrue(regularFontWeight + 0.1 == 0.1 + UIFontWeightRegular)
#endif
}
#if !os(watchOS)
UIKitTests.test("UILayoutPriority") {
#if swift(>=4) // Swift 4
let lowLayoutPriority: UILayoutPriority = .defaultLow
let highLayoutPriority: UILayoutPriority = .defaultHigh
expectTrue(lowLayoutPriority < highLayoutPriority)
expectTrue(lowLayoutPriority + 2.0 == UILayoutPriority(lowLayoutPriority.rawValue + 2.0))
expectTrue(2.0 + lowLayoutPriority == UILayoutPriority(lowLayoutPriority.rawValue + 2.0))
expectTrue(lowLayoutPriority - 2.0 == UILayoutPriority(lowLayoutPriority.rawValue - 2.0))
expectTrue(highLayoutPriority - lowLayoutPriority == highLayoutPriority.rawValue - lowLayoutPriority.rawValue)
expectTrue(lowLayoutPriority + (highLayoutPriority - lowLayoutPriority) == highLayoutPriority)
var mutablePriority = lowLayoutPriority
mutablePriority -= 1.0
mutablePriority += 2.0
expectTrue(mutablePriority == lowLayoutPriority + 1.0)
let priorotyRange = lowLayoutPriority...highLayoutPriority
expectTrue(priorotyRange.contains(.defaultLow))
expectFalse(priorotyRange.contains(.required))
#else // Swift 3
let lowLayoutPriority: UILayoutPriority = UILayoutPriorityDefaultLow
let highLayoutPriority: UILayoutPriority = UILayoutPriorityDefaultHigh
expectTrue(lowLayoutPriority < highLayoutPriority)
expectTrue(2.0 + lowLayoutPriority == lowLayoutPriority + 2.0)
expectTrue(lowLayoutPriority + (highLayoutPriority - lowLayoutPriority) == highLayoutPriority)
var mutablePriority = lowLayoutPriority
mutablePriority -= 1.0
mutablePriority += 2.0
expectTrue(mutablePriority == lowLayoutPriority + 1.0)
#endif
}
#endif
#if !os(watchOS)
class TestChildView : UIView, CustomPlaygroundQuickLookable {
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
}
var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text("child")
}
}
UIKitTests.test("CustomPlaygroundQuickLookable") {
switch PlaygroundQuickLook(reflecting: TestChildView()) {
case .text("child"): break
default: expectUnreachable(
"TestChildView custom quicklookable should have been invoked")
}
}
#endif
UIKitTests.test("NSValue bridging") {
expectBridgeToNSValue(UIEdgeInsets(top: 17, left: 38, bottom: 6, right: 79),
nsValueInitializer: { NSValue(uiEdgeInsets: $0) },
nsValueGetter: { $0.uiEdgeInsetsValue },
equal: (==))
expectBridgeToNSValue(UIOffset(horizontal: 17, vertical: 38),
nsValueInitializer: { NSValue(uiOffset: $0) },
nsValueGetter: { $0.uiOffsetValue },
equal: (==))
}
#if os(iOS) || os(tvOS)
UIKitTests.test("UIContentSizeCategory comparison") {
if #available(iOS 11.0, tvOS 11.0, *) {
expectTrue(UIContentSizeCategory.large < UIContentSizeCategory.extraLarge)
expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.extraLarge)
expectFalse(UIContentSizeCategory.large >= UIContentSizeCategory.extraLarge)
expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.extraLarge)
expectFalse(UIContentSizeCategory.large == UIContentSizeCategory.extraLarge)
expectTrue(UIContentSizeCategory.extraLarge > UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.extraLarge >= UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.extraLarge < UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.extraLarge <= UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.extraLarge == UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.large == UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.large >= UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.large)
expectFalse(UIContentSizeCategory.large < UIContentSizeCategory.large)
expectTrue(UIContentSizeCategory.accessibilityExtraExtraExtraLarge.isAccessibilityCategory)
expectFalse(UIContentSizeCategory.extraSmall.isAccessibilityCategory)
}
}
#endif
#if os(iOS) || os(watchOS) || os(tvOS)
UIKitTests.test("UIFontMetrics scaling") {
if #available(iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
let metrics = UIFontTextStyle.headline.metrics
expectTrue(metrics != nil)
}
}
#endif
#if os(iOS) || os(tvOS)
UIKitTests.test("UIFocusEnvironment") {
if #available(iOS 11.0, tvOS 11.0, *) {
let item1 = UIView()
let item2 = UIView()
_ = item1.contains(item2)
_ = item1.isFocused
}
}
#endif
#if os(iOS)
UIKitTests.test("NSItemProviderReadingWriting support") {
if #available(iOS 11.0, *) {
func f<T : UIDragDropSession>(session: T) {
_ = session.canLoadObjects(ofClass: String.self)
_ = session.canLoadObjects(ofClass: URL.self)
}
func g<T : UIDropSession>(session: T) {
_ = session.loadObjects(ofClass: String.self) { _ in ()}
_ = session.loadObjects(ofClass: URL.self) { _ in () }
}
let pc0 = UIPasteConfiguration(forAccepting: String.self)
let pc1 = UIPasteConfiguration(forAccepting: URL.self)
pc0.addTypeIdentifiers(forAccepting: URL.self)
pc1.addTypeIdentifiers(forAccepting: String.self)
var pb = UIPasteboard.general
pb.setObjects(["Hello"])
pb.setObjects([URL(string: "https://www.apple.com")!])
pb.setObjects(["Hello"], localOnly: true, expirationDate: nil)
pb.setObjects([URL(string: "https://www.apple.com")!], localOnly: true, expirationDate: nil)
}
}
#endif
runAllTests()
|
apache-2.0
|
a689542bf6597266ce4f1a0d7eb4daab
| 34.257813 | 114 | 0.710835 | 4.528851 | false | true | false | false |
zapdroid/RXWeather
|
Weather/CityPresenter.swift
|
1
|
2246
|
//
// CityPresenter.swift
// RXWeather
//
// Created by Zafer Caliskan on 02/06/2017.
// Copyright © 2017 Boran ASLAN. All rights reserved.
//
import Foundation
import CoreLocation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class CityPresenter: BasePresenter {
// MARK: - Observable Variables
let cityName = BehaviorSubject<String>.init(value: "")
let icon = BehaviorSubject<String>.init(value: "")
let temperature = BehaviorSubject<String>.init(value: "")
let precipitationProbability = BehaviorSubject<String>.init(value: "")
let humidity = BehaviorSubject<String>.init(value: "")
let windSpeed = BehaviorSubject<String>.init(value: "")
let forecasts = BehaviorSubject<[Forecast]>.init(value: [])
// MARK: - Properties
private var weather: Weather!
// MARK: - Dependencies
fileprivate var interactor: CityInteractorProtocol
// MARK: - Initialization
init(interactor: CityInteractorProtocol) {
self.interactor = interactor
super.init()
}
func setWeather(weather: Weather) {
self.weather = weather
loadView()
_ = compositeDisposable.insert(observe5DayForecast())
}
// MARK: - Business
fileprivate func loadView() {
cityName.onNext(weather.cityName)
icon.onNext(weather.icon)
temperature.onNext(String(format: "%.0f", weather.temperature) + "°")
precipitationProbability.onNext(String(format: "%.0f", weather.precipitationProbability))
humidity.onNext(String(format: "%.0f", weather.humidity))
windSpeed.onNext(String(format: "%.0f", weather.windSpeed))
}
// MARK: - Observables
fileprivate func observe5DayForecast() -> Disposable {
let location = CLLocation(latitude: weather.lat, longitude: weather.lon)
return interactor.get5DayWeatherForecast(location: location)
.subscribe(onNext: { result in
switch result {
case let .success(forecastList):
self.forecasts.onNext(forecastList)
case let .failure(weatherError):
self.showWarningAlert.onNext(weatherError.rawValue)
}
})
}
}
|
mit
|
22db6435314aee41276efeaf3d19f018
| 27.769231 | 97 | 0.647504 | 4.607803 | false | false | false | false |
dllewellyn/iOS-Networking-Scheduler
|
NetworkingScheduler/ScheduleAssistant.swift
|
1
|
1512
|
//
// ScheduleAssistant.swift
// NetworkingScheduler
//
// Created by Daniel Llewellyn on 14/04/16.
// Copyright © 2016 Daniel Llewellyn. All rights reserved.
//
import Foundation
public class ScheduleAssistant {
// Static instance
static var instance : ScheduleAssistant?
// Started
private var started : Bool = false
/**
Get the instance
*/
public class func sharedManager() -> ScheduleAssistant {
if (instance == nil)
{
instance = ScheduleAssistant.init()
}
return instance!
}
/**
Start the schedule assistant
*/
public func start() {
// Avoid double starts
if (!started)
{
started = true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.run()
})
}
}
/**
Stop the schedule assistant
*/
public func stop() {
if (started)
{
started = false;
}
}
/**
This function needs to continously try and execute the schedule function
*/
private func run() {
while (started)
{
let schedule : Schedule = Schedule.sharedManager()
if schedule.scheduleList.count > 0
{
schedule.executeAllCallbacks()
}
sleep(1)
}
}
}
|
apache-2.0
|
1310f276a1d0833243eeeb79174ac8de
| 19.432432 | 92 | 0.499007 | 5.087542 | false | false | false | false |
a7ex/ServicesFromWSDL
|
ServicesFromWSDL/Exporter/XML2JavaFiles.swift
|
1
|
2992
|
//
// XML2JavaFiles.swift
// SwiftDTO
//
// Created by Alex da Franca on 08.06.17.
// Copyright © 2017 Farbflash. All rights reserved.
//
import Foundation
class XML2JavaFiles: BaseExporter, DTOFileGenerator {
override func generateServiceCode() -> String? {
let filename = parser.serviceName
var classString = parser.headerStringFor(filename: filename, outputType: .java)
classString += "\npackage data.api.service.SoapServices.GeneratedFiles;"
classString += "\n"
classString += "\nimport component.module.JsonModule;"
classString += "\nimport data.api.model.GeneratedFiles.*;"
classString += "\nimport data.api.service.SoapServices.BaseSoapService;"
classString += "\nimport rx.Observable;"
classString += "\n"
classString += "\npublic class \(filename) extends BaseSoapService {\n"
classString += "\n"
let indent = " "
classString += "\n\(indent)public \(filename)(JsonModule jsonModule) {"
classString += "\n\(indent)\(indent)super(jsonModule);\n\(indent)}"
// we sort the functions alphabetically
// otherwise they come in random order and so it is difficult to track changes...
let sortedServices = parser.services.sorted()
for service in sortedServices {
var hasInput = false
let inputTypeResolved: String
classString += "\n\(indent)public Observable<Object> \(service.name)("
if let inputType = service.input?.type,
!inputType.isEmpty {
//swiftlint:disable:next force_unwrapping
inputTypeResolved = inputType.components(separatedBy: ":").last!.capitalizedFirst
classString += "\(inputTypeResolved) request) {\n"
hasInput = true
} else {
classString += ") {\n"
inputTypeResolved = "null"
}
classString += "\(indent)\(indent)return startRequest(\"\(parser.serviceIdentifier)\", \"\(service.name)\""
if hasInput {
classString += ", request.asParameterMap()"
} else {
classString += ", null"
}
if let outputType = service.output?.type,
!outputType.isEmpty {
//swiftlint:disable:next force_unwrapping
let outputTypeResolved = outputType.components(separatedBy: ":").last!
.capitalizedFirst
classString += ", \(outputTypeResolved).class"
} else {
classString += ", null"
}
classString += ");\n"
classString += "\(indent)}"
}
classString += "\n}"
return classString
}
override func fileTypeExtension() -> OutputType {
// Override 'fileTypeExtension()' in your concrete subclass of BaseExporter!
// default type is swift
return .java
}
}
|
apache-2.0
|
f11775eea8cd2dc753487611a3038d40
| 35.925926 | 119 | 0.579071 | 5.01005 | false | false | false | false |
pavellitvinko/RubyParser
|
parser/Swift/swComment.swift
|
1
|
945
|
//
// Comment.swift
// parser
//
// Created by Pavel Litvinko on 26.11.14.
// Copyright (c) 2014 Pavel Litvinko. All rights reserved.
//
import Foundation
import ExSwift
class SwiftComment: Statement {
override func test(line: String, reader: StreamReader) -> Bool {
return isSingleLineComment(line) || isMultilineComment(line, reader)
}
func isSingleLineComment(line: String) -> Bool{
// \/\/
return line =~ "\\/\\/"
}
func isMultilineComment(line: String, _ reader: StreamReader) -> Bool{
// \/\*
if line =~ "\\/\\*" {
var endFound = false
while let s = reader.nextLine() {
//\*\/
if s =~ "\\*\\/" {
endFound = true
break
}
}
if endFound {
return true
}
}
return false
}
}
|
mit
|
98e86b82b9ba364573f69a1e54462c92
| 22.04878 | 76 | 0.475132 | 4.375 | false | false | false | false |
6ag/BaoKanIOS
|
BaoKanIOS/Classes/Utils/JFNewsDALManager.swift
|
1
|
15394
|
//
// JFNewsDALManager.swift
// LiuAGeIOS
//
// Created by zhoujianfeng on 16/6/12.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
import SwiftyJSON
/// DAL: data access layer 数据访问层
class JFNewsDALManager: NSObject {
static let shareManager = JFNewsDALManager()
/// 过期时间间隔 从缓存开始计时,单位秒 7天
fileprivate let timeInterval: TimeInterval = 86400 * 7
/**
在退出到后台的时候,根据缓存时间自动清除过期的缓存数据
*/
func clearCacheData() {
// 计算过期时间
let overDate = Date(timeIntervalSinceNow: -timeInterval)
// print("时间低于 \(overDate) 的都清除")
// 记录时间格式 2016-06-13 02:29:37
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let overString = df.string(from: overDate)
// 生成sql语句
let sql = "DELETE FROM \(NEWS_LIST_HOME_TOP) WHERE createTime < '\(overString)';" +
"DELETE FROM \(NEWS_LIST_HOME_LIST) WHERE createTime < '\(overString)';" +
"DELETE FROM \(NEWS_LIST_OTHER_TOP) WHERE createTime < '\(overString)';" +
"DELETE FROM \(NEWS_LIST_OTHER_LIST) WHERE createTime < '\(overString)';" +
"DELETE FROM \(NEWS_CONTENT) WHERE createTime < '\(overString)';"
JFSQLiteManager.shareManager.dbQueue.inDatabase { (db) -> Void in
if (db?.executeStatements(sql))! {
// print("清除缓存数据成功")
}
}
}
}
// MARK: - 搜索关键词数据管理
extension JFNewsDALManager {
/**
从本地查询搜索关键词列表数据
- parameter keyboard: 关键词
- parameter finished: 数据回调
*/
func loadSearchKeyListFromLocation(_ keyboard: String, finished: @escaping (_ success: Bool, _ result: [[String : AnyObject]]?, _ error: NSError?) -> ()) {
// 字符不能少于1个
if keyboard.characters.count == 0 {
finished(true, [[String : AnyObject]](), nil)
return
}
let sql = "select * from \(SEARCH_KEYBOARD) where keyboard like '%\(keyboard)%' or pinyin like '%\(keyboard)%' order by num DESC limit 10";
JFSQLiteManager.shareManager.dbQueue.inDatabase { (db) in
var array = [[String : AnyObject]]()
let result = try! db?.executeQuery(sql, values: nil)
while (result?.next())! {
let keyboard = result?.string(forColumn: "keyboard")
let pinyin = result?.string(forColumn: "pinyin")
let num = result?.int(forColumn: "num")
let dict: [String : AnyObject] = [
"keyboard" : keyboard as AnyObject,
"pinyin" : pinyin as AnyObject,
"num" : Int(num!) as AnyObject
]
array.append(dict)
}
finished(true, array, nil)
}
}
/**
更新本地搜索关键词列表数据到本地 - 这个方法是定期更新的哈
*/
func updateSearchKeyListData() {
JFSQLiteManager.shareManager.dbQueue.inDatabase { (db) in
if (db?.executeStatements("DELETE FROM \(SEARCH_KEYBOARD);"))! {
// print("清空表成功")
JFNetworkTool.shareNetworkTool.get(SEARCH_KEY_LIST, parameters: nil) { (status, result, tipString) in
switch status {
case .success:
guard let successResult = result?["data"] else {
return
}
let array = successResult.arrayObject as! [[String : AnyObject]]
let sql = "INSERT INTO \(SEARCH_KEYBOARD) (keyboard, pinyin, num) VALUES (?, ?, ?)"
JFSQLiteManager.shareManager.dbQueue.inTransaction { (db, rollback) in
for dict in array {
// 拼音有可能转换失败
guard let pinyin = dict["pinyin"] as? String else {continue}
let keyboard = dict["keyboard"] as! String
let num = Int(dict["num"] as! String)!
if (db?.executeUpdate(sql, withArgumentsIn: [keyboard, pinyin, num]))! {
// print("缓存数据成功 - \(keyboard)")
} else {
// print("缓存数据失败 - \(keyboard)")
// rollback?.memory = true
break
}
}
}
case .unusual:
break
case .failure:
break
}
}
} else {
print("清空表失败")
}
}
}
}
// MARK: - 资讯列表数据管理
extension JFNewsDALManager {
/**
清除资讯列表缓存
- parameter classid: 要清除的分类id
*/
func cleanCache(_ classid: Int) {
var sql = ""
if classid == 0 {
sql = "DELETE FROM \(NEWS_LIST_HOME_TOP); DELETE FROM \(NEWS_LIST_HOME_LIST);"
} else {
sql = "DELETE FROM \(NEWS_LIST_OTHER_TOP) WHERE classid=\(classid); DELETE FROM \(NEWS_LIST_OTHER_LIST) WHERE classid=\(classid);"
}
JFSQLiteManager.shareManager.dbQueue.inDatabase { (db) in
if (db?.executeStatements(sql))! {
// print("清空表成功 classid = \(classid)")
} else {
// print("清空表失败 classid = \(classid)")
}
}
}
/**
加载资讯列表数据
- parameter classid: 资讯分类id
- parameter pageIndex: 加载分页
- parameter type: 1为资讯列表 2为资讯幻灯片
- parameter finished: 数据回调
*/
func loadNewsList(_ table: String, classid: Int, pageIndex: Int, type: Int, finished: @escaping (_ result: JSON?, _ error: NSError?) -> ()) {
// 先从本地加载数据
loadNewsListFromLocation(classid, pageIndex: pageIndex, type: type) { (status, result, tipString) in
if status == .success {
finished(result, nil)
// print("加载了本地数据 \(result)")
return
}
// 本地没有数据才从网络中加载
JFNetworkTool.shareNetworkTool.loadNewsListFromNetwork(table, classid: classid, pageIndex: pageIndex, type: type) { (status, result, tipString) in
switch status {
case .success:
// 缓存数据到本地
self.saveNewsListData(classid, data: result!["data"], type: type)
finished(result!["data"], nil)
case .unusual:
finished(nil, nil)
case .failure:
finished(nil, nil)
}
}
}
}
/**
从本地加载资讯列表数据
- parameter classid: 资讯分类id
- parameter pageIndex: 加载分页
- parameter finished: 数据回调
*/
fileprivate func loadNewsListFromLocation(_ classid: Int, pageIndex: Int, type: Int, finished: @escaping NetworkFinished) {
var sql = ""
if type == 1 {
// 计算分页
let pre_count = (pageIndex - 1) * 20
let oneCount = 20
if classid == 0 {
sql = "SELECT * FROM \(NEWS_LIST_HOME_LIST) ORDER BY id ASC LIMIT \(pre_count), \(oneCount)"
} else {
sql = "SELECT * FROM \(NEWS_LIST_OTHER_LIST) WHERE classid=\(classid) ORDER BY id ASC LIMIT \(pre_count), \(oneCount)"
}
} else {
if classid == 0 {
sql = "SELECT * FROM \(NEWS_LIST_HOME_TOP) ORDER BY id ASC LIMIT 0, 3"
} else {
sql = "SELECT * FROM \(NEWS_LIST_OTHER_TOP) WHERE classid=\(classid) ORDER BY id ASC LIMIT 0, 3"
}
}
JFSQLiteManager.shareManager.dbQueue.inDatabase { (db) in
var array = [JSON]()
let result = try! db?.executeQuery(sql, values: nil)
while (result?.next())! {
let newsJson = result?.string(forColumn: "news")
let json = JSON.parse(string: newsJson!)
array.append(json)
}
if array.count > 0 {
finished(.success, JSON(array), nil)
} else {
finished(.failure, nil, nil)
}
}
}
/**
缓存资讯列表数据到本地
- parameter data: json数据
*/
fileprivate func saveNewsListData(_ saveClassid: Int, data: JSON, type: Int) {
var sql = ""
if type == 1 {
if saveClassid == 0 {
sql = "INSERT INTO \(NEWS_LIST_HOME_LIST) (classid, news) VALUES (?, ?)"
} else {
sql = "INSERT INTO \(NEWS_LIST_OTHER_LIST) (classid, news) VALUES (?, ?)"
}
} else {
if saveClassid == 0 {
sql = "INSERT INTO \(NEWS_LIST_HOME_TOP) (classid, news) VALUES (?, ?)"
} else {
sql = "INSERT INTO \(NEWS_LIST_OTHER_TOP) (classid, news) VALUES (?, ?)"
}
}
JFSQLiteManager.shareManager.dbQueue.inTransaction { (db, rollback) in
guard let array = data.arrayObject as! [[String : AnyObject]]? else {
return
}
// 每一个字典是一条资讯
for dict in array {
// 资讯分类id
let classid = Int(dict["classid"] as! String)!
// 单条资讯json数据
let newsData = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0))
let newsJson = String(data: newsData, encoding: String.Encoding.utf8)!
if (db?.executeUpdate(sql, withArgumentsIn: [classid, newsJson]))! {
// print("缓存数据成功 - \(classid)")
} else {
// print("缓存数据失败 - \(classid)")
// rollback?.memory = true
break
}
}
}
}
}
// MARK: - 资讯正文数据管理
extension JFNewsDALManager {
/**
加载资讯列表数据
- parameter classid: 资讯分类id
- parameter pageIndex: 加载分页
- parameter type: 1为资讯列表 2为资讯幻灯片
- parameter finished: 数据回调
*/
func loadNewsDetail(_ classid: Int, id: Int, finished: @escaping (_ result: JSON?, _ error: NSError?) -> ()) {
loadNewsDetailFromLocation(classid, id: id) { (status, result, tipString) in
// 本地有数据直接返回
if status == .success {
finished(result, nil)
return
}
JFNetworkTool.shareNetworkTool.loadNewsDetailFromNetwork(classid, id: id, finished: { (status, result, tipString) in
switch status {
case .success:
// 缓存数据到本地
self.saveNewsDetailData(classid, id: id, data: result!["data"])
finished(result!["data"], nil)
case .unusual:
finished(nil, nil)
case .failure:
finished(nil, nil)
}
})
}
}
/**
从本地加载(资讯正文)数据
- parameter classid: 资讯分类id
- parameter id: 资讯id
- parameter finished: 数据回调
*/
fileprivate func loadNewsDetailFromLocation(_ classid: Int, id: Int, finished: @escaping NetworkFinished) {
let sql = "SELECT * FROM \(NEWS_CONTENT) WHERE id=\(id) AND classid=\(classid) LIMIT 1;"
JFSQLiteManager.shareManager.dbQueue.inDatabase { (db) in
let result = try! db?.executeQuery(sql, values: nil)
while (result?.next())! {
let newsJson = result?.string(forColumn: "news")
let json = JSON.parse(string: newsJson!)
finished(.success, json, nil)
// print("从缓存中取正文数据 \(json)")
result?.close()
return
}
finished(.failure, nil, nil)
}
}
/**
缓存资讯正文数据到本地
- parameter classid: 资讯分类id
- parameter id: 资讯id
- parameter data: JSON数据 data = [content : ..., otherLink: [...]]
*/
fileprivate func saveNewsDetailData(_ classid: Int, id: Int, data: JSON) {
let sql = "INSERT INTO \(NEWS_CONTENT) (id, classid, news) VALUES (?, ?, ?)"
JFSQLiteManager.shareManager.dbQueue.inTransaction { (db, rollback) in
guard let dict = data.dictionaryObject else {
return
}
// 单条资讯json数据
let newsData = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0))
let newsJson = String(data: newsData, encoding: String.Encoding.utf8)!
if (db?.executeUpdate(sql, withArgumentsIn: [id, classid, newsJson]))! {
// print("缓存数据成功 - \(classid)")
} else {
// print("缓存数据失败 - \(classid)")
rollback?.pointee = true
}
}
}
}
// MARK: - 评论数据管理
extension JFNewsDALManager {
func loadCommentList(_ classid: Int, id: Int, pageIndex: Int, pageSize: Int, finished: @escaping (_ result: JSON?, _ error: NSError?) -> ()) {
// 评论不做数据缓存,直接从网络请求
JFNetworkTool.shareNetworkTool.loadCommentListFromNetwork(classid, id: id, pageIndex: pageIndex, pageSize: pageSize) { (status, result, tipString) in
if status == .success {
finished(result!["data"], nil)
} else {
finished(nil, nil)
}
}
}
}
|
apache-2.0
|
fe14cf5ea2ae7f3c2961dfc9dfeb0521
| 32.800469 | 159 | 0.470449 | 4.7148 | false | false | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/SavedPageSpotlightManager.swift
|
1
|
4132
|
import UIKit
import MobileCoreServices
import CoreSpotlight
import CocoaLumberjackSwift
extension URL {
var searchableItemAttributes: CSSearchableItemAttributeSet? {
guard wikiResourcePath != nil else {
return nil
}
guard let title = self.wmf_title else {
return nil
}
let components = title.components(separatedBy: " ")
let searchableItem = CSSearchableItemAttributeSet(itemContentType: kUTTypeInternetLocation as String)
searchableItem.keywords = ["Wikipedia","Wikimedia","Wiki"] + components
searchableItem.title = self.wmf_title
searchableItem.displayName = self.wmf_title
searchableItem.identifier = NSURL.wmf_desktopURL(for: self as URL)?.absoluteString
searchableItem.relatedUniqueIdentifier = NSURL.wmf_desktopURL(for: self as URL)?.absoluteString
return searchableItem
}
}
extension NSURL {
@objc var wmf_searchableItemAttributes: CSSearchableItemAttributeSet? {
return (self as URL).searchableItemAttributes
}
}
public class WMFSavedPageSpotlightManager: NSObject {
private let queue = DispatchQueue(label: "org.wikimedia.saved_page_spotlight_manager", qos: DispatchQoS.background, attributes: [], autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.workItem, target: nil)
private let dataStore: MWKDataStore
@objc var savedPageList: MWKSavedPageList {
return dataStore.savedPageList
}
@objc public required init(dataStore: MWKDataStore) {
self.dataStore = dataStore
super.init()
}
@objc public func reindexSavedPages() {
self.savedPageList.enumerateItems { (item, stop) in
guard let URL = item.url else {
return
}
self.addToIndex(url: URL as NSURL)
}
}
private func searchableItemAttributes(for article: WMFArticle) -> CSSearchableItemAttributeSet {
let searchableItem = article.url?.searchableItemAttributes ??
CSSearchableItemAttributeSet(itemContentType: kUTTypeInternetLocation as String)
searchableItem.subject = article.wikidataDescription
searchableItem.contentDescription = article.snippet
if let imageURL = article.imageURL(forWidth: WMFImageWidth.medium.rawValue) {
searchableItem.thumbnailData = dataStore.cacheController.imageCache.data(withURL: imageURL)?.data
}
return searchableItem
}
@objc public func addToIndex(url: NSURL) {
guard let article = dataStore.fetchArticle(with: url as URL), let identifier = NSURL.wmf_desktopURL(for: url as URL)?.absoluteString else {
return
}
dataStore.viewContext.perform { [weak self] in
guard let self = self else {
return
}
let searchableItemAttributes = self.searchableItemAttributes(for: article)
self.queue.async {
searchableItemAttributes.keywords?.append("Saved")
let item = CSSearchableItem(uniqueIdentifier: identifier, domainIdentifier: "org.wikimedia.wikipedia", attributeSet: searchableItemAttributes)
item.expirationDate = NSDate.distantFuture
CSSearchableIndex.default().indexSearchableItems([item]) { (error) -> Void in
if let error = error {
DDLogError("Indexing error: \(error.localizedDescription)")
}
}
}
}
}
@objc public func removeFromIndex(url: NSURL) {
guard let identifier = NSURL.wmf_desktopURL(for: url as URL)?.absoluteString else {
return
}
queue.async {
CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: [identifier]) { (error) in
if let error = error {
DDLogError("Deindexing error: \(error.localizedDescription)")
}
}
}
}
}
|
mit
|
158a96904ba1e41de1c2858ff8bc3c49
| 36.563636 | 215 | 0.632865 | 5.465608 | false | false | false | false |
dduan/swift
|
benchmark/single-source/SetTests.swift
|
1
|
4598
|
//===--- SetTests.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_SetIsSubsetOf(N: Int) {
let size = 200
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var isSubset = false;
for _ in 0 ..< N * 5000 {
isSubset = set.isSubsetOf(otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset, "Incorrect results in SetIsSubsetOf")
}
@inline(never)
func sink(s: inout Set<Int>) {
}
@inline(never)
public func run_SetExclusiveOr(N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var xor = Set<Int>()
for _ in 0 ..< N * 100 {
xor = set.exclusiveOr(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion(N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var or = Set<Int>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect(N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var and = Set<Int>()
for _ in 0 ..< N * 100 {
and = set.intersect(otherSet)
}
sink(&and)
}
class Box<T : Hashable where T : Equatable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue : Int {
return value.hashValue
}
}
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_SetIsSubsetOf_OfObjects(N: Int) {
let size = 200
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var isSubset = false;
for _ in 0 ..< N * 5000 {
isSubset = set.isSubsetOf(otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset, "Incorrect results in SetIsSubsetOf")
}
@inline(never)
func sink(s: inout Set<Box<Int>>) {
}
@inline(never)
public func run_SetExclusiveOr_OfObjects(N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var xor = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
xor = set.exclusiveOr(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion_OfObjects(N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var or = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect_OfObjects(N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var and = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
and = set.intersect(otherSet)
}
sink(&and)
}
|
apache-2.0
|
4ea4b259a05e4fb6c6888c32983a9b62
| 20.287037 | 80 | 0.624184 | 3.643423 | false | false | false | false |
PatrickChow/ForOneNight
|
NightDriver/Source/UIKit/UITableView+Nv.swift
|
1
|
1761
|
//
// Created by Patrick Chow on 2017/5/9.
// Copyright (c) 2017 Jiemian Technology. All rights reserved.
import UIKit.UITableView
extension Reactive where Base: UITableView {
@discardableResult
public func separatorColor(_ day: RenderPropertyType?, night: RenderPropertyType?) -> Self {
base?.separatorColor = renderProperty(day,night) as? UIColor
propertiesObserved.append { [weak self] in
self?.base?.separatorColor = self?.renderProperty(day,night) as? UIColor
}
return self
}
@discardableResult
public func sectionIndexColor(_ day: RenderPropertyType?, night: RenderPropertyType?) -> Self {
base?.sectionIndexColor = renderProperty(day,night) as? UIColor
propertiesObserved.append { [weak self] in
self?.base?.sectionIndexColor = self?.renderProperty(day,night) as? UIColor
}
return self
}
@discardableResult
public func sectionIndexBackgroundColor(_ day: RenderPropertyType?, night: RenderPropertyType?) -> Self {
base?.sectionIndexBackgroundColor = renderProperty(day,night) as? UIColor
propertiesObserved.append { [weak self] in
self?.base?.sectionIndexBackgroundColor = self?.renderProperty(day,night) as? UIColor
}
return self
}
@discardableResult
public func sectionIndexTrackingBackgroundColor(_ day: RenderPropertyType?, night: RenderPropertyType?) -> Self {
base?.sectionIndexTrackingBackgroundColor = renderProperty(day,night) as? UIColor
propertiesObserved.append { [weak self] in
self?.base?.sectionIndexTrackingBackgroundColor = self?.renderProperty(day,night) as? UIColor
}
return self
}
}
|
mit
|
b5154ead01bd5c50b6f4beea5b0204a8
| 37.282609 | 117 | 0.682567 | 5.288288 | false | false | false | false |
russbishop/swift
|
stdlib/public/SDK/Foundation/DateInterval.swift
|
1
|
8192
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct DateInterval : ReferenceConvertible, Comparable, Hashable {
public typealias ReferenceType = NSDateInterval
/// The start date.
public var start : Date
/// The end date.
///
/// - precondition: `end >= start`
public var end : Date {
get {
return start + duration
}
set {
precondition(newValue >= start, "Reverse intervals are not allowed")
duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
}
/// The duration.
///
/// - precondition: `duration >= 0`
public var duration : TimeInterval {
willSet {
precondition(newValue >= 0, "Negative durations are not allowed")
}
}
/// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`.
public init() {
let d = Date()
start = d
duration = 0
}
/// Initialize a `DateInterval` with the specified start and end date.
///
/// - precondition: `end >= start`
public init(start: Date, end: Date) {
if end < start {
fatalError("Reverse intervals are not allowed")
}
self.start = start
duration = end.timeIntervalSince(start)
}
/// Initialize a `DateInterval` with the specified start date and duration.
///
/// - precondition: `duration >= 0`
public init(start: Date, duration: TimeInterval) {
precondition(duration >= 0, "Negative durations are not allowed")
self.start = start
self.duration = duration
}
/**
Compare two DateIntervals.
This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g. Given intervals a and b
```
a. |-----|
b. |-----|
```
`a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g. Given intervals c and d
```
c. |-----|
d. |---|
```
`c.compare(d)` would result in `.OrderedDescending` because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result.
*/
public func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = start.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
/// Returns `true` if `self` intersects the `dateInterval`.
public func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end)
}
/// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect.
///
/// In the event that there is no intersection, the method returns nil.
public func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if self == dateInterval {
return self
}
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = start
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = end
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
/// Returns `true` if `self` contains `date`.
public func contains(_ date: Date) -> Bool {
let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalforSelfEnd = end.timeIntervalSinceReferenceDate
if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) {
return true
}
return false
}
public var hashValue: Int {
var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate))
return withUnsafeMutablePointer(&buf) {
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(sizeof(UInt.self) * 2)))
}
}
public var description: String {
return "(Start Date) \(start) + (Duration) \(duration) seconds = (End Date) \(end)"
}
public var debugDescription: String {
return description
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public func ==(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.start == rhs.start && lhs.duration == rhs.duration
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public func <(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension DateInterval : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSDateInterval.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateInterval {
return NSDateInterval(start: start, duration: duration)
}
public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) {
if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool {
result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval {
var result: DateInterval? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
|
apache-2.0
|
898484f95b23566c14f84de288ad7936
| 37.280374 | 327 | 0.635864 | 5.211196 | false | false | false | false |
piemonte/Position
|
Sources/Position.swift
|
1
|
20458
|
//
// Position.swift
//
// Created by patrick piemonte on 3/1/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2015-present patrick piemonte (http://patrickpiemonte.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
import CoreLocation
/// Position location authorization protocol.
public protocol PositionAuthorizationObserver: AnyObject {
/// Permission change authorization status, this may be triggered on application resume if the app settings have changed
func position(_ position: Position, didChangeLocationAuthorizationStatus status: Position.LocationAuthorizationStatus)
}
/// Position location updates protocol.
public protocol PositionObserver: AnyObject {
/// Location positioning one-shot updates
func position(_ position: Position, didUpdateOneShotLocation location: CLLocation?)
/// Location positioning tracking updates
func position(_ position: Position, didUpdateTrackingLocations locations: [CLLocation]?)
/// Location accuracy updates
func position(_ position: Position, didChangeDesiredAccurary desiredAccuracy: Double)
// Location extras
func position(_ position: Position, didUpdateFloor floor: CLFloor)
func position(_ position: Position, didVisit visit: CLVisit?)
/// Error handling
func position(_ position: Position, didFailWithError error: Error?)
}
/// Position heading updates protocol.
public protocol PositionHeadingObserver: AnyObject {
func position(_ postiion: Position, didUpdateHeading newHeading: CLHeading)
}
/// 🛰 Position, Swift and efficient location positioning.
open class Position {
// MARK: - types
/// Location authorization status
public enum LocationAuthorizationStatus: Int, CustomStringConvertible {
case notDetermined = 0
case notAvailable
case denied
case allowedWhenInUse
case allowedAlways
public var description: String {
get {
switch self {
case .notDetermined:
return "Not Determined"
case .notAvailable:
return "Not Available"
case .denied:
return "Denied"
case .allowedWhenInUse:
return "When In Use"
case .allowedAlways:
return "Allowed Always"
}
}
}
}
/// Location accuracy authorization status
public enum LocationAccuracyAuthorizationStatus: Int {
case fullAccuracy = 0
case reducedAccuracy
}
/// Possible error types
public enum ErrorType: Error, CustomStringConvertible {
case timedOut
case restricted
case cancelled
public var description: String {
get {
switch self {
case .timedOut:
return "Timed out"
case .restricted:
return "Restricted"
case .cancelled:
return "Cancelled"
}
}
}
}
/// Completion handler for one-shot location requests
public typealias OneShotCompletionHandler = (Swift.Result<CLLocation, Error>) -> Void
/// Time based filter constant
public static let TimeFilterNone: TimeInterval = 0.0
/// Time based filter constant
public static let TimeFilter5Minutes: TimeInterval = 5.0 * 60.0
/// Time based filter constant
public static let TimeFilter10Minutes: TimeInterval = 10.0 * 60.0
/// A statute mile to be 8 furlongs or 1609.344 meters
public static let MilesToMetersRatio: Double = 1609.344
// MARK: - singleton
/// Shared singleton
public static let shared = Position()
// MARK: - properties
/// Distance in meters a device must move before updating location.
public var distanceFilter: Double {
get {
_deviceLocationManager.distanceFilter
}
set {
_deviceLocationManager.distanceFilter = newValue
}
}
/// Time that must pass for a device before updating location.
public var timeFilter: TimeInterval {
get {
_deviceLocationManager.timeFilter
}
set {
_deviceLocationManager.timeFilter = newValue
}
}
/// When `true`, location will reduce power usage from adjusted accuracy when backgrounded.
public var adjustLocationUseWhenBackgrounded: Bool = false {
didSet {
if _deviceLocationManager.isUpdatingLowPowerLocation == true {
_deviceLocationManager.stopLowPowerUpdating()
_deviceLocationManager.startUpdating()
}
}
}
/// When `true`, location will reduce power usage from adjusted accuracy based on the current battery level.
public var adjustLocationUseFromBatteryLevel: Bool = false {
didSet {
UIDevice.current.isBatteryMonitoringEnabled = self.adjustLocationUseFromBatteryLevel
}
}
/// Location tracking desired accuracy when the app is active.
public var trackingDesiredAccuracyWhenActive: Double {
get {
_deviceLocationManager.trackingDesiredAccuracyActive
}
set {
_deviceLocationManager.trackingDesiredAccuracyActive = newValue
}
}
/// Location tracking desired accuracy when the app is in the background.
public var trackingDesiredAccuracyWhenInBackground: Double {
get {
_deviceLocationManager.trackingDesiredAccuracyBackground
}
set {
_deviceLocationManager.trackingDesiredAccuracyBackground = newValue
}
}
/// `true` when location services are updating
public var isUpdatingLocation: Bool {
_deviceLocationManager.isUpdatingLocation == true || _deviceLocationManager.isUpdatingLowPowerLocation == true
}
/// Last determined location
public var location: CLLocation? {
_deviceLocationManager.location
}
/// Last determined heading
public var heading: CLHeading? {
_deviceLocationManager.heading
}
// MARK: - ivars
internal private(set) var _authorizationObservers: NSHashTable<AnyObject>?
internal private(set) var _observers: NSHashTable<AnyObject>?
internal private(set) var _headingObservers: NSHashTable<AnyObject>?
internal private(set) var _deviceLocationManager: DeviceLocationManager = DeviceLocationManager()
internal private(set) var _updating: Bool = false
// MARK: - object lifecycle
public init() {
_deviceLocationManager.delegate = self
addBatteryObservers()
addAppObservers()
}
deinit {
removeAppObservers()
removeBatteryObservers()
}
}
// MARK: - observers
extension Position {
/// Adds an authorization observer.
///
/// - Parameter observer: Observing instance.
public func addAuthorizationObserver(_ observer: PositionAuthorizationObserver) {
if _authorizationObservers == nil {
_authorizationObservers = NSHashTable.weakObjects()
}
if _authorizationObservers?.contains(observer) == false {
_authorizationObservers?.add(observer)
}
}
/// Removes an authorization observer.
///
/// - Parameter observer: Observing instance.
public func removeAuthorizationObserver(_ observer: PositionAuthorizationObserver) {
if _authorizationObservers?.contains(observer) == true {
_authorizationObservers?.remove(observer)
}
if _authorizationObservers?.count == 0 {
_authorizationObservers = nil
}
}
/// Adds a position location observer.
///
/// - Parameter observer: Observing instance.
public func addObserver(_ observer: PositionObserver) {
if _observers == nil {
_observers = NSHashTable.weakObjects()
}
if _observers?.contains(observer) == false {
_observers?.add(observer)
}
}
/// Removes a position location observer.
///
/// - Parameter observer: Observing instance.
public func removeObserver(_ observer: PositionObserver) {
if _observers?.contains(observer) == true {
_observers?.remove(observer)
}
if _observers?.count == 0 {
_observers = nil
}
}
/// Adds a position heading observer.
///
/// - Parameter observer: Observing instance.
public func addHeadingObserver(_ observer: PositionHeadingObserver) {
if _headingObservers == nil {
_headingObservers = NSHashTable.weakObjects()
}
if _headingObservers?.contains(observer) == false {
_headingObservers?.add(observer)
}
}
/// Removes a position heading observer.
///
/// - Parameter observer: Observing instance.
public func removeHeadingObserver(_ observer: PositionHeadingObserver) {
if _headingObservers?.contains(observer) == true {
_headingObservers?.remove(observer)
}
if _headingObservers?.count == 0 {
_headingObservers = nil
}
}
}
// MARK: - authorization / permission
extension Position {
/// Authorization status for location services.
public var locationServicesStatus: LocationAuthorizationStatus {
_deviceLocationManager.locationServicesStatus
}
/// Request location authorization for in use always.
public func requestAlwaysLocationAuthorization() {
_deviceLocationManager.requestAlwaysAuthorization()
}
/// Request location authorization for in app use only.
public func requestWhenInUseLocationAuthorization() {
_deviceLocationManager.requestWhenInUseAuthorization()
}
@available(iOS 14, *)
public var locationAccuracyAuthorizationStatus: LocationAccuracyAuthorizationStatus {
_deviceLocationManager.locationAccuracyAuthorizationStatus
}
/// Request one time accuracy authorization. Be sure to include "FullAccuracyPurpose" to your Info.plist.
@available(iOS 14, *)
public func requestOneTimeFullAccuracyAuthorization(_ completionHandler: ((Bool) -> Void)? = nil) {
_deviceLocationManager.requestAccuracyAuthorization { completed in
completionHandler?(completed)
}
}
}
// MARK: - location & heading
extension Position {
/// Triggers a single location request at a specific desired accuracy regardless of any other location tracking configuration or requests.
///
/// - Parameters:
/// - desiredAccuracy: Minimum accuracy to meet before for request.
/// - completionHandler: Completion handler for when the location is determined.
public func performOneShotLocationUpdate(withDesiredAccuracy desiredAccuracy: Double, completionHandler: Position.OneShotCompletionHandler? = nil) {
_deviceLocationManager.performOneShotLocationUpdate(withDesiredAccuracy: desiredAccuracy, completionHandler: completionHandler)
}
/// Start positioning updates.
public func startUpdating() {
_deviceLocationManager.startUpdating()
_updating = true
}
/// Stop positioning updates.
public func stopUpdating() {
_deviceLocationManager.stopUpdating()
_deviceLocationManager.stopLowPowerUpdating()
_updating = false
}
}
// MARK: - heading
extension Position {
/// Start heading updates.
public func startUpdatingHeading() {
_deviceLocationManager.startUpdatingHeading()
}
/// Stop heading updates.
public func stopUpdatingHeading() {
_deviceLocationManager.stopUpdatingHeading()
}
}
// MARK: - private functions
extension Position {
internal func checkAuthorizationStatusForServices() {
if _deviceLocationManager.locationServicesStatus == .denied {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
for observer in self._observers?.allObjects as? [PositionAuthorizationObserver] ?? [] {
observer.position(self, didChangeLocationAuthorizationStatus: .denied)
}
}
}
}
internal func updateLocationAccuracyIfNecessary() {
if adjustLocationUseFromBatteryLevel == true {
switch UIDevice.current.batteryState {
case .full,
.charging:
_deviceLocationManager.trackingDesiredAccuracyActive = kCLLocationAccuracyNearestTenMeters
_deviceLocationManager.trackingDesiredAccuracyBackground = kCLLocationAccuracyHundredMeters
break
case .unplugged,
.unknown:
fallthrough
@unknown default:
let batteryLevel: Float = UIDevice.current.batteryLevel
if batteryLevel < 0.15 {
_deviceLocationManager.trackingDesiredAccuracyActive = kCLLocationAccuracyThreeKilometers
_deviceLocationManager.trackingDesiredAccuracyBackground = kCLLocationAccuracyThreeKilometers
} else {
_deviceLocationManager.trackingDesiredAccuracyActive = kCLLocationAccuracyHundredMeters
_deviceLocationManager.trackingDesiredAccuracyBackground = kCLLocationAccuracyKilometer
}
break
}
}
}
}
// MARK: - Notifications
extension Position {
// add / remove
internal func addAppObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: UIApplication.shared)
NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: UIApplication.shared)
}
internal func removeAppObservers() {
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: UIApplication.shared)
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: UIApplication.shared)
}
internal func addBatteryObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleBatteryLevelChanged(_:)), name: UIDevice.batteryLevelDidChangeNotification, object: UIApplication.shared)
NotificationCenter.default.addObserver(self, selector: #selector(handleBatteryStateChanged(_:)), name: UIDevice.batteryStateDidChangeNotification, object: UIApplication.shared)
}
internal func removeBatteryObservers() {
NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: UIApplication.shared)
NotificationCenter.default.removeObserver(self, name: UIDevice.batteryStateDidChangeNotification, object: UIApplication.shared)
}
// handlers
@objc
private func handleApplicationDidBecomeActive(_ notification: Notification) {
checkAuthorizationStatusForServices()
// if position is not updating, don't modify state
if _updating == false {
return
}
// internally, locationManager will adjust desiredaccuracy to trackingDesiredAccuracyBackground
if adjustLocationUseWhenBackgrounded == true {
_deviceLocationManager.stopLowPowerUpdating()
}
}
@objc
private func handleApplicationWillResignActive(_ notification: Notification) {
if _updating == true {
return
}
if adjustLocationUseWhenBackgrounded == true {
_deviceLocationManager.startLowPowerUpdating()
}
updateLocationAccuracyIfNecessary()
}
@objc
private func handleBatteryLevelChanged(_ notification: Notification) {
let batteryLevel = UIDevice.current.batteryLevel
if batteryLevel < 0 {
return
}
updateLocationAccuracyIfNecessary()
}
@objc
private func handleBatteryStateChanged(_ notification: Notification) {
updateLocationAccuracyIfNecessary()
}
}
// MARK: - DeviceLocationManagerDelegate
extension Position: DeviceLocationManagerDelegate {
internal func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didChangeLocationAuthorizationStatus status: LocationAuthorizationStatus) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
for observer in self._observers?.allObjects as? [PositionAuthorizationObserver] ?? [] {
observer.position(self, didChangeLocationAuthorizationStatus: status)
}
}
}
internal func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didFailWithError error: Error?) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
for observer in self._observers?.allObjects as? [PositionObserver] ?? [] {
observer.position(self, didFailWithError: error)
}
}
}
internal func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didUpdateOneShotLocation location: CLLocation?) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
for observer in self._observers?.allObjects as? [PositionObserver] ?? [] {
observer.position(self, didUpdateOneShotLocation: location)
}
}
}
internal func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didUpdateTrackingLocations locations: [CLLocation]?) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
for observer in self._observers?.allObjects as? [PositionObserver] ?? [] {
observer.position(self, didUpdateTrackingLocations: locations)
}
}
}
func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didUpdateHeading newHeading: CLHeading) {
for observer in self._observers?.allObjects as? [PositionHeadingObserver] ?? [] {
observer.position(self, didUpdateHeading: newHeading)
}
}
internal func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didUpdateFloor floor: CLFloor) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
for observer in self._observers?.allObjects as? [PositionObserver] ?? [] {
observer.position(self, didUpdateFloor: floor)
}
}
}
internal func deviceLocationManager(_ deviceLocationManager: DeviceLocationManager, didVisit visit: CLVisit?) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if let observers = self._observers?.allObjects as? [PositionObserver] {
observers.forEach({ observer in
observer.position(self, didVisit: visit)
})
}
}
}
}
|
mit
|
3eab15005ad3a3adb7ad8691a5d7d2b3
| 34.512153 | 192 | 0.665705 | 5.579651 | false | false | false | false |
aeidelson/light-playground
|
swift_app/light-playground/LightGrid/MetalLightGrid.swift
|
1
|
14358
|
import Metal
import CoreGraphics
/// An implementation of LightGrid which draws primarily using Metal.
final class MetalLightGrid: LightGrid {
public init(
context: LightSimulatorContext,
size: CGSize,
initialRenderProperties: RenderImageProperties
) {
self.context = context
self.metalContext = context.metalContext!
self.width = Int(size.width.rounded())
self.height = Int(size.height.rounded())
self.renderProperties = initialRenderProperties
// Make the textures used for storing the image state.
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(
pixelFormat: .r32Float,
width: width,
height: height,
mipmapped: false)
textureDescriptor.storageMode = .shared
self.rMetalTextureOld = metalContext.device.makeTexture(descriptor: textureDescriptor)!
self.rMetalTextureCurrent = metalContext.device.makeTexture(descriptor: textureDescriptor)!
self.gMetalTextureOld = metalContext.device.makeTexture(descriptor: textureDescriptor)!
self.gMetalTextureCurrent = metalContext.device.makeTexture(descriptor: textureDescriptor)!
self.bMetalTextureOld = metalContext.device.makeTexture(descriptor: textureDescriptor)!
self.bMetalTextureCurrent = metalContext.device.makeTexture(descriptor: textureDescriptor)!
}
// MARK: LightGrid
public func reset(updateImage: Bool) {
// Wipe each of the "current" textures.
let emptyBytes = [Float](repeatElement(0, count: height * width))
rMetalTextureCurrent.replace(
region: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0,
withBytes: emptyBytes,
bytesPerRow: MemoryLayout<Float32>.size * width)
gMetalTextureCurrent.replace(
region: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0,
withBytes: emptyBytes,
bytesPerRow: MemoryLayout<Float32>.size * width)
bMetalTextureCurrent.replace(
region: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0,
withBytes: emptyBytes,
bytesPerRow: MemoryLayout<Float32>.size * width)
// Reset any variables we need to.
totalSegmentCount = 0
// Send out an updated image.
if updateImage {
self.updateImage()
}
}
public func drawSegments(layout: SimulationLayout, segments: [LightSegment], lowQuality: Bool) {
if layout.version < latestLayoutVersion {
return
}
latestLayoutVersion = layout.version
// Swap the old and current textures so we can re-use the previous texture as the source.
swap(&rMetalTextureOld, &rMetalTextureCurrent)
swap(&gMetalTextureOld, &gMetalTextureCurrent)
swap(&bMetalTextureOld, &bMetalTextureCurrent)
// Before drawing the new segments, texture's brightness is reduced using a compute kernel.
// How much to multiply the old texture by before drawing the new segments on top.
let baseImageBrightness: Float32 =
Float32(totalSegmentCount) / Float(totalSegmentCount + UInt64(segments.count))
let preprocessParameters: [Float32] = [baseImageBrightness]
let preprocessParametersBuffer = metalContext.device.makeBuffer(
bytes: preprocessParameters,
length: MemoryLayout<Float32>.size * preprocessParameters.count,
options: [])
let preprocessCommandBuffer = metalContext.commandQueue.makeCommandBuffer()!
let preprocessEncoder = preprocessCommandBuffer.makeComputeCommandEncoder()!
preprocessEncoder.setComputePipelineState(metalContext.imagePreprocessingPipelineState)
preprocessEncoder.setBuffer(preprocessParametersBuffer, offset: 0, index: 0)
preprocessEncoder.setTexture(rMetalTextureOld, index: 0)
preprocessEncoder.setTexture(rMetalTextureCurrent, index: 1)
preprocessEncoder.setTexture(gMetalTextureOld, index: 2)
preprocessEncoder.setTexture(gMetalTextureCurrent, index: 3)
preprocessEncoder.setTexture(bMetalTextureOld, index: 4)
preprocessEncoder.setTexture(bMetalTextureCurrent, index: 5)
// TODO: Figure out what these dimensions should actually be.
let threadExecutionWidth =
metalContext.imagePreprocessingPipelineState.threadExecutionWidth
let maxTotalThreadsPerThreadgroup =
metalContext.imagePreprocessingPipelineState.maxTotalThreadsPerThreadgroup
let threadsPerThreadGroup = MTLSizeMake(
threadExecutionWidth,
maxTotalThreadsPerThreadgroup / threadExecutionWidth,
1)
let threadgroupsPerGrid = MTLSizeMake(
(width + threadsPerThreadGroup.width - 1) / threadsPerThreadGroup.width,
(height + threadsPerThreadGroup.height - 1) / threadsPerThreadGroup.height,
1)
preprocessEncoder.dispatchThreadgroups(
threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadGroup)
preprocessEncoder.endEncoding()
preprocessCommandBuffer.commit()
// After the preprocessing, draw the segments in a render pass.
let renderCommandBuffer = metalContext.commandQueue.makeCommandBuffer()!
let renderPassDescriptor = MTLRenderPassDescriptor()
renderPassDescriptor.colorAttachments[0].texture = rMetalTextureCurrent
renderPassDescriptor.colorAttachments[0].loadAction = .load
renderPassDescriptor.colorAttachments[0].storeAction = .store
renderPassDescriptor.colorAttachments[1].texture = gMetalTextureCurrent
renderPassDescriptor.colorAttachments[1].loadAction = .load
renderPassDescriptor.colorAttachments[1].storeAction = .store
renderPassDescriptor.colorAttachments[2].texture = bMetalTextureCurrent
renderPassDescriptor.colorAttachments[2].loadAction = .load
renderPassDescriptor.colorAttachments[2].storeAction = .store
let renderEncoder = renderCommandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)!
renderEncoder.setRenderPipelineState(metalContext.renderPipelineState)
// The y-axis is flipped to match our own coord system.
renderEncoder.setViewport(MTLViewport(
originX: 0,
originY: Double(height),
width: Double(width),
height: -Double(height),
znear: 0,
zfar: 1
))
// Create the vertex and color inputs to the render pass.
let numOfVerts = segments.count * 2
var positions = [Float32](repeatElement(0.0, count: numOfVerts * 4))
var colors = [Float32](repeatElement(0.0, count: numOfVerts * 4))
let newSegmentBrightness = 1 / Float(UInt64(segments.count) + totalSegmentCount)
var i = 0
while i < segments.count {
let segment = segments[i]
// The brightness is adjusted so diagonal lines are as heavily weighted as horizontal ones.
var dx = abs(Float(segment.pos2.x) - Float(segment.pos1.x))
var dy = abs(Float(segment.pos2.y) - Float(segment.pos1.y))
// TODO: Figure out if this swapping is necessary?
if dy > dx {
swap(&dx, &dy)
}
// Save ourselves a lot of trouble by avoiding zero-values.
if abs(dx) < 0.01 {
dx = 0.01
}
let updatedBrightness = abs(sqrtf(dx*dx + dy*dy) / dx) * newSegmentBrightness
// The position and color arrays are populated
var vertexIndex = i * 2 * 4
let p1 = gridToMetalCoord(segment.pos1)
let p2 = gridToMetalCoord(segment.pos2)
// First vert
// TODO: Move the float calculating to the LightColor to avoid re-calculating these values.
positions[vertexIndex + 0] = Float(p1.x)
positions[vertexIndex + 1] = Float(p1.y)
positions[vertexIndex + 2] = 0
positions[vertexIndex + 3] = 1
colors[vertexIndex + 0] = Float(segment.color.r) / Float(UInt8.max) * updatedBrightness
colors[vertexIndex + 1] = Float(segment.color.g) / Float(UInt8.max) * updatedBrightness
colors[vertexIndex + 2] = Float(segment.color.b) / Float(UInt8.max) * updatedBrightness
colors[vertexIndex + 3] = 0
// Seccond vert
vertexIndex += 4
positions[vertexIndex + 0] = Float(p2.x)
positions[vertexIndex + 1] = Float(p2.y)
positions[vertexIndex + 2] = 0
positions[vertexIndex + 3] = 1
colors[vertexIndex + 0] = Float(segment.color.r) / Float(UInt8.max) * updatedBrightness
colors[vertexIndex + 1] = Float(segment.color.g) / Float(UInt8.max) * updatedBrightness
colors[vertexIndex + 2] = Float(segment.color.b) / Float(UInt8.max) * updatedBrightness
colors[vertexIndex + 3] = 0
i += 1
}
// Set the values on the encoder and do do the drawing.
let positionBuffer = metalContext.device.makeBuffer(
bytes: positions,
length: positions.count * MemoryLayout<Float>.size,
options: [])
let colorBuffer = metalContext.device.makeBuffer(
bytes: colors,
length: colors.count * MemoryLayout<Float32>.size,
options: [])
renderEncoder.setVertexBuffer(positionBuffer, offset: 0, index: 0)
renderEncoder.setVertexBuffer(colorBuffer, offset: 0, index: 1)
renderEncoder.drawPrimitives(
type: .line,
vertexStart: 0,
vertexCount: numOfVerts,
instanceCount: 1)
renderEncoder.endEncoding()
renderCommandBuffer.commit()
renderCommandBuffer.waitUntilCompleted()
// Record the new segment count and update the image.
totalSegmentCount += UInt64(segments.count)
updateImage()
}
// Converts from our to the Metal coordinate space.
private func gridToMetalCoord(_ pos: CGPoint) -> (x: Float, y: Float) {
let metalDim = Float(2)
let metalOrigin = metalDim / 2
return (
x: (Float(pos.x) / Float(width)) * metalDim - metalOrigin,
y: (Float(pos.y) / Float(height)) * metalDim - metalOrigin
)
}
public var renderProperties: RenderImageProperties {
didSet {
if !oldValue.exposure.isEqual(to: renderProperties.exposure) {
updateImage()
}
}
}
public var snapshotHandler: (SimulationSnapshot) -> Void = { _ in }
// MARK: Private
private func updateImage() {
// Read each texture
var redTextureReadBuffer = [Float32](repeatElement(0, count: width * height))
rMetalTextureCurrent.getBytes(
&redTextureReadBuffer,
bytesPerRow: MemoryLayout<Float32>.size * width,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0)
var greenTextureReadBuffer = [Float32](repeatElement(0, count: width * height))
gMetalTextureCurrent.getBytes(
&greenTextureReadBuffer,
bytesPerRow: MemoryLayout<Float32>.size * width,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0)
var blueTextureReadBuffer = [Float32](repeatElement(0, count: width * height))
bMetalTextureCurrent.getBytes(
&blueTextureReadBuffer,
bytesPerRow: MemoryLayout<Float32>.size * width,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0)
// Write the textures to the corresponding image channel on the rendered image.
let exposure = Float(renderProperties.exposure)
let bufferSize = width * height * 4
let imagePixelBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
var i = 0
while i < width * height {
let redValue = UInt8(Float(UInt8.max) * min(redTextureReadBuffer[i] * exposure, 1.0))
let greenValue = UInt8(Float(UInt8.max) * min(greenTextureReadBuffer[i] * exposure, 1.0))
let blueValue = UInt8(Float(UInt8.max) * min(blueTextureReadBuffer[i] * exposure, 1.0))
let imageIndex = i * 4
imagePixelBuffer[imageIndex + 0] = redValue
imagePixelBuffer[imageIndex + 1] = greenValue
imagePixelBuffer[imageIndex + 2] = blueValue
i += 1
}
let imageDataProvider = CGDataProvider(
data: NSData(
bytesNoCopy: UnsafeMutableRawPointer(imagePixelBuffer),
length: bufferSize,
freeWhenDone: true))
let image = CGImage(
width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 4 * 8,
bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
// Alpha is ignored.
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue),
provider: imageDataProvider!,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent)
if let imageUnwrapped = image {
snapshotHandler(SimulationSnapshot(image: imageUnwrapped, totalLightSegmentsTraced: totalSegmentCount))
}
}
private let width: Int
private let height: Int
private var totalSegmentCount = UInt64(0)
private var latestLayoutVersion = UInt64(0)
private let context: LightSimulatorContext
private let metalContext: MetalContext
// MARK: Metal textures
/// We use one texture per channel, to allow for more bits per channel. There are also two textures maintained
/// per channel since Metal doesn't apparently allow reading and writing to the same texture on iOS.
private var rMetalTextureOld: MTLTexture
private var rMetalTextureCurrent: MTLTexture
private var gMetalTextureOld: MTLTexture
private var gMetalTextureCurrent: MTLTexture
private var bMetalTextureOld: MTLTexture
private var bMetalTextureCurrent: MTLTexture
}
|
apache-2.0
|
38f13e2dfec4d78ea272932c2d19f851
| 40.49711 | 115 | 0.649046 | 4.805221 | false | false | false | false |
lucaslouca/swift-concurrency
|
app-ios/Fluxcapacitor/FXCFluxcapacitorAPI.swift
|
1
|
14558
|
//
// FXCFluxcapacitorAPI.swift
// Fluxcapacitor
//
// Created by Lucas Louca on 22/05/15.
// Copyright (c) 2015 Lucas Louca. All rights reserved.
//
import UIKit
class FXCFluxcapacitorAPI: NSObject, FXCItemFetchDelegate {
let orderDataSourceURL = NSURL(string:"http://lucaslouca.com/swift-concurrency/orders.plist")
let itemsDataSourceURL = NSURL(string:"http://lucaslouca.com/swift-concurrency/items.plist")
let pendingOperations: FXCPendingOperations = FXCPendingOperations()
var items = [Int:FXCItem]()
/**
Read-Only computed property sharedInstance holding the the shared API object.
*/
class var sharedInstance: FXCFluxcapacitorAPI {
struct Singleton {
static let instance = FXCFluxcapacitorAPI()
}
return Singleton.instance
}
/**
This method creates an asynchronous web request which, when finished, will run the completion block on the main queue.
When the download is complete the property list data is extracted into an NSDictionary and then processed again into an
array of FXCOrder objects.
- parameter delegate: FXCOrderFetchDelegate the should get notified when the order details are downloaded
*/
func fetchOrderDetails(delegate: FXCOrderFetchDelegate) {
let request = NSURLRequest(URL:orderDataSourceURL!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {response, data, error in
do {
if data != nil {
var orderDetails = [FXCOrder]()
let datasourceDictionary = try NSPropertyListSerialization.propertyListWithData(data!, options: NSPropertyListMutabilityOptions.Immutable, format: nil) as! NSDictionary
for(key, value): (AnyObject, AnyObject) in datasourceDictionary {
let orderId = key as? String
let url = NSURL(string:value as? String ?? "")
if orderId != nil && url != nil {
let order = FXCOrder(id:Int(orderId!)!, url:url!)
orderDetails.append(order)
}
}
// Notify delegate that order details fetching is complete
delegate.orderDetailsFetchDidFinishWith(orderDetails)
}
if error != nil {
let alert = UIAlertView(title:"Oops!",message:error!.localizedDescription, delegate:nil, cancelButtonTitle:"OK")
alert.show()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
} catch {
print("Unable to complete request. \(error)")
}
}
}
/**
Start the download of data for the given order at indexPath.
- parameter order: the FXCOrder containing the details (URL to order XML) inorder to download the full order data (price, images etc)
- parameter indexPath: NSIndexPath of the order
- parameter delegate: FXCOrderFetchDelegate the should get notified when the order data are downloaded
*/
func startDownloadForOrder(order: FXCOrder, indexPath: NSIndexPath, delegate: FXCOrderFetchDelegate){
if let _ = pendingOperations.orderDownloadsInProgress[indexPath] {
return
}
let downloadOperation = FXCOperationOrderDownloader(order: order)
downloadOperation.completionBlock = {
if downloadOperation.cancelled {
return
}
// UI stuff needs to be done on the main thread
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.orderDownloadsInProgress.removeValueForKey(indexPath)
// Notify delegate that the order has been downloaded
delegate.orderDownloadDidFinishForIndexPath(indexPath)
})
}
pendingOperations.orderDownloadsInProgress[indexPath] = downloadOperation
pendingOperations.orderDownloadQueue.addOperation(downloadOperation)
}
/**
Get a Set of all pending order operations (download and XML parsing)
:return: Set of all pending order operations (download and XML parsing)
*/
func allPendingOrderOperations() -> Set<NSIndexPath> {
var result = Set(pendingOperations.orderDownloadsInProgress.keys.array)
result.unionInPlace(pendingOperations.orderXMLParsingInProgress.keys.array)
return result
}
/**
Cancel the download of the order with indexPath.
- parameter indexPath: NSIndexPath of the order
*/
func cancelDownloadOrderOperation(indexPath: NSIndexPath) {
if let pendingDownload = pendingOperations.orderDownloadsInProgress[indexPath] {
pendingDownload.cancel()
}
pendingOperations.orderDownloadsInProgress.removeValueForKey(indexPath)
}
/**
Start the XML parsing of the downloaded order data for the given order at indexPath.
- parameter order: the FXCOrder containing the data (NSData) that needs to pased and mapped to the FXCOrder attributes
- parameter indexPath: NSIndexPath of the order
- parameter delegate: FXCOrderFetchDelegate the should get notified when the order data parsing is done
*/
func startXMPParsingForOrder(order: FXCOrder, indexPath: NSIndexPath, delegate: FXCOrderFetchDelegate){
if let _ = pendingOperations.orderXMLParsingInProgress[indexPath] {
return
}
let parseOperation = FXCOperationOrderXMLParse(order: order)
parseOperation.completionBlock = {
if parseOperation.cancelled {
return
}
// UI stuff needs to be done on the main thread
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.orderXMLParsingInProgress.removeValueForKey(indexPath)
// Notify delegate that the order has been parsed
delegate.orderXMParsingDidFinishForIndexPath(indexPath)
})
}
pendingOperations.orderXMLParsingInProgress[indexPath] = parseOperation
pendingOperations.orderXMLParsingQueue.addOperation(parseOperation)
}
/**
Cancel the XML parsing of the order with indexPath.
- parameter indexPath: NSIndexPath of the order
*/
func cancelXMLParsingOrderOperation(indexPath: NSIndexPath) {
if let pendingDownload = pendingOperations.orderXMLParsingInProgress[indexPath] {
pendingDownload.cancel()
}
pendingOperations.orderXMLParsingInProgress.removeValueForKey(indexPath)
}
func suspendAllOrderDownloads() {
pendingOperations.orderDownloadQueue.suspended = true
}
func suspendAllOrderXMLParsingOperations() {
pendingOperations.orderXMLParsingQueue.suspended = true
}
func resumeAllOrderDownloads() {
pendingOperations.orderDownloadQueue.suspended = false
}
func resumeAllOrderXMLParsingOperations() {
pendingOperations.orderXMLParsingQueue.suspended = false
}
// MARK: - Items Download
func fetchItems(){
self.fetchItemDetails(self)
}
/**
Fetch the list of all item IDs with the URL to their XML file: (id, URL)
*/
func fetchItemDetails(delegate: FXCItemFetchDelegate) {
let request = NSURLRequest(URL:itemsDataSourceURL!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {response, data, error in
do {
if data != nil {
var itemDetails = [Int:FXCItem]()
let datasourceDictionary = try NSPropertyListSerialization.propertyListWithData(data!, options: NSPropertyListMutabilityOptions.Immutable, format: nil) as! NSDictionary
for(key, value): (AnyObject, AnyObject) in datasourceDictionary {
let itemId = key as? String
let url = NSURL(string:value as? String ?? "")
if itemId != nil && url != nil {
let item = FXCItem(id:Int(itemId!)!, url:url!)
itemDetails[item.id] = item
}
}
// Notify delegate that order details fetching is complete
delegate.itemDetailsFetchDidFinishWith(itemDetails)
}
if error != nil {
let alert = UIAlertView(title:"Oops!",message:error!.localizedDescription, delegate:nil, cancelButtonTitle:"OK")
alert.show()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
} catch {print("Unable to complete request. \(error)")}
}
}
/**
Stage 1:
Called when we have all the item id and URL to their XML
*/
func itemDetailsFetchDidFinishWith(itemDetails:[Int:FXCItem]) {
items = itemDetails
for (_, item) in items {
FXCFluxcapacitorAPI.sharedInstance.startOperationsForItem(item)
}
}
/**
Stage 2:
Called when we have the XML data for an item (not parsed)
*/
func itemDownloadDidFinishForItem(item: FXCItem) {
FXCFluxcapacitorAPI.sharedInstance.startOperationsForItem(item)
}
/**
Stage 3:
Called when we have parsed the XML data of an item
*/
func itemXMParsingDidFinishForItem(item: FXCItem) {
FXCFluxcapacitorAPI.sharedInstance.startOperationsForItem(item)
}
/**
Stage 4:
Called when the image of an item has been downloaded
*/
func itemImageDownloadDidFinishForItem(item: FXCItem) {
}
func startOperationsForItem(itemDetails: FXCItem) {
switch (itemDetails.state) {
case .New:
FXCFluxcapacitorAPI.sharedInstance.startDownloadForItem(itemDetails, delegate:self)
case .Downloaded:
FXCFluxcapacitorAPI.sharedInstance.startXMPParsingForItem(itemDetails, delegate:self)
case .XMLParsed:
FXCFluxcapacitorAPI.sharedInstance.startImageDownloadForItem(itemDetails, delegate:self)
default:
NSLog("")
}
}
/**
Start the download of data for the given item.
- parameter item: the FXCItem containing the details (URL to order XML) inorder to download the full order data (weight, name, image-url etc)
- parameter delegate: FXCItemFetchDelegate the should get notified when the item data are downloaded
*/
func startDownloadForItem(item: FXCItem, delegate: FXCItemFetchDelegate){
if let _ = pendingOperations.itemDownloadsInProgress[item.id] {
return
}
let downloadOperation = FXCOperationItemDownloader(item: item)
downloadOperation.completionBlock = {
if downloadOperation.cancelled {
return
}
// UI stuff needs to be done on the main thread
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.itemDownloadsInProgress.removeValueForKey(item.id)
// Notify delegate that the order has been downloaded
delegate.itemDownloadDidFinishForItem(item)
})
}
pendingOperations.itemDownloadsInProgress[item.id] = downloadOperation
pendingOperations.itemDownloadQueue.addOperation(downloadOperation)
}
/**
Start the XML parsing of the downloaded item data for the given item.
- parameter item: the FXCItem containing the data (NSData) that needs to pased and mapped to the FXCItem fields
- parameter delegate: FXCItemFetchDelegate the should get notified when the item data parsing is done
*/
func startXMPParsingForItem(item: FXCItem, delegate: FXCItemFetchDelegate){
if let _ = pendingOperations.itemXMLParsingInProgress[item.id] {
return
}
let parseOperation = FXCOperationItemXMLParse(item: item)
parseOperation.completionBlock = {
if parseOperation.cancelled {
return
}
// UI stuff needs to be done on the main thread
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.itemXMLParsingInProgress.removeValueForKey(item.id)
// Notify delegate that the item has been parsed
delegate.itemXMParsingDidFinishForItem(item)
})
}
pendingOperations.itemXMLParsingInProgress[item.id] = parseOperation
pendingOperations.itemXMLParsingQueue.addOperation(parseOperation)
}
/**
Start the image download of a parsed item.
- parameter item: the FXCItem containing the URL of the image
- parameter delegate: FXCItemFetchDelegate the should get notified when the image download is done
*/
func startImageDownloadForItem(item: FXCItem, delegate: FXCItemFetchDelegate){
if let _ = pendingOperations.itemImageDownloadsInProgress[item.id] {
return
}
let parseOperation = FXCOperationItemImageDownloader(item: item)
parseOperation.completionBlock = {
if parseOperation.cancelled {
return
}
// UI stuff needs to be done on the main thread
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.itemImageDownloadsInProgress.removeValueForKey(item.id)
// Notify delegate that the item has been parsed
delegate.itemImageDownloadDidFinishForItem?(item)
})
}
pendingOperations.itemImageDownloadsInProgress[item.id] = parseOperation
pendingOperations.itemImageDownloadQueue.addOperation(parseOperation)
}
}
|
mit
|
c73e1c2fd645f319b02f3a0d39469ebe
| 38.5625 | 189 | 0.630993 | 5.39385 | false | false | false | false |
IvanVorobei/Sparrow
|
sparrow/extension/SPBezierPathExtension.swift
|
3
|
2267
|
// The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension UIBezierPath {
func resizeTo(width: CGFloat) {
let currentWidth = self.bounds.width
let relativeFactor = width / currentWidth
self.apply(CGAffineTransform(scaleX: relativeFactor, y: relativeFactor))
}
func convertToImage(fill: Bool, stroke: Bool, color: UIColor = .black) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: self.bounds.width, height: self.bounds.height), false, 0.0)
let context = UIGraphicsGetCurrentContext()
context!.setStrokeColor(color.cgColor)
context!.setFillColor(color.cgColor)
if stroke {
self.stroke()
}
if fill {
self.fill()
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
public struct SPBezierPath {
public static func setContext() {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
}
public static func endContext() {
UIGraphicsEndImageContext()
}
}
|
mit
|
086fa166bed46d2b35994eaa7a3b69ff
| 38.068966 | 120 | 0.70609 | 4.862661 | false | false | false | false |
mshhmzh/firefox-ios
|
Client/Frontend/Share/ShareExtensionHelper.swift
|
3
|
6033
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import OnePasswordExtension
private let log = Logger.browserLogger
class ShareExtensionHelper: NSObject {
private weak var selectedTab: Tab?
private let selectedURL: NSURL
private var onePasswordExtensionItem: NSExtensionItem!
private let activities: [UIActivity]
init(url: NSURL, tab: Tab?, activities: [UIActivity]) {
self.selectedURL = url
self.selectedTab = tab
self.activities = activities
}
func createActivityViewController(completionHandler: (Bool) -> Void) -> UIActivityViewController {
var activityItems = [AnyObject]()
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.jobName = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString
printInfo.outputType = .General
activityItems.append(printInfo)
if let tab = selectedTab {
activityItems.append(TabPrintPageRenderer(tab: tab))
}
if let title = selectedTab?.title {
activityItems.append(TitleActivityItemProvider(title: title))
}
activityItems.append(self)
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: activities)
// Hide 'Add to Reading List' which currently uses Safari.
// We would also hide View Later, if possible, but the exclusion list doesn't currently support
// third-party activity types (rdar://19430419).
activityViewController.excludedActivityTypes = [
UIActivityTypeAddToReadingList,
]
// This needs to be ready by the time the share menu has been displayed and
// activityViewController(activityViewController:, activityType:) is called,
// which is after the user taps the button. So a million cycles away.
if (ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
findLoginExtensionItem()
}
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
if !completed {
completionHandler(completed)
return
}
if self.isPasswordManagerActivityType(activityType) {
if let logins = returnedItems {
self.fillPasswords(logins)
}
}
completionHandler(completed)
}
return activityViewController
}
}
extension ShareExtensionHelper: UIActivityItemSource {
func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
if let displayURL = selectedTab?.displayURL {
return displayURL
}
return selectedURL
}
func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
if isPasswordManagerActivityType(activityType) {
return onePasswordExtensionItem
} else {
// Return the URL for the selected tab. If we are in reader view then decode
// it so that we copy the original and not the internal localhost one.
if let url = selectedTab?.displayURL where ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
return selectedTab?.displayURL ?? selectedURL
}
}
func activityViewController(activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: String?) -> String {
// Because of our UTI declaration, this UTI now satisfies both the 1Password Extension and the usual NSURL for Share extensions.
return "org.appextension.fill-browser-action"
}
}
private extension ShareExtensionHelper {
static func isPasswordManagerExtensionAvailable() -> Bool {
return OnePasswordExtension.sharedExtension().isAppExtensionAvailable()
}
func isPasswordManagerActivityType(activityType: String?) -> Bool {
if (!ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
return false
}
// A 'password' substring covers the most cases, such as pwsafe and 1Password.
// com.agilebits.onepassword-ios.extension
// com.app77.ios.pwsafe2.find-login-action-password-actionExtension
// If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier.
return (activityType?.rangeOfString("password") != nil)
|| (activityType == "com.lastpass.ilastpass.LastPassExt")
}
func findLoginExtensionItem() {
guard let selectedWebView = selectedTab?.webView else {
return
}
if selectedWebView.URL?.absoluteString == nil {
return
}
// Add 1Password to share sheet
OnePasswordExtension.sharedExtension().createExtensionItemForWebView(selectedWebView, completion: {(extensionItem, error) -> Void in
if extensionItem == nil {
log.error("Failed to create the password manager extension item: \(error).")
return
}
// Set the 1Password extension item property
self.onePasswordExtensionItem = extensionItem
})
}
func fillPasswords(returnedItems: [AnyObject]) {
guard let selectedWebView = selectedTab?.webView else {
return
}
OnePasswordExtension.sharedExtension().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in
if !success {
log.error("Failed to fill item into webview: \(returnedItemsError).")
}
})
}
}
|
mpl-2.0
|
35fb97553b2834694e10546b6f252e02
| 38.690789 | 164 | 0.670479 | 5.885854 | false | false | false | false |
brokenseal/iOS-exercises
|
Team Treehouse/Interactive Story/Interactive Story/ViewController.swift
|
1
|
3767
|
//
// ViewController.swift
// Interactive Story
//
// Created by Davide Callegari on 24/02/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var textFieldBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.keyboardWillShow),
name: Notification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.keyboardWillHide),
name: Notification.Name.UIKeyboardWillHide,
object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "startAdventure" {
do {
if let name = nameTextField.text {
if name == "" {
throw AdventureError.nameNotProvided
} else {
guard let pageController = segue.destination as? PageController else { return }
pageController.page = Adventure.story(withName: name)
}
}
} catch AdventureError.nameNotProvided {
let alertController = UIAlertController(title: "Name not provided",
message: "Please provide a name to start the story",
preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
} catch let error {
fatalError("\(error.localizedDescription)")
}
}
}
func keyboardWillShow(_ notification: Notification){
if let info = notification.userInfo,
let keyboardFrame = info[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = keyboardFrame.cgRectValue
let padding = CGFloat(10)
textFieldBottomConstraint.constant = frame.size.height + padding
UIView.animate(withDuration: 0.8) {
self.view.layoutIfNeeded()
}
}
}
func keyboardWillHide(_ notification: Notification){
if let info = notification.userInfo,
let keyboardFrame = info[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = keyboardFrame.cgRectValue
let padding = CGFloat(10)
textFieldBottomConstraint.constant -= frame.size.height - padding
UIView.animate(withDuration: 0.8) {
self.view.layoutIfNeeded()
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
mit
|
766c7f4e3670120b4168f04e322e8469
| 38.229167 | 108 | 0.5547 | 6.214521 | false | false | false | false |
DSanzh/GuideMe-iOS
|
GuideMe/Controller/TourEventsVC.swift
|
1
|
1851
|
//
// TourEventsVC.swift
// GuideMe
//
// Created by Sanzhar on 9/20/17.
// Copyright © 2017 Sanzhar Dauylov. All rights reserved.
//
import UIKit
import EasyPeasy
class TourEventsVC: UIViewController {
lazy var tableView: UITableView = {
let _table = UITableView()
_table.delegate = self
_table.dataSource = self
_table.backgroundColor = .clear
_table.register(EventCell.self, forCellReuseIdentifier: "EventCell")
_table.tableFooterView = UIView()
_table.separatorStyle = .none
return _table
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupContraints()
}
private func setupViews() {
view.addSubview(tableView)
view.backgroundColor = ColorConstants.gmWhite
}
private func setupContraints() {
tableView.easy.layout([
Top(5.heightProportion()).to(view),
Left().to(view),
Right().to(view),
Bottom().to(view)
])
}
}
extension TourEventsVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: EventCell = tableView.dequeueReusableCell(withIdentifier: "EventCell", for: indexPath) as! EventCell
cell.configureCell()
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
|
mit
|
8b0a5efe7f76c87cc2f8d77911b7eab4
| 26.205882 | 118 | 0.637297 | 5.054645 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.