repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ctinnell/ct-playgrounds | refs/heads/master | HackerRank/GSTest.playground/Contents.swift | mit | 1 | import Foundation
func rangeFromNSRange(nsRange: NSRange, str: String) -> Range<String.Index>? {
let from16 = str.utf16.startIndex.advancedBy(nsRange.location, limit: str.utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: str.utf16.endIndex)
if let from = String.Index(from16, within: str),
let to = String.Index(to16, within: str) {
return from ..< to
}
return nil
}
func locate(stringToLocate: String, baseString: String) -> [Range<String.Index>] {
var ranges = [Range<String.Index>]()
do {
// Create the regular expression.
let regex = try NSRegularExpression(pattern: stringToLocate, options: [])
// Use the regular expression to get an array of NSTextCheckingResult.
// Use map to extract the range from each result.
ranges = regex.matchesInString(baseString, options: [], range: NSMakeRange(0, baseString.characters.count)).map({rangeFromNSRange($0.range, str: baseString)!})
}
catch {
// There was a problem creating the regular expression
ranges = []
}
return ranges
}
let results = locate("11111", baseString: "111111111111111")
print(results)
| 5158fb7ef46b30a0b2f7edddac8971c4 | 34.676471 | 167 | 0.663644 | false | false | false | false |
Zedenem/XMonsters | refs/heads/master | XMonsters/AboutViewController.swift | mit | 1 | //
// AboutViewController.swift
// XMonsters
//
// Created by Zouhair Mahieddine on 6/13/15.
// Copyright (c) 2015 Zedenem. All rights reserved.
//
import UIKit
import StoreKit
class AboutViewController: UITableViewController {
@IBOutlet weak var aboutLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Flurry.logEvent("about", timed: true)
}
@IBAction func dismiss(sender: UIBarButtonItem) {
Flurry.endTimedEvent("about", withParameters: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
aboutLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.view.frame)
let height = aboutLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 40
return height
}
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch (indexPath.section, indexPath.row) {
case (0, 1):
Flurry.logEvent("select_app_store")
presentAppStore()
case (0, 2):
Flurry.logEvent("select_twitter")
presentTwitter()
case (0, 3):
Flurry.logEvent("present_github")
presentGithub()
case (1, 0):
Flurry.logEvent("present_ffworld")
presentFFWorld()
case (1, 1):
Flurry.logEvent("present_ffwiki")
presentFFWiki()
default:break
}
}
func presentAppStore() {
Flurry.logEvent("present_app_store")
UIApplication.sharedApplication().openURL(NSURL(string: "https://itunes.apple.com/app/id981939574")!)
}
func presentTwitter() {
let app = UIApplication.sharedApplication()
if let twitterAppURL = NSURL(string: "twitter://user?screen_name=zedenem") {
if app.canOpenURL(twitterAppURL) {
Flurry.logEvent("present_twitter_app")
app.openURL(twitterAppURL)
return
}
}
Flurry.logEvent("present_twitter_web")
app.openURL(NSURL(string: "https://twitter.com/zedenem")!)
}
func presentGithub() {
UIApplication.sharedApplication().openURL(NSURL(string: "https://github.com/Zedenem/XMonsters")!)
}
func presentFFWorld() {
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.ffworld.com/?rub=ff10&page=q_arene")!)
}
func presentFFWiki() {
UIApplication.sharedApplication().openURL(NSURL(string: "http://finalfantasy.wikia.com/wiki/Monster_Arena")!)
}
}
extension AboutViewController: SKStoreProductViewControllerDelegate {
func productViewControllerDidFinish(viewController: SKStoreProductViewController!) {
Flurry.endTimedEvent("present_app_store", withParameters: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
} | 72336b519a1a3845d559d96b872b4df4 | 30.591398 | 113 | 0.707525 | false | false | false | false |
klundberg/swift-corelibs-foundation | refs/heads/master | TestFoundation/TestUtils.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
func ensureFiles(_ fileNames: [String]) -> Bool {
var result = true
let fm = FileManager.default()
for name in fileNames {
guard !fm.fileExists(atPath: name) else {
continue
}
if name.hasSuffix("/") {
do {
try fm.createDirectory(atPath: name, withIntermediateDirectories: true, attributes: nil)
} catch let err {
print(err)
return false
}
} else {
var isDir: ObjCBool = false
let dir = name.bridge().stringByDeletingLastPathComponent
if !fm.fileExists(atPath: dir, isDirectory: &isDir) {
do {
try fm.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
} catch let err {
print(err)
return false
}
} else if !isDir {
return false
}
result = result && fm.createFile(atPath: name, contents: nil, attributes: nil)
}
}
return result
}
| 0e5b6fe985f7d923a6780d7f1f73bd1f | 30.519231 | 107 | 0.565589 | false | false | false | false |
JackieQu/QP_DouYu | refs/heads/master | QP_DouYu/QP_DouYu/Classes/Home/View/RecommendGameView.swift | mit | 1 | //
// RecommendGameView.swift
// QP_DouYu
//
// Created by JackieQu on 2017/2/19.
// Copyright © 2017年 JackieQu. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetsMargin : CGFloat = 10
class RecommendGameView: UIView {
// MARK:- 定义数据的属性
var groups : [BaseGameModel]? {
didSet {
collectionView.reloadData()
}
}
// MARK:- 控件属性
@IBOutlet weak var collectionView: UICollectionView!
// MARK:- 系统回调
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = .init(rawValue: 0)
// 注册 cell
collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 设置 collectionView 内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetsMargin, bottom: 0, right: kEdgeInsetsMargin)
}
}
// MARK:- 提供快速创建的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
// MARK:- 遵守 UICollectionView 的数据源协议
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionViewGameCell
cell.baseGame = groups![indexPath.item]
// cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.blue
return cell
}
}
| 1848140ab4600c9186f81d77f9d2c028 | 29.758065 | 130 | 0.66387 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/swiftlint/Commands/RulesCommand.swift | mit | 1 | import Commandant
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Result
import SwiftLintFramework
import SwiftyTextTable
private func print(ruleDescription desc: RuleDescription) {
print("\(desc.consoleDescription)")
if !desc.triggeringExamples.isEmpty {
func indent(_ string: String) -> String {
return string.components(separatedBy: "\n")
.map { " \($0)" }
.joined(separator: "\n")
}
print("\nTriggering Examples (violation is marked with '↓'):")
for (index, example) in desc.triggeringExamples.enumerated() {
print("\nExample #\(index + 1)\n\n\(indent(example))")
}
}
}
struct RulesCommand: CommandProtocol {
let verb = "rules"
let function = "Display the list of rules and their identifiers"
func run(_ options: RulesOptions) -> Result<(), CommandantError<()>> {
if let ruleID = options.ruleID {
guard let rule = masterRuleList.list[ruleID] else {
return .failure(.usageError(description: "No rule with identifier: \(ruleID)"))
}
print(ruleDescription: rule.description)
return .success(())
}
if options.onlyDisabledRules && options.onlyEnabledRules {
return .failure(.usageError(description: "You can't use --disabled and --enabled at the same time."))
}
let configuration = Configuration(options: options)
let rules = ruleList(for: options, configuration: configuration)
print(TextTable(ruleList: rules, configuration: configuration).render())
return .success(())
}
private func ruleList(for options: RulesOptions, configuration: Configuration) -> RuleList {
guard options.onlyEnabledRules || options.onlyDisabledRules else {
return masterRuleList
}
let filtered: [Rule.Type] = masterRuleList.list.compactMap { ruleID, ruleType in
let configuredRule = configuration.rules.first { rule in
return type(of: rule).description.identifier == ruleID
}
if options.onlyEnabledRules && configuredRule == nil {
return nil
} else if options.onlyDisabledRules && configuredRule != nil {
return nil
}
return ruleType
}
return RuleList(rules: filtered)
}
}
struct RulesOptions: OptionsProtocol {
fileprivate let ruleID: String?
let configurationFile: String
fileprivate let onlyEnabledRules: Bool
fileprivate let onlyDisabledRules: Bool
// swiftlint:disable line_length
static func create(_ configurationFile: String) -> (_ ruleID: String) -> (_ onlyEnabledRules: Bool) -> (_ onlyDisabledRules: Bool) -> RulesOptions {
return { ruleID in { onlyEnabledRules in { onlyDisabledRules in
self.init(ruleID: (ruleID.isEmpty ? nil : ruleID),
configurationFile: configurationFile,
onlyEnabledRules: onlyEnabledRules,
onlyDisabledRules: onlyDisabledRules)
}}}
}
static func evaluate(_ mode: CommandMode) -> Result<RulesOptions, CommandantError<CommandantError<()>>> {
return create
<*> mode <| configOption
<*> mode <| Argument(defaultValue: "",
usage: "the rule identifier to display description for")
<*> mode <| Switch(flag: "e",
key: "enabled",
usage: "only display enabled rules")
<*> mode <| Switch(flag: "d",
key: "disabled",
usage: "only display disabled rules")
}
}
// MARK: - SwiftyTextTable
extension TextTable {
init(ruleList: RuleList, configuration: Configuration) {
let columns = [
TextTableColumn(header: "identifier"),
TextTableColumn(header: "opt-in"),
TextTableColumn(header: "correctable"),
TextTableColumn(header: "enabled in your config"),
TextTableColumn(header: "kind"),
TextTableColumn(header: "configuration")
]
self.init(columns: columns)
let sortedRules = ruleList.list.sorted { $0.0 < $1.0 }
func truncate(_ string: String) -> String {
let stringWithNoNewlines = string.replacingOccurrences(of: "\n", with: "\\n")
let minWidth = "configuration".count - "...".count
let configurationStartColumn = 112
let truncatedEndIndex = stringWithNoNewlines.index(
stringWithNoNewlines.startIndex,
offsetBy: max(minWidth, Terminal.currentWidth() - configurationStartColumn),
limitedBy: stringWithNoNewlines.endIndex
)
if let truncatedEndIndex = truncatedEndIndex {
return stringWithNoNewlines[..<truncatedEndIndex] + "..."
}
return stringWithNoNewlines
}
for (ruleID, ruleType) in sortedRules {
let rule = ruleType.init()
let configuredRule = configuration.rules.first { rule in
return type(of: rule).description.identifier == ruleID
}
addRow(values: [
ruleID,
(rule is OptInRule) ? "yes" : "no",
(rule is CorrectableRule) ? "yes" : "no",
configuredRule != nil ? "yes" : "no",
ruleType.description.kind.rawValue,
truncate((configuredRule ?? rule).configurationDescription)
])
}
}
}
struct Terminal {
static func currentWidth() -> Int {
var size = winsize()
#if os(Linux)
_ = ioctl(CInt(STDOUT_FILENO), UInt(TIOCGWINSZ), &size)
#else
_ = ioctl(STDOUT_FILENO, TIOCGWINSZ, &size)
#endif
return Int(size.ws_col)
}
}
| b9c3a74033e28cc15d20eedb2f0422f3 | 36.175 | 152 | 0.585575 | false | true | false | false |
vapor/vapor | refs/heads/main | Sources/Vapor/Response/Response+Body.swift | mit | 1 | extension Response {
struct BodyStream {
let count: Int
let callback: (BodyStreamWriter) -> ()
}
/// Represents a `Response`'s body.
///
/// let body = Response.Body(string: "Hello, world!")
///
/// This can contain any data (streaming or static) and should match the message's `"Content-Type"` header.
public struct Body: CustomStringConvertible, ExpressibleByStringLiteral {
/// The internal HTTP body storage enum. This is an implementation detail.
internal enum Storage {
/// Cases
case none
case buffer(ByteBuffer)
case data(Data)
case dispatchData(DispatchData)
case staticString(StaticString)
case string(String)
case stream(BodyStream)
}
/// An empty `Response.Body`.
public static let empty: Body = .init()
public var string: String? {
switch self.storage {
case .buffer(var buffer): return buffer.readString(length: buffer.readableBytes)
case .data(let data): return String(decoding: data, as: UTF8.self)
case .dispatchData(let dispatchData): return String(decoding: dispatchData, as: UTF8.self)
case .staticString(let staticString): return staticString.description
case .string(let string): return string
default: return nil
}
}
/// The size of the HTTP body's data.
/// `-1` is a chunked stream.
public var count: Int {
switch self.storage {
case .data(let data): return data.count
case .dispatchData(let data): return data.count
case .staticString(let staticString): return staticString.utf8CodeUnitCount
case .string(let string): return string.utf8.count
case .buffer(let buffer): return buffer.readableBytes
case .none: return 0
case .stream(let stream): return stream.count
}
}
/// Returns static data if not streaming.
public var data: Data? {
switch self.storage {
case .buffer(var buffer): return buffer.readData(length: buffer.readableBytes)
case .data(let data): return data
case .dispatchData(let dispatchData): return Data(dispatchData)
case .staticString(let staticString): return Data(bytes: staticString.utf8Start, count: staticString.utf8CodeUnitCount)
case .string(let string): return Data(string.utf8)
case .none: return nil
case .stream: return nil
}
}
public var buffer: ByteBuffer? {
switch self.storage {
case .buffer(let buffer): return buffer
case .data(let data):
let buffer = self.byteBufferAllocator.buffer(bytes: data)
return buffer
case .dispatchData(let dispatchData):
let buffer = self.byteBufferAllocator.buffer(dispatchData: dispatchData)
return buffer
case .staticString(let staticString):
let buffer = self.byteBufferAllocator.buffer(staticString: staticString)
return buffer
case .string(let string):
let buffer = self.byteBufferAllocator.buffer(string: string)
return buffer
case .none: return nil
case .stream: return nil
}
}
public func collect(on eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer?> {
switch self.storage {
case .stream(let stream):
let collector = ResponseBodyCollector(eventLoop: eventLoop, byteBufferAllocator: self.byteBufferAllocator)
stream.callback(collector)
return collector.promise.futureResult
.map { $0 }
default:
return eventLoop.makeSucceededFuture(self.buffer)
}
}
/// See `CustomDebugStringConvertible`.
public var description: String {
switch storage {
case .none: return "<no body>"
case .buffer(let buffer): return buffer.getString(at: 0, length: buffer.readableBytes) ?? "n/a"
case .data(let data): return String(data: data, encoding: .ascii) ?? "n/a"
case .dispatchData(let data): return String(data: Data(data), encoding: .ascii) ?? "n/a"
case .staticString(let string): return string.description
case .string(let string): return string
case .stream: return "<stream>"
}
}
internal var storage: Storage
internal let byteBufferAllocator: ByteBufferAllocator
/// Creates an empty body. Useful for `GET` requests where HTTP bodies are forbidden.
public init(byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
self.storage = .none
}
/// Create a new body wrapping `Data`.
public init(data: Data, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
storage = .data(data)
}
/// Create a new body wrapping `DispatchData`.
public init(dispatchData: DispatchData, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
storage = .dispatchData(dispatchData)
}
/// Create a new body from the UTF8 representation of a `StaticString`.
public init(staticString: StaticString, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
storage = .staticString(staticString)
}
/// Create a new body from the UTF8 representation of a `String`.
public init(string: String, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
self.storage = .string(string)
}
/// Create a new body from a Swift NIO `ByteBuffer`.
public init(buffer: ByteBuffer, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
self.storage = .buffer(buffer)
}
public init(stream: @escaping (BodyStreamWriter) -> (), count: Int, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.byteBufferAllocator = byteBufferAllocator
self.storage = .stream(.init(count: count, callback: stream))
}
public init(stream: @escaping (BodyStreamWriter) -> (), byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator()) {
self.init(stream: stream, count: -1, byteBufferAllocator: byteBufferAllocator)
}
/// `ExpressibleByStringLiteral` conformance.
public init(stringLiteral value: String) {
self.byteBufferAllocator = ByteBufferAllocator()
self.storage = .string(value)
}
/// Internal init.
internal init(storage: Storage, byteBufferAllocator: ByteBufferAllocator) {
self.byteBufferAllocator = byteBufferAllocator
self.storage = storage
}
}
}
private final class ResponseBodyCollector: BodyStreamWriter {
var buffer: ByteBuffer
var eventLoop: EventLoop
var promise: EventLoopPromise<ByteBuffer>
init(eventLoop: EventLoop, byteBufferAllocator: ByteBufferAllocator) {
self.buffer = byteBufferAllocator.buffer(capacity: 0)
self.eventLoop = eventLoop
self.promise = self.eventLoop.makePromise(of: ByteBuffer.self)
}
func write(_ result: BodyStreamResult, promise: EventLoopPromise<Void>?) {
switch result {
case .buffer(var buffer):
self.buffer.writeBuffer(&buffer)
case .error(let error):
self.promise.fail(error)
case .end:
self.promise.succeed(self.buffer)
}
promise?.succeed(())
}
}
| eb6443860c8b08e286db3d8a80109c30 | 41.897436 | 143 | 0.608966 | false | false | false | false |
edragoev1/pdfjet | refs/heads/master | Sources/PDFjet/BarCode.swift | mit | 1 | /**
* BarCode.swift
*
Copyright 2020 Innovatics Inc.
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
///
/// Used to create one dimentional barcodes - UPC, Code 39 and Code 128.
///
/// Please see Example_11.
///
public class BarCode : Drawable {
public static let UPC = 0
public static let CODE128 = 1
public static let CODE39 = 2
public static let LEFT_TO_RIGHT = 0
public static let TOP_TO_BOTTOM = 1
public static let BOTTOM_TO_TOP = 2
private var barcodeType = 0
private var text: String
private var x1: Float = 0.0
private var y1: Float = 0.0
private var m1: Float = 0.75 // Module length
private var barHeightFactor: Float = 50.0
private var direction = LEFT_TO_RIGHT
private var font: Font?
private let tableA = [3211,2221,2122,1411,1132,1231,1114,1312,1213,3112]
private var tableB = [String : String]()
///
/// The constructor.
///
/// @param type the type of the barcode.
/// @param text the content string of the barcode.
///
public init(
_ barcodeType: Int,
_ text: String) {
self.barcodeType = barcodeType
self.text = text
tableB["*"] = "bWbwBwBwb"
tableB["-"] = "bWbwbwBwB"
tableB["$"] = "bWbWbWbwb"
tableB["%"] = "bwbWbWbWb"
tableB[" "] = "bWBwbwBwb"
tableB["."] = "BWbwbwBwb"
tableB["/"] = "bWbWbwbWb"
tableB["+"] = "bWbwbWbWb"
tableB["0"] = "bwbWBwBwb"
tableB["1"] = "BwbWbwbwB"
tableB["2"] = "bwBWbwbwB"
tableB["3"] = "BwBWbwbwb"
tableB["4"] = "bwbWBwbwB"
tableB["5"] = "BwbWBwbwb"
tableB["6"] = "bwBWBwbwb"
tableB["7"] = "bwbWbwBwB"
tableB["8"] = "BwbWbwBwb"
tableB["9"] = "bwBWbwBwb"
tableB["A"] = "BwbwbWbwB"
tableB["B"] = "bwBwbWbwB"
tableB["C"] = "BwBwbWbwb"
tableB["D"] = "bwbwBWbwB"
tableB["E"] = "BwbwBWbwb"
tableB["F"] = "bwBwBWbwb"
tableB["G"] = "bwbwbWBwB"
tableB["H"] = "BwbwbWBwb"
tableB["I"] = "bwBwbWBwb"
tableB["J"] = "bwbwBWBwb"
tableB["K"] = "BwbwbwbWB"
tableB["L"] = "bwBwbwbWB"
tableB["M"] = "BwBwbwbWb"
tableB["N"] = "bwbwBwbWB"
tableB["O"] = "BwbwBwbWb"
tableB["P"] = "bwBwBwbWb"
tableB["Q"] = "bwbwbwBWB"
tableB["R"] = "BwbwbwBWb"
tableB["S"] = "bwBwbwBWb"
tableB["T"] = "bwbwBwBWb"
tableB["U"] = "BWbwbwbwB"
tableB["V"] = "bWBwbwbwB"
tableB["W"] = "BWBwbwbwb"
tableB["X"] = "bWbwBwbwB"
tableB["Y"] = "BWbwBwbwb"
tableB["Z"] = "bWBwBwbwb"
}
public func setPosition(_ x1: Float, _ y1: Float) {
setLocation(x1, y1)
}
///
/// Sets the location where this barcode will be drawn on the page.
///
/// @param x1 the x coordinate of the top left corner of the barcode.
/// @param y1 the y coordinate of the top left corner of the barcode.
///
public func setLocation(_ x1: Float, _ y1: Float) {
self.x1 = x1
self.y1 = y1
}
///
/// Sets the module length of this barcode.
/// The default value is 0.75
///
/// @param moduleLength the specified module length.
///
public func setModuleLength(_ moduleLength: Double) {
self.m1 = Float(moduleLength)
}
///
/// Sets the module length of this barcode.
/// The default value is 0.75
///
/// @param moduleLength the specified module length.
///
public func setModuleLength(_ moduleLength: Float) {
self.m1 = moduleLength
}
///
/// Sets the bar height factor.
/// The height of the bars is the moduleLength * barHeightFactor
/// The default value is 50.0
///
/// @param barHeightFactor the specified bar height factor.
///
public func setBarHeightFactor(_ barHeightFactor: Double) {
self.barHeightFactor = Float(barHeightFactor)
}
///
/// Sets the bar height factor.
/// The height of the bars is the moduleLength * barHeightFactor
/// The default value is 50.0f
///
/// @param barHeightFactor the specified bar height factor.
///
public func setBarHeightFactor(_ barHeightFactor: Float) {
self.barHeightFactor = barHeightFactor
}
///
/// Sets the drawing direction for this font.
///
/// @param direction the specified direction.
///
public func setDirection(_ direction: Int) {
self.direction = direction
}
///
/// Sets the font to be used with this barcode.
///
/// @param font the specified font.
///
public func setFont(_ font: Font) {
self.font = font
}
///
/// Draws this barcode on the specified page.
///
/// @param page the specified page.
/// @return x and y coordinates of the bottom right corner of this component.
/// @throws Exception
///
@discardableResult
public func drawOn(_ page: Page?) -> [Float] {
if barcodeType == BarCode.UPC {
return drawCodeUPC(page, x1, y1)
}
else if barcodeType == BarCode.CODE128 {
return drawCode128(page, x1, y1)
}
else if barcodeType == BarCode.CODE39 {
return drawCode39(page, x1, y1)
}
else {
Swift.print("Unsupported Barcode Type.")
}
return [Float]()
}
@discardableResult
func drawOnPageAtLocation(_ page: Page?, _ x1: Float, _ y1: Float) -> [Float] {
if (barcodeType == BarCode.UPC) {
return drawCodeUPC(page, x1, y1)
}
else if (barcodeType == BarCode.CODE128) {
return drawCode128(page, x1, y1)
}
else if (barcodeType == BarCode.CODE39) {
return drawCode39(page, x1, y1)
}
else {
Swift.print("Unsupported Barcode Type.")
}
return [Float]()
}
private func drawCodeUPC(_ page: Page?, _ x1: Float, _ y1: Float) -> [Float] {
var x: Float = x1
let y: Float = y1
let h: Float = m1 * barHeightFactor // Barcode height when drawn horizontally
// Calculate the check digit:
// 1. Add the digits in the odd-numbered positions (first, third, fifth, etc.)
// together and multiply by three.
// 2. Add the digits in the even-numbered positions (second, fourth, sixth, etc.)
// to the result.
// 3. Subtract the result modulo 10 from ten.
// 4. The answer modulo 10 is the check digit.
var scalars = Array(text.unicodeScalars)
var sum = 0
var i = 0
while i < 11 {
sum += Int(scalars[i].value) - 48
i += 2
}
sum *= 3
i = 1
while i < 11 {
sum += Int(scalars[i].value) - 48
i += 2
}
let reminder = sum % 10
let checkDigit = UInt16((10 - reminder) % 10)
scalars.append(UnicodeScalar(checkDigit)!)
x = drawEGuard(page, x, y, m1, h + 8)
i = 0
while i < 6 {
let digit = Int(scalars[i].value) - 0x30
let symbols = Array(String(tableA[digit]).unicodeScalars)
for j in 0..<symbols.count {
let n = symbols[j].value - 0x30
if j%2 != 0 {
drawVertBar(page, x, y, Float(n)*m1, h)
}
x += Float(n)*m1
}
i += 1
}
x = drawMGuard(page, x, y, m1, h + 8)
i = 6
while i < 12 {
let digit = Int(scalars[i].value) - 0x30
let symbols = Array(String(tableA[digit]).unicodeScalars)
for j in 0..<symbols.count {
let n = symbols[j].value - 0x30
if j%2 == 0 {
drawVertBar(page, x, y, Float(n)*m1, h)
}
x += Float(n)*m1
}
i += 1
}
x = drawEGuard(page, x, y, m1, h + 8)
var xy = [x, y]
if font != nil {
var label = String(scalars[0])
label += " "
label += String(scalars[1])
label += String(scalars[2])
label += String(scalars[3])
label += String(scalars[4])
label += String(scalars[5])
label += " "
label += String(scalars[6])
label += String(scalars[7])
label += String(scalars[8])
label += String(scalars[9])
label += String(scalars[10])
label += " "
label += String(scalars[11])
let fontSize = font!.getSize()
font!.setSize(10.0)
let text = TextLine(font!, label)
.setLocation(
x1 + ((x - x1) - font!.stringWidth(label))/2,
y1 + h + font!.bodyHeight)
xy = text.drawOn(page)
xy[0] = max(x, xy[0])
xy[1] = max(y, xy[1])
font!.setSize(fontSize)
return [xy[0], xy[1] + font!.descent]
}
return [xy[0], xy[1]]
}
private func drawEGuard(
_ page: Page?,
_ x: Float,
_ y: Float,
_ m1: Float,
_ h: Float) -> Float {
if page != nil {
// 101
drawBar(page, x + (0.5 * m1), y, m1, h)
drawBar(page, x + (2.5 * m1), y, m1, h)
}
return (x + (3.0 * m1))
}
private func drawMGuard(
_ page: Page?,
_ x: Float,
_ y: Float,
_ m1: Float,
_ h: Float) -> Float {
if page != nil {
// 01010
drawBar(page, x + (1.5 * m1), y, m1, h)
drawBar(page, x + (3.5 * m1), y, m1, h)
}
return (x + (5.0 * m1))
}
private func drawBar(
_ page: Page?,
_ x: Float,
_ y: Float,
_ m1: Float, // Single bar width
_ h: Float) {
if page != nil {
page!.setPenWidth(m1)
page!.moveTo(x, y)
page!.lineTo(x, y + h)
page!.strokePath()
}
}
private func drawCode128(_ page: Page?, _ x1: Float, _ y1: Float) -> [Float] {
var x: Float = x1
var y: Float = y1
var w: Float = m1
var h: Float = m1
if direction == BarCode.TOP_TO_BOTTOM {
w *= barHeightFactor
}
else if direction == BarCode.LEFT_TO_RIGHT {
h *= barHeightFactor
}
var list = [UInt16]()
for symchar in text.unicodeScalars {
if symchar.value < 32 {
list.append(UInt16(GS1_128.SHIFT))
list.append(UInt16(symchar.value + 64))
}
else if symchar.value < 128 {
list.append(UInt16(symchar.value - 32))
}
else if symchar.value < 256 {
list.append(UInt16(GS1_128.FNC_4))
list.append(UInt16(symchar.value - 160)) // 128 + 32
}
else {
// list.append(UInt16(31)) // '?'
list.append(UInt16(256)) // This will generate an exception.
}
if list.count == 48 {
// Maximum number of data characters is 48
break
}
}
var buf = String()
var checkDigit = GS1_128.START_B
buf.append(String(UnicodeScalar(checkDigit)!))
for i in 0..<list.count {
let codeword = list[i]
buf.append(String(UnicodeScalar(codeword)!))
checkDigit += Int(codeword) * Int(i + 1)
}
checkDigit %= GS1_128.START_A
buf.append(String(UnicodeScalar(checkDigit)!))
buf.append(String(UnicodeScalar(GS1_128.STOP)!))
let scalars = [UnicodeScalar](buf.unicodeScalars)
for scalar in scalars {
let symbol = String(GS1_128.TABLE[Int(scalar.value)])
var j = 0
for scalar in symbol.unicodeScalars {
let n = Int(scalar.value) - 0x30
if j%2 == 0 {
if direction == BarCode.LEFT_TO_RIGHT {
drawVertBar(page, x, y, m1 * Float(n), h)
}
else if direction == BarCode.TOP_TO_BOTTOM {
drawHorzBar(page, x, y, m1 * Float(n), w)
}
}
if direction == BarCode.LEFT_TO_RIGHT {
x += Float(n) * m1
}
else if direction == BarCode.TOP_TO_BOTTOM {
y += Float(n) * m1
}
j += 1
}
}
var xy = [x, y]
if font != nil {
if direction == BarCode.LEFT_TO_RIGHT {
let textLine = TextLine(font!, text)
.setLocation(x1 + ((x - x1) - font!.stringWidth(text))/2, y1 + h + font!.bodyHeight)
xy = textLine.drawOn(page)
xy[0] = max(x, xy[0])
return [xy[0], xy[1] + font!.descent]
}
else if direction == BarCode.TOP_TO_BOTTOM {
let textLine = TextLine(font!, text)
.setLocation(
x + w + font!.bodyHeight,
y - ((y - y1) - font!.stringWidth(text))/2)
.setTextDirection(90)
xy = textLine.drawOn(page)
xy[1] = max(y, xy[1])
}
}
return xy
}
private func drawCode39(_ page: Page?, _ x1: Float, _ y1: Float) -> [Float] {
text = "*" + text + "*"
var x: Float = x1
var y: Float = y1
let w: Float = m1 * barHeightFactor // Barcode width when drawn vertically
let h: Float = m1 * barHeightFactor // Barcode height when drawn horizontally
var xy: [Float] = [0.0, 0.0]
if direction == BarCode.LEFT_TO_RIGHT {
for symchar in text.unicodeScalars {
let code = tableB[String(symchar)]
if code == nil {
Swift.print("The input string '" + text +
"' contains characters that are invalid in a Code39 barcode.")
}
else {
let scalars = Array(code!.unicodeScalars)
for i in 0..<9 {
let ch = String(scalars[i])
if ch == "w" {
x += m1
}
else if ch == "W" {
x += m1 * 3
}
else if ch == "b" {
drawVertBar(page, x, y, m1, h)
x += m1
}
else if ch == "B" {
drawVertBar(page, x, y, m1 * 3, h)
x += m1 * 3
}
}
x += m1
}
}
if font != nil {
let textLine = TextLine(font!, text)
.setLocation(
x1 + ((x - x1) - font!.stringWidth(text))/2,
y1 + h + font!.bodyHeight)
xy = textLine.drawOn(page)
xy[0] = max(x, xy[0])
}
}
else if direction == BarCode.TOP_TO_BOTTOM {
for symchar in text.unicodeScalars {
let code = tableB[String(symchar)]
if code == nil {
Swift.print("The input string '" + text +
"' contains characters that are invalid in a Code39 barcode.")
}
else {
let scalars = Array(code!.unicodeScalars)
for i in 0..<9 {
let ch = String(scalars[i])
if ch == "w" {
y += m1
}
else if ch == "W" {
y += 3 * m1
}
else if ch == "b" {
drawHorzBar(page, x, y, m1, h)
y += m1
}
else if ch == "B" {
drawHorzBar(page, x, y, 3 * m1, h)
y += 3 * m1
}
}
y += m1
}
}
if font != nil {
let textLine = TextLine(font!, text)
.setLocation(
x - font!.bodyHeight,
y1 + ((y - y1) - font!.stringWidth(text))/2)
.setTextDirection(270)
xy = textLine.drawOn(page)
xy[0] = max(x, xy[0]) + w
xy[1] = max(y, xy[1])
}
}
else if direction == BarCode.BOTTOM_TO_TOP {
var height: Float = 0.0
for symchar in text.unicodeScalars {
let code = tableB[String(symchar)]
if code == nil {
Swift.print("The input string '" + text +
"' contains characters that are invalid in a Code39 barcode.")
}
else {
let scalar = Array(code!.unicodeScalars)
for i in 0..<9 {
let ch = String(scalar[i])
if ch == "w" || ch == "b" {
height += m1
}
else if ch == "W" || ch == "B" {
height += 3 * m1
}
}
height += m1
}
}
y += height - m1
for symchar in text.unicodeScalars {
let code = tableB[String(symchar)]
if code == nil {
Swift.print("The input string '" + text +
"' contains characters that are invalid in a Code39 barcode.")
}
else {
let scalars = Array(code!.unicodeScalars)
for i in 0..<9 {
let ch = String(scalars[i])
if ch == "w" {
y -= m1
}
else if ch == "W" {
y -= 3 * m1
}
else if ch == "b" {
drawHorzBar2(page, x, y, m1, h)
y -= m1
}
else if ch == "B" {
drawHorzBar2(page, x, y, 3 * m1, h)
y -= 3 * m1
}
}
y -= m1
}
}
if font != nil {
y = y1 + ( height - m1)
let textLine = TextLine(font!, text)
.setLocation(
x + w + font!.bodyHeight,
y - ((y - y1) - font!.stringWidth(text))/2)
.setTextDirection(90)
xy = textLine.drawOn(page)
xy[1] = max(y, xy[1])
return [xy[0], xy[1] + font!.descent]
}
}
return [xy[0], xy[1]]
}
private func drawVertBar(
_ page: Page?,
_ x: Float,
_ y: Float,
_ m1: Float, // Module length
_ h: Float) {
if page != nil {
page!.setPenWidth(m1)
page!.moveTo(x + m1/2, y)
page!.lineTo(x + m1/2, y + h)
page!.strokePath()
}
}
private func drawHorzBar(
_ page: Page?,
_ x: Float,
_ y: Float,
_ m1: Float, // Module length
_ w: Float) {
if page != nil {
page!.setPenWidth(m1)
page!.moveTo(x, y + m1/2)
page!.lineTo(x + w, y + m1/2)
page!.strokePath()
}
}
private func drawHorzBar2(
_ page: Page?,
_ x: Float,
_ y: Float,
_ m1: Float, // Module length
_ w: Float) {
if page != nil {
page!.setPenWidth(m1)
page!.moveTo(x, y - m1/2)
page!.lineTo(x + w, y - m1/2)
page!.strokePath()
}
}
public func getHeight() -> Float {
if font == nil {
return m1 * barHeightFactor
}
return m1 * barHeightFactor + font!.getHeight()
}
} // End of BarCode.swift
| 51a148bcac0ae64a9db730ab82fcf931 | 30.90634 | 108 | 0.447275 | false | false | false | false |
iCrany/iOSExample | refs/heads/master | iOSExample/Module/QuartzCore/QuartzCoreTableViewController.swift | mit | 1 | //
// QuartzCoreTableViewController.swift
// iOSExample
//
// Created by iCrany on 2017/6/21.
// Copyright (c) 2017 iCrany. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
class QuartzCoreTableViewController: UIViewController {
struct Constant {
static let kLayerExample1 = "GradientLayerExample1"
static let kLayerExample2 = "GradientLayerExample2"
static let kLayerExample3 = "Layer HitTest Example"
static let kLayerExample4 = "Circle progress Example"
static let kLayerExample5 = "Raywenderlich CoreGraphic Example1"
static let kLayerExample6 = "UIImage to gray image"
}
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain)
tableView.tableFooterView = UIView.init()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kLayerExample1)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kLayerExample2)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kLayerExample3)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kLayerExample4)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kLayerExample5)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kLayerExample6)
return tableView
}()
fileprivate var dataSource: [String] = []
init() {
super.init(nibName: nil, bundle: nil)
self.prepareDataSource()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "QuartzCore Example"
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { maker in
maker.edges.equalTo(self.view)
}
}
private func prepareDataSource() {
self.dataSource.append(Constant.kLayerExample1)
self.dataSource.append(Constant.kLayerExample2)
self.dataSource.append(Constant.kLayerExample3)
self.dataSource.append(Constant.kLayerExample4)
self.dataSource.append(Constant.kLayerExample5)
}
}
extension QuartzCoreTableViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedDataSourceStr = self.dataSource[indexPath.row]
switch selectedDataSourceStr {
case Constant.kLayerExample1:
let vc: QuartzCoreViewController = QuartzCoreViewController.init(viewType: .GradientExample1)
self.navigationController?.pushViewController(vc, animated: true)
case Constant.kLayerExample2:
let vc: QuartzCoreViewController = QuartzCoreViewController.init(viewType: .GradientExample2)
self.navigationController?.pushViewController(vc, animated: true)
case Constant.kLayerExample3:
let vc: CALayerHitTestViewController = CALayerHitTestViewController.init()
self.navigationController?.pushViewController(vc, animated: true)
case Constant.kLayerExample4:
let vc: CircleViewController = CircleViewController()
self.navigationController?.pushViewController(vc, animated: true)
case Constant.kLayerExample5:
let vc: CoreGraphicsRayExampleVC = CoreGraphicsRayExampleVC()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
}
extension QuartzCoreTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSourceStr: String = self.dataSource[indexPath.row]
let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: dataSourceStr)
if let cell = tableViewCell {
cell.textLabel?.text = dataSourceStr
cell.textLabel?.textColor = UIColor.black
return cell
} else {
return UITableViewCell.init(style: .default, reuseIdentifier: "error")
}
}
}
| 3d90ae9b2cfe950999434dd8b70f2198 | 36.837398 | 106 | 0.702836 | false | false | false | false |
open-telemetry/opentelemetry-swift | refs/heads/main | Sources/Exporters/DatadogExporter/Persistence/FileReader.swift | apache-2.0 | 1 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
internal struct Batch {
/// Data read from file, prefixed with `[` and suffixed with `]`.
let data: Data
/// File from which `data` was read.
fileprivate let file: ReadableFile
}
internal final class FileReader {
/// Data reading format.
private let dataFormat: DataFormat
/// Orchestrator producing reference to readable file.
private let orchestrator: FilesOrchestrator
/// Files marked as read.
private var filesRead: [ReadableFile] = []
init(dataFormat: DataFormat, orchestrator: FilesOrchestrator) {
self.dataFormat = dataFormat
self.orchestrator = orchestrator
}
// MARK: - Reading batches
func readNextBatch() -> Batch? {
if let file = orchestrator.getReadableFile(excludingFilesNamed: Set(filesRead.map { $0.name })) {
do {
let fileData = try file.read()
let batchData = dataFormat.prefixData + fileData + dataFormat.suffixData
return Batch(data: batchData, file: file)
} catch {
print("Failed to read data from file")
return nil
}
}
return nil
}
/// This method gets remaining files at once, and process each file after with the block passed.
/// Currently called from flush method
func onRemainingBatches(process: (Batch) -> ()) -> Bool {
do {
try orchestrator.getAllFiles(excludingFilesNamed: Set(filesRead.map { $0.name }))?.forEach {
let fileData = try $0.read()
let batchData = dataFormat.prefixData + fileData + dataFormat.suffixData
process(Batch(data: batchData, file: $0))
}
} catch {
return false
}
return true
}
// MARK: - Accepting batches
func markBatchAsRead(_ batch: Batch) {
orchestrator.delete(readableFile: batch.file)
filesRead.append(batch.file)
}
}
| e02fd40b797b1abca202cf3c86a76521 | 30.348485 | 105 | 0.609957 | false | false | false | false |
softwarejoint/BERT-Swift | refs/heads/master | Sources/BertDecoder.swift | mit | 1 | //
// BertDecoder.swift
//
// Created by Pankaj Soni on 06/10/16.
// Copyright © 2017-2021 pankaj soni. All rights reserved.
//
import BigInt
import Foundation
public class BertDecoder: Bert {
private var decodeAtomAsString = false
private var decodePropListsAsMap = false
private var decodeMapKeysAsString = false
private var keys: NSMutableArray!
private var ptr: UnsafePointer<UInt8>!
public func withDecodeAtomAsString(decodeAtomAsString : Bool) -> BertDecoder {
self.decodeAtomAsString = decodeAtomAsString
return self
}
public func withDecodePropListsAsMap(decodePropListsAsMap : Bool)-> BertDecoder {
self.decodePropListsAsMap = decodePropListsAsMap
return self
}
public func withDecodeMapKeysAsString(decodeMapKeysAsString : Bool) -> BertDecoder {
self.decodeMapKeysAsString = decodeMapKeysAsString
return self
}
public func withDecodeBinaryAsStringForKey(key: NSObject) -> BertDecoder {
if (keys == nil){
keys = NSMutableArray()
}
keys.add(key)
return self
}
public func shouldDecodeBinaryAsStringForKey(key: NSObject) -> Bool {
if (keys == nil) {
return false
}
return (keys.index(of: key) != NSNotFound)
}
public func decodeAny(data: Data) -> Any? {
if data.count == 0 {
return nil
}
data.withUnsafeBytes { (rawptr: UnsafeRawBufferPointer) in
ptr = rawptr.bindMemory(to: UInt8.self).baseAddress!
}
if (ptr.pointee == MAGIC){
advancePtrBy(n: 1)
let result = decode()
ptr = nil
return result
}
return nil
}
private func decode() -> Any? {
let type: UInt8 = ptr[0];
advancePtrBy(n: 1)
switch type {
case NIL_EXT:
return [Any]()
case SMALL_INTEGER_EXT:
return decodeByte()
case INTEGER_EXT:
return decodeInteger()
case NEW_FLOAT_EXT:
return decodeDouble()
case SMALL_BIG_EXT:
return decodeLongOrBigInteger(tag: SMALL_BIG_EXT)
case LARGE_BIG_EXT:
return decodeLongOrBigInteger(tag: LARGE_BIG_EXT)
case ATOM_EXT:
return decodeAtom(tag: ATOM_EXT)
case SMALL_ATOM_EXT:
return decodeAtom(tag: SMALL_ATOM_EXT)
case STRING_EXT:
return decodeString()
case BINARY_EXT:
return decodeBinary()
case LIST_EXT:
return decodeArray()
case SMALL_TUPLE_EXT:
return decodeTuple(tag: SMALL_TUPLE_EXT)
case LARGE_TUPLE_EXT:
return decodeTuple(tag: LARGE_TUPLE_EXT)
case MAP_EXT:
return decodeMap()
default:
print("ERROR: Un decodable data received \(type)")
return nil
}
}
private func decodeByte() -> NSNumber {
let num = NSNumber(value: ptr[0])
advancePtrBy(n: MemoryLayout<UInt8>.size)
return num
}
private func decodeShort() -> NSNumber {
let result = ptr.withMemoryRebound(to: Int16.self, capacity: 1) { ptr -> NSNumber in
let i = Int16(bigEndian: ptr.pointee)
return NSNumber(value: i)
}
advancePtrBy(n: MemoryLayout<Int16>.size)
return result
}
private func decodeInteger() -> NSNumber {
let result = ptr.withMemoryRebound(to: Int32.self, capacity: 1) { ptr -> NSNumber in
let i = Int32(bigEndian: ptr.pointee)
return NSNumber(value: i)
}
advancePtrBy(n: MemoryLayout<Int32>.size)
return result
}
private func decodeDouble() -> Double {
let array = Array(UnsafeBufferPointer(start: ptr, count: MemoryLayout<Double>.size).reversed())
advancePtrBy(n: MemoryLayout<Double>.size)
return array.withUnsafeBufferPointer { (ptr) -> Double in
let baseAddr = ptr.baseAddress!
return baseAddr.withMemoryRebound(to: Double.self, capacity: 1, { (ptr) -> Double in
return ptr.pointee
})
}
}
private func decodeLongOrBigInteger(tag: UInt8) -> Any? {
var byteCount: NSNumber!
switch tag {
case SMALL_BIG_EXT:
byteCount = decodeByte()
case LARGE_BIG_EXT:
byteCount = decodeInteger()
default:
return nil
}
let sign = decodeByte() == 1 ? BigInt.Sign.minus : BigInt.Sign.plus
let array = Array(UnsafeBufferPointer<UInt8>(start: ptr, count: byteCount.intValue).reversed())
let bytes = Data(bytes: array, count: byteCount.intValue)
advancePtrBy(n: byteCount.intValue)
let bigInt = BigInt(sign: sign, magnitude: BigUInt(bytes))
return NSNumber(value: (bigInt.description as NSString).longLongValue)
}
private func decodeAtom(tag: UInt8) -> Any? {
var byteCount: NSNumber!
switch tag {
case ATOM_EXT:
byteCount = decodeShort()
case SMALL_ATOM_EXT:
byteCount = decodeByte()
default:
return nil
}
var atom: String?
if byteCount.intValue > 0 {
atom = decodeString(byteCount: byteCount)
}
if (atom == nil || atom!.isEmpty) {
return nil
}
if atom == "true" {
return true
}
else if atom == "false" {
return false
}
else if (decodeAtomAsString) {
return atom
}
else {
return BertAtom(atom: atom!)
}
}
private func decodeString() -> String? {
let byteCount: NSNumber = decodeShort()
return decodeString(byteCount: byteCount)
}
private func decodeBinary() -> Data {
let byteCount = decodeInteger()
return decodeData(byteCount: byteCount)
}
private func decodeArray() -> Any {
let numElements = decodeInteger().intValue
var canDecodeAsMap: Bool = decodePropListsAsMap
let array: AnyObject = NSMutableArray()
for _ in 0..<numElements {
let decoded = decode()
canDecodeAsMap =
canDecodeAsMap &&
(decoded is BertTuple) &&
(decoded as! BertTuple).isKV()
array.add(decoded as AnyObject)
}
if decodeByte().uint8Value != NIL_EXT {
let _ = ptr.predecessor()
}
if (canDecodeAsMap){
let dict = NSMutableDictionary()
for tuple in array as! [BertTuple] {
dict.setObject(tuple.object(at: 1), forKey: tuple.object(at: 0) as! NSCopying)
}
return dict
}
return array
}
private func decodeTuple(tag: UInt8) -> Any? {
var elements: NSNumber
switch tag {
case SMALL_TUPLE_EXT:
elements = decodeByte()
case LARGE_TUPLE_EXT:
elements = decodeInteger()
default:
return nil
}
let tuple = BertTuple()
for _ in stride(from: 0, to: elements.intValue, by: 1) {
tuple.add(decode() as AnyObject)
}
return tuple
}
private func decodeMap() -> Dictionary<NSObject, Any> {
let numElements = decodeInteger().intValue
var dict = Dictionary<NSObject, Any>()
for _ in stride(from: 0, to: numElements, by: 1) {
let key = decodeMapKey()
let value = decodeMapValue(key: key)
guard let dictKey = key as? NSObject else { continue }
if let val = value {
dict[dictKey] = val
} else if let val = value as? String{
dict[dictKey] = val
} else if let val = value as? Array<AnyObject>{
dict[dictKey] = val
} else {
print("ERROR: unparsed value = \(String(describing: value)) for key = \(String(describing: key))")
}
}
return dict
}
private func decodeMapKey() -> Any? {
let key = decode()
if !decodeMapKeysAsString {
return key
}
if key is String {
return key
}
if key is BertAtom {
return (key as! BertAtom).stringVal
}
if key is Data {
return String(data: key as! Data, encoding: String.Encoding.utf8)
}
return String(describing: key)
}
private func decodeMapValue(key: Any?) -> Any? {
if (key == nil) {
return nil
}
let value = decode()
if shouldDecodeBinaryAsStringForKey(key: key as! NSObject) {
switch value {
case nil: return nil
case let array as Array<Data>:
return array.map { String(data: $0 as Data, encoding: String.Encoding.utf8)!}
case let value as Data:
return String(data: value, encoding: String.Encoding.utf8)
default:
break
}
}
return value
}
private func decodeString(byteCount: NSNumber) -> String? {
let data: Data = decodeData(byteCount: byteCount)
return String(data: data, encoding: String.Encoding.utf8)
}
private func decodeData(byteCount: NSNumber) -> Data {
let data = Data(bytes: ptr, count: byteCount.intValue)
advancePtrBy(n: byteCount.intValue)
return data
}
private func advancePtrBy(n: Int){
ptr = ptr.advanced(by: n)
}
}
| 8dde89da156ebd8a6aefc120b90b4df1 | 27.64507 | 114 | 0.533681 | false | false | false | false |
chenchangqing/travelMapMvvm | refs/heads/master | travelMapMvvm/travelMapMvvm/Views/Controllers/POIMapViewController/POIMapViewController.swift | apache-2.0 | 1 | //
// POIMapViewController.swift
// travelMapMvvm
//
// Created by green on 15/9/11.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import UIKit
import ReactiveCocoa
class POIMapViewController: UIViewController, THSegmentedPageViewControllerDelegate {
// MARK: - UI
@IBOutlet weak var locationBtn : UIButton! // 定位按钮
@IBOutlet weak var scrollView : GScrollView! // POI水平显示控件
@IBOutlet weak var mapView : MKMapView! // 地图
// MARK: - View Model
var poiMapViewModel: POIMapViewModel!
// MARK: - reuseIdentifier
let kBasicMapAnnotationView = "BasicMapAnnotationView"
let kDistanceAnnotationView = "DistanceAnnotationView"
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
self.poiMapViewModel.active = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// 停止定位
if self.poiMapViewModel.locationManager.isRunning {
self.showHUDMessage(kMsgStopLocation)
self.poiMapViewModel.locationManager.stopUpdatingLocation()
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == kSegueFromPOIMapViewControllerToPOIDetailViewController {
let poiDetailViewModel = POIDetailViewModel(poiModel: sender as! POIModel)
let poiDetailViewController = segue.destinationViewController as! POIDetailViewController
poiDetailViewController.poiDetailViewModel = poiDetailViewModel
}
}
// MARK: - setup
private func setup() {
setUpCommand()
bindViewModel()
setupMap()
setupEvents()
setupMessage()
}
/**
* 命令设置
*/
private func setUpCommand() {
poiMapViewModel.refreshCommand.executionSignals.subscribeNextAs { (signal:RACSignal) -> () in
signal.dematerialize().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNext({ (any:AnyObject!) -> Void in
// 处理POI列表
self.poiMapViewModel.poiList = any as! [POIModel]
}, error: { (error:NSError!) -> Void in
self.poiMapViewModel.failureMsg = error.localizedDescription
}, completed: { () -> Void in
// println("completed")
})
}
poiMapViewModel.updatingLocationPlacemarkCommand.executionSignals.subscribeNextAs { (signal:RACSignal) -> () in
signal.dematerialize().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNext({ (any:AnyObject!) -> Void in
// 处理定位地址
self.poiMapViewModel.lastUserAnnotation = MKPlacemark(placemark: any as! CLPlacemark)
}, error: { (error:NSError!) -> Void in
self.poiMapViewModel.failureMsg = error.localizedDescription
}, completed: { () -> Void in
})
}
}
/**
* 绑定view model
*/
private func bindViewModel() {
RACObserve(self, "poiMapViewModel.poiList").subscribeNextAs { (poiList:[POIModel]!) -> () in
// 更新POI水平显示控件
self.scrollView.dataSource = poiList
// 更新地图
// 删除标注
self.mapView.removeAnnotations(self.poiMapViewModel.basicMapAnnotationDic.keys)
self.mapView.removeAnnotations(self.poiMapViewModel.distanceAnnotationDic.keys)
// 组织标注dic
for poiTuple in enumerate(poiList) {
let annotationTuple = self.poiMapViewModel.getAnnotationTuple(poiTuple.element, i: poiTuple.index)
if let basicMapAnnotation=annotationTuple.basicMapAnnotation {
self.poiMapViewModel.basicMapAnnotationDic[basicMapAnnotation] = self.getBasicAnnotationView(basicMapAnnotation)
// callout
basicMapAnnotation.title = poiTuple.element.poiName
basicMapAnnotation.subtitle = poiTuple.element.address
}
if let distanceAnnotation=annotationTuple.distanceAnnotation {
self.poiMapViewModel.distanceAnnotationDic[distanceAnnotation] = self.getDistanceAnnotationView(distanceAnnotation)
}
}
// 增加标注
self.mapView.addAnnotations(self.poiMapViewModel.basicMapAnnotationDic.keys)
self.mapView.addAnnotations(self.poiMapViewModel.distanceAnnotationDic.keys)
}
RACObserve(self, "poiMapViewModel.lastCoordinate").subscribeNext { (lastCoordinate:AnyObject?) -> () in
if let lastCoordinate=lastCoordinate as? CLLocationCoordinate2DModel {
// 查询位置信息
self.poiMapViewModel.updatingLocationPlacemarkCommand.execute(lastCoordinate)
// 显示距离
self.showDistances(lastCoordinate.latitude, longitude: lastCoordinate.longitude)
}
}
RACObserve(self, "poiMapViewModel.lastUserAnnotation").subscribeNext { (currentUserAnnotation:AnyObject?) -> () in
// 更新标注
self.updateLastUserAnnotation(currentUserAnnotation as? MKPlacemark)
}
}
/**
* 事件设置
*/
private func setupEvents() {
// POI水平显示控件
self.scrollView.selectFunc = { index in
if index < self.poiMapViewModel.basicMapAnnotationDic.count {
self.mapView.selectAnnotation(self.poiMapViewModel.basicMapAnnotationDic.keys[index], animated: true)
}
}
self.scrollView.unselectFunc = { index in
if index < self.poiMapViewModel.basicMapAnnotationDic.count {
self.mapView.deselectAnnotation(self.poiMapViewModel.basicMapAnnotationDic.keys[index], animated: true)
}
}
// 点击定位按钮
locationBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNextAs { (btn:UIButton!) -> () in
if btn.selected {
self.showHUDMessage(kMsgStopLocation)
self.poiMapViewModel.locationManager.stopUpdatingLocation()
self.resetUserPositionInfo() // 重置坐标及标注
self.hideDistances() // 隐藏距离
} else {
self.showHUDMessage(kMsgStartLocation)
// 开始定位
self.startUpdatingLocation()
}
btn.selected = !btn.selected
}
}
/**
* 地图设置
*/
private func setupMap() {
self.mapView.delegate = self
}
/**
* 成功失败提示
*/
private func setupMessage() {
RACSignal.combineLatest([
RACObserve(poiMapViewModel, "failureMsg"),
RACObserve(poiMapViewModel, "successMsg"),
self.poiMapViewModel.refreshCommand.executing
]).subscribeNextAs { (tuple: RACTuple) -> () in
let failureMsg = tuple.first as! String
let successMsg = tuple.second as! String
let isLoading = tuple.third as! Bool
if isLoading {
self.showHUDIndicator()
} else {
if failureMsg.isEmpty && successMsg.isEmpty {
self.hideHUD()
}
}
if !failureMsg.isEmpty {
self.showHUDErrorMessage(failureMsg)
}
if !successMsg.isEmpty {
self.showHUDMessage(successMsg)
}
}
}
// MARK: - THSegmentedPageViewControllerDelegate
func viewControllerTitle() -> String! {
return self.title
}
}
| b9343c2d15f8d5a34278f16c29bacd7c | 31.081784 | 135 | 0.542063 | false | false | false | false |
andykkt/BFWControls | refs/heads/develop | BFWControls/Modules/NibView/View/NibContainerSegmentedControl.swift | mit | 1 | //
// NibContainerSegmentedControl.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 17/7/18.
// Copyright © 2018 BareFeetWare. All rights reserved.
// Free to use and modify, without warranty.
//
import UIKit
open class NibContainerSegmentedControl: UISegmentedControl {
// MARK: - NibView container
open var nibView: NibView {
fatalError("Concrete subclass must provide nibView.")
}
// MARK: - UpdateView
var needsUpdateView = true
func setNeedsUpdateView() {
needsUpdateView = true
}
func updateViewIfNeeded() {
if needsUpdateView {
needsUpdateView = false
updateView()
}
}
func updateView() {
setDividerImage(UIImage(),
forLeftSegmentState: .normal,
rightSegmentState: .normal,
barMetrics: .default)
let cellView = nibView as! NibCellView
setTitleTextAttributes(cellView.textLabel?.attributedText?.attributes(at: 0, effectiveRange: nil), for: .normal)
cellView.textLabel?.text = nil
for state: UIControlState in [.normal, .selected] {
cellView.accessoryView?.isHidden = state == .normal
let segmentWidth: CGFloat = 10.0 // arbitrary since stretched
cellView.frame.size.width = segmentWidth
let image = cellView.image(
size: CGSize(width: segmentWidth,
height: bounds.height)
)
setBackgroundImage(image, for: state, barMetrics: .default)
}
}
// MARK: - UIView
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.height = 44.0
return size
}
open override func layoutSubviews() {
updateViewIfNeeded()
super.layoutSubviews()
}
}
| 714aab75413d065e23dacf48c997a000 | 27.850746 | 120 | 0.591309 | false | false | false | false |
box/box-ios-sdk | refs/heads/main | Sources/Modules/CollaborationsModule.swift | apache-2.0 | 1 | //
// CollaborationsModule.swift
// BoxSDK
//
// Created by Abel Osorio on 5/29/19.
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
/// Specifies type of value that has granted access to an object.
public enum AccessibleBy: BoxEnum {
/// The user that is granted access
case user
/// The group that is granted access
case group
/// A custom object type for defining access that is not yet implemented
case customValue(String)
/// Creates a new value
///
/// - Parameter value: String representation of an AccessibleBy rawValue
public init(_ value: String) {
switch value {
case "user":
self = .user
case "group":
self = .group
default:
self = .customValue(value)
}
}
/// Returns string representation of type that can be used in a request.
public var description: String {
switch self {
case .user:
return "user"
case .group:
return "group"
case let .customValue(userValue):
return userValue
}
}
}
/// Provides [Collaborations](../Structs/Collaborations.html) management.
public class CollaborationsModule {
/// Required for communicating with Box APIs.
weak var boxClient: BoxClient!
// swiftlint:disable:previous implicitly_unwrapped_optional
/// Initializer
///
/// - Parameter boxClient: Required for communicating with Box APIs.
init(boxClient: BoxClient) {
self.boxClient = boxClient
}
/// Get information about a collaboration.
///
/// - Parameters:
/// - collaborationId: The ID of the collaboration to get details
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: The collaboration object is returned or an error
public func get(
collaborationId: String,
fields: [String]? = nil,
completion: @escaping Callback<Collaboration>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/collaborations/\(collaborationId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Create a new collaboration that grants a group access to a file or folder in a specific role.
///
/// - Parameters:
/// - itemType: The object type. Can be file or folder
/// - itemId: The id of the file or the folder
/// - role: The level of access granted. Can be editor, viewer, previewer, uploader, previewer uploader, viewer uploader, or co-owner.
/// - accessibleBy: The ID of the group that is granted access
/// - accessibleByType: Can be user or group
/// - canViewPath: Whether view path collaboration feature is enabled or not. View path collaborations allow the invitee to see the entire ancestral path to the associated folder.
/// this parameter is only available for folder collaborations
/// The user will not gain privileges in any ancestral folder (e.g. see content the user is not collaborated on).
/// - fields: Attribute(s) to include in the response
/// - notify: Determines if the user, (or all the users in the group) should receive email notification of the collaboration.
/// - completion: The collaboration object is returned or an error
public func create(
itemType: String,
itemId: String,
role: CollaborationRole,
accessibleBy: String,
accessibleByType: AccessibleBy,
canViewPath: Bool? = nil,
fields: [String]? = nil,
notify: Bool? = nil,
completion: @escaping Callback<Collaboration>
) {
var json: [String: Any] = [
"item": [
"id": itemId,
"type": itemType
],
"accessible_by": [
"id": accessibleBy,
"type": accessibleByType.description
],
"role": role.description
]
if let canViewPath = canViewPath {
json["can_view_path"] = canViewPath
}
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/collaborations", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields), "notify": notify],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Create a new collaboration that grants a user to a file or folder in a specific role.
///
/// - Parameters:
/// - itemType: The object type. Can be file or folder
/// - itemId: The id of the file or the folder
/// - role: The level of access granted. Can be editor, viewer, previewer, uploader, previewer uploader, viewer uploader, or co-owner.
/// - login: The ID of the user or group that is granted access
/// - canViewPath: Whether view path collaboration feature is enabled or not. View path collaborations allow the invitee to see the entire ancestral path to the associated folder.
/// this parameter is only available for folder collaborations
/// The user will not gain privileges in any ancestral folder (e.g. see content the user is not collaborated on).
/// - fields: Attribute(s) to include in the response
/// - notify: Determines if the user, (or all the users in the group) should receive email notification of the collaboration.
/// - completion: The collaboration object is returned or an error
public func createByUserEmail(
itemType: String,
itemId: String,
role: CollaborationRole,
login: String,
canViewPath: Bool? = nil,
fields: [String]? = nil,
notify: Bool? = nil,
completion: @escaping Callback<Collaboration>
) {
var json: [String: Any] = [
"item": [
"id": itemId,
"type": itemType
],
"accessible_by": [
"login": login,
"type": "user"
],
"role": role.description
]
if let canViewPath = canViewPath {
json["can_view_path"] = canViewPath
}
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/collaborations", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields), "notify": notify],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Update a collaboration.
///
/// - Parameters:
/// - collaborationId: The ID of the collaboration to get details
/// - role: The level of access granted. Can be editor, viewer, previewer, uploader, previewer uploader, viewer uploader, co-owner, or owner.
/// - status: The status of the collaboration invitation. Can be accepted or rejected.
/// - canViewPath: Whether view path collaboration feature is enabled or not. View path collaborations allow the invitee to see the entire ancestral path to the associated folder.
/// The user will not gain privileges in any ancestral folder (e.g. see content the user is not collaborated on).
/// This parameter is only available for folder collaborations
/// - fields: Attribute(s) to include in the response
/// - completion: The collaboration object is returned or an error
public func update(
collaborationId: String,
role: CollaborationRole,
status: CollaborationStatus? = nil,
canViewPath: Bool? = nil,
fields: [String]? = nil,
completion: @escaping Callback<Collaboration>
) {
var json: [String: Any] = ["role": role.description]
if let canViewPath = canViewPath {
json["can_view_path"] = canViewPath
}
if let status = status {
json["status"] = status.description
}
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/collaborations/\(collaborationId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Delete a collaboration.
///
/// - Parameters:
/// - collaborationId: The ID of the collaboration to delete
/// - completion: An empty response will be returned upon successful deletion or an error
public func delete(
collaborationId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/collaborations/\(collaborationId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Get information about a collaboration.
///
/// - Parameters:
/// - collaborationId: The ID of the collaboration to get details
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: The collaboration object is returned or an error
public func listPendingForEnterprise(
offset: Int? = nil,
limit: Int? = nil,
fields: [String]? = nil
) -> PagingIterator<Collaboration> {
.init(
client: boxClient,
url: URL.boxAPIEndpoint("/2.0/collaborations", configuration: boxClient.configuration),
queryParameters: [
"offset": offset,
"limit": limit,
"status": "pending",
"fields": FieldsQueryParam(fields)
]
)
}
/// Retrieves the acceptance requirements status for a specified collaboration
///
/// - Parameters:
/// - collaborationId: The ID of the collaboration to get details
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: The collaboration object is returned or an error
public func getAcceptanceRequirementsStatus(
collaborationId: String,
completion: @escaping Callback<Collaboration.AcceptanceRequirementsStatus>
) {
boxClient.collaborations.get(
collaborationId: collaborationId,
fields: ["acceptance_requirements_status"],
completion: { result in
switch result {
case let .success(collaboration):
guard let acceptanceRequirement = collaboration.acceptanceRequirementsStatus else {
completion(.failure(BoxAPIError(message: .notFound("Collaboration does not have acceptance requirement status"))))
return
}
completion(.success(acceptanceRequirement))
case let .failure(error):
completion(.failure(error))
}
}
)
}
}
| ad701e6e0bd45651f1b3ff8bc4fbe353 | 38.918149 | 185 | 0.614335 | false | false | false | false |
mr-v/AssertThrows | refs/heads/master | AssertThrowsTests/AssertThrowsFailingTestCase.swift | mit | 1 | //
// AssertThrowsFailingTestCase.swift
// AssertThrows
//
// Copyright (c) 2016 Witold Skibniewski (http://mr-v.github.io/)
//
// 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 XCTest
import AssertThrows
/// Tests failing on purpose didn't figure out how to catch their failures.
//class AssertThrowsFailingTestCase: XCTestCase {
// func test_NonDerivedTypeAssertionFails() {
// let movie = Movie()
// AssertThrows(WSDerivedError.self, try movie.throwsBaseError())
// }
//
// func test_NotMatchingCaseFails() {
// let movie = Movie()
// AssertThrows(TestError.noLuck, try movie.throwOnUnkown(.unkown))
// }
//
// func test_NotMatchingTypeFails() {
// let movie = Movie()
// AssertThrows(AnotherTestError.self, try movie.throwOnUnkown(.unkown))
// }
//
// func test_NotMatchingTypeAndCaseFails() {
// let movie = Movie()
// AssertThrows(AnotherTestError.whatsUp, try movie.throwOnUnkown(.unkown))
// }
//
// func test_AssertThrows_CantAssertNonThrowingFunction() {
// let movie = Movie()
// AssertThrows(AnotherTestError.self, movie.dontThrow())
// }
//}
| 8b7c8b345cb5efafe83b7364fbcf76c6 | 39.518519 | 82 | 0.713437 | false | true | false | false |
Cleverlance/Pyramid | refs/heads/master | Sources/Common/Core/Infrastructure/Interval.swift | mit | 1 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
public struct Interval<T> {
public let min: T?
public let max: T?
public init(min: T?, max: T?) {
self.min = min
self.max = max
}
}
public func == <T: Equatable>(lhs: Interval<T>, rhs: Interval<T>) -> Bool {
return lhs.min == rhs.min && lhs.max == rhs.max
}
public func == <T: Equatable>(lhs: Interval<T>?, rhs: Interval<T>?) -> Bool {
return lhs?.min == rhs?.min && lhs?.max == rhs?.max
}
| c461a897deb2568a2a3861bfcfec4c46 | 22.571429 | 77 | 0.569697 | false | false | false | false |
kkireto/CacheDataManagerSwift | refs/heads/master | CacheDataManager.swift | mit | 1 | //The MIT License (MIT)
//
//Copyright (c) 2014 Kireto
//
//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
class CacheDataManager: NSObject {
class var sharedInstance : CacheDataManager {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : CacheDataManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = CacheDataManager()
}
return Static.instance!
}
override init () {
super.init()
self.createCacheDirectoryPath()
}
// MARK: - image createCacheDirectoryPaths
private func createCacheDirectoryPath() {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
let cachePath = paths.first as String
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(cachePath, isDirectory:&isDir) {
if !isDir {
NSFileManager.defaultManager().removeItemAtPath(cachePath, error: nil)
NSFileManager.defaultManager().createDirectoryAtPath(cachePath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
}
else {
NSFileManager.defaultManager().createDirectoryAtPath(cachePath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
}
// MARK: - image cacheDirectoryPath
func cacheDirectoryPath() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
let cachePath = paths.first as NSString
return cachePath
}
func cacheDirectoryPath(assetId: Int) -> NSString {
var retPath = self.cacheDirectoryPath()
retPath = retPath.stringByAppendingString("\(assetId)")
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(retPath, isDirectory:&isDir) {
if !isDir {
NSFileManager.defaultManager().removeItemAtPath(retPath, error: nil)
NSFileManager.defaultManager().createDirectoryAtPath(retPath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
}
else {
NSFileManager.defaultManager().createDirectoryAtPath(retPath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
return retPath
}
func imageCachePath(imageURL: NSString, assetId: Int) -> NSString {
var retPath = self.cacheDirectoryPath(assetId)
let imageName = imageURL.lastPathComponent
retPath = retPath.stringByAppendingString(imageName)
return retPath
}
// MARK: - set image
func setImage(imageView: UIImageView, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
imageView.image = UIImage(contentsOfFile: imageCachePath)
}
else {
if placeholderImage.length > 0 {
imageView.image = UIImage(named: placeholderImage)
}
imageView.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
UIImagePNGRepresentation(image).writeToFile(imageCachePath, atomically: true)
if let imgView = imageView as UIImageView? {
if imageView.tag == assetId {
imageView.image = image
}
}
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setImage(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
UIImagePNGRepresentation(image).writeToFile(imageCachePath, atomically: true)
if let btn = button as UIButton? {
if button.tag == assetId {
button.setImage(image, forState: UIControlState.Normal)
}
}
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setBackgroundImage(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setBackgroundImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setBackgroundImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
UIImagePNGRepresentation(image).writeToFile(imageCachePath, atomically: true)
if let btn = button as UIButton? {
if button.tag == assetId {
button.setBackgroundImage(image, forState: UIControlState.Normal)
}
}
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
// MARK: - set image in background
func setImageInBackground(imageView: UIImageView, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
imageView.image = UIImage(contentsOfFile: imageCachePath)
}
else {
if placeholderImage.length > 0 {
imageView.image = UIImage(named: placeholderImage)
}
imageView.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
var args = ["image_view":imageView,
"image_path":imageCachePath,
"image":image,
"asset_id": assetId] as NSDictionary
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.setImageViewImage(args)
})
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setImageInBackground(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
var args = ["button":button,
"image_path":imageCachePath,
"image":image,
"asset_id": assetId] as NSDictionary
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.setButtonImage(args)
})
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setBackgroundImageInBackground(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setBackgroundImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setBackgroundImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
var args = ["button":button,
"image_path":imageCachePath,
"image":image,
"asset_id": assetId] as NSDictionary
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.setButtonBackgroundImage(args)
})
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
// MARK: - background methods
private func setImageViewImage(args:NSDictionary) {
var imageView = args.valueForKey("image_view") as? UIImageView
var imageCachePath = args.valueForKey("image_path") as? NSString
var image = args.valueForKey("image_view") as? UIImage
var assetId = args.valueForKey("asset_id") as? Int
if imageView != nil && imageCachePath != nil && image != nil && assetId != nil {
if imageView!.tag == assetId! {
UIImagePNGRepresentation(image!).writeToFile(imageCachePath!, atomically: true)
if imageView != nil {
if imageView!.tag == assetId! {
//update GUI on main thread
dispatch_async(dispatch_get_main_queue(), {
imageView!.image = image!
})
}
}
}
}
}
private func setButtonImage(args:NSDictionary) {
var button = args.valueForKey("button") as? UIButton
var imageCachePath = args.valueForKey("image_path") as? NSString
var image = args.valueForKey("image_view") as? UIImage
var assetId = args.valueForKey("asset_id") as? Int
if button != nil && imageCachePath != nil && image != nil && assetId != nil {
if button!.tag == assetId! {
UIImagePNGRepresentation(image!).writeToFile(imageCachePath!, atomically: true)
if button != nil {
if button!.tag == assetId! {
//update GUI on main thread
dispatch_async(dispatch_get_main_queue(), {
button!.setImage(image!, forState: UIControlState.Normal)
})
}
}
}
}
}
private func setButtonBackgroundImage(args:NSDictionary) {
var button = args.valueForKey("button") as? UIButton
var imageCachePath = args.valueForKey("image_path") as? NSString
var image = args.valueForKey("image_view") as? UIImage
var assetId = args.valueForKey("asset_id") as? Int
if button != nil && imageCachePath != nil && image != nil && assetId != nil {
if button!.tag == assetId! {
UIImagePNGRepresentation(image!).writeToFile(imageCachePath!, atomically: true)
if button != nil {
if button!.tag == assetId! {
//update GUI on main thread
dispatch_async(dispatch_get_main_queue(), {
button!.setBackgroundImage(image!, forState: UIControlState.Normal)
})
}
}
}
}
}
// MARK: - remove cache data
func removeCachedData(imageURL: NSString, assetId: Int) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let path = self.imageCachePath(imageURL, assetId: assetId)
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory:&isDir) {
if !isDir {
NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
}
}
}
func removeCachedData(assetId: Int) {
let imagesDir = self.cacheDirectoryPath(assetId)
self.emptyDirectory(imagesDir)
}
func removeAllCachedData() {
let dirToEmpty = self.cacheDirectoryPath()
self.emptyDirectory(dirToEmpty)
}
private func emptyDirectory(path: NSString) {
if let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path, error: nil) as NSArray? {
for file in files {
let fileName = file as String
let filePath = path.stringByAppendingPathComponent(fileName)
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(filePath, isDirectory:&isDir) {
if isDir {
self.emptyDirectory(filePath)
}
else {
NSFileManager.defaultManager().removeItemAtPath(filePath, error: nil)
}
}
}
}
}
}
| 7a83507917e34ca1e7b33a16c29956b2 | 48.122715 | 144 | 0.602477 | false | false | false | false |
BlueCocoa/Maria | refs/heads/master | Pods/SwiftyJSON/Source/SwiftyJSON.swift | gpl-3.0 | 1 | // SwiftyJSON.swift
//
// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
///Error domain
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int = 999
public let ErrorIndexOutOfBounds: Int = 900
public let ErrorWrongType: Int = 901
public let ErrorNotExist: Int = 500
public let ErrorInvalidJSON: Int = 490
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type :Int{
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) {
do {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error?.pointee = aError
}
self.init(NSNull())
}
}
/**
Creates a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
public static func parse(_ string:String) -> JSON {
return string.data(using: String.Encoding.utf8)
.flatMap{ JSON(data: $0) } ?? JSON(NSNull())
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: Any) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
- parameter jsonDictionary: A Swift dictionary of JSON objects
- returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: Any](minimumCapacity: jsonDictionary.count)
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// Private object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String : Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false
/// Private type
fileprivate var _type: Type = .null
/// prviate error
fileprivate var _error: NSError? = nil
/// Object in JSON
public var object: Any {
get {
switch self.type {
case .array:
return self.rawArray
case .dictionary:
return self.rawDictionary
case .string:
return self.rawString
case .number:
return self.rawNumber
case .bool:
return self.rawBool
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .bool
self.rawBool = number.boolValue
} else {
_type = .number
self.rawNumber = number
}
case let string as String:
_type = .string
self.rawString = string
case _ as NSNull:
_type = .null
case let array as [JSON]:
_type = .array
self.rawArray = array.map { $0.object }
case let array as [Any]:
_type = .array
self.rawArray = array
case let dictionary as [String : Any]:
_type = .dictionary
self.rawDictionary = dictionary
default:
_type = .unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// JSON type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null JSON
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
public enum JSONIndex:Comparable
{
case array(Int)
case dictionary(DictionaryIndex<String, JSON>)
case null
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool
{
switch (lhs, rhs)
{
case (.array(let left), .array(let right)):
return left == right
case (.dictionary(let left), .dictionary(let right)):
return left == right
case (.null, .null): return true
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool
{
switch (lhs, rhs)
{
case (.array(let left), .array(let right)):
return left < right
case (.dictionary(let left), .dictionary(let right)):
return left < right
default:
return false
}
}
extension JSON: Collection
{
public typealias Index = JSONIndex
public var startIndex: Index
{
switch type
{
case .array:
return .array(rawArray.startIndex)
case .dictionary:
return .dictionary(dictionaryValue.startIndex)
default:
return .null
}
}
public var endIndex: Index
{
switch type
{
case .array:
return .array(rawArray.endIndex)
case .dictionary:
return .dictionary(dictionaryValue.endIndex)
default:
return .null
}
}
public func index(after i: Index) -> Index
{
switch i
{
case .array(let idx):
return .array(rawArray.index(after: idx))
case .dictionary(let idx):
return .dictionary(dictionaryValue.index(after: idx))
default:
return .null
}
}
public subscript (position: Index) -> (String, JSON)
{
switch position
{
case .array(let idx):
return (String(idx), JSON(self.rawArray[idx]))
case .dictionary(let idx):
return dictionaryValue[idx]
default:
return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey
{
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey:JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if self.type != .array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
let array = elements
self.init(dictionaryLiteral: array)
}
public init(dictionaryLiteral elements: [(String, Any)]) {
let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in
let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in
if let value = dictionary[key] {
return (key, value)
}
return nil
}
return JSON(dictionaryLiteral: initializeElement)
}
var dict = [String : Any](minimumCapacity: elements.count)
for element in elements {
let elementToSet: Any
if let json = element.1 as? JSON {
elementToSet = json.object
} else if let jsonArray = element.1 as? [JSON] {
elementToSet = JSON(jsonArray).object
} else if let dictionary = element.1 as? [String : Any] {
elementToSet = jsonFromDictionaryLiteral(dictionary).object
} else if let dictArray = element.1 as? [[String : Any]] {
let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) }
elementToSet = JSON(jsonArray).object
} else {
elementToSet = element.1
}
dict[element.0] = elementToSet
}
self.init(dict)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements as Any)
}
}
extension JSON: Swift.ExpressibleByNilLiteral {
@available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions")
public init(nilLiteral: ()) {
self.init(NSNull() as Any)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return self.object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(self.object) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
}
return try JSONSerialization.data(withJSONObject: self.object, options: opt)
}
public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
switch self.type {
case .array, .dictionary:
do {
let data = try self.rawData(options: opt)
return String(data: data, encoding: encoding)
} catch _ {
return nil
}
case .string:
return self.rawString
case .number:
return self.rawNumber.stringValue
case .bool:
return self.rawBool.description
case .null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.prettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [Any]? {
get {
switch self.type {
case .array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .dictionary {
var d = [String : JSON](minimumCapacity: rawDictionary.count)
for (key, value) in rawDictionary {
d[key] = JSON(value)
}
return d
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : Any]? {
get {
switch self.type {
case .dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .bool:
return self.rawBool
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = newValue as Bool
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .bool:
return self.rawBool
case .number:
return self.rawNumber.boolValue
case .string:
return self.rawString.caseInsensitiveCompare("true") == .orderedSame
default:
return false
}
}
set {
self.object = newValue
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .string:
return self.object as? String
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSString(string:newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .string:
return self.object as? String ?? ""
case .number:
return self.rawNumber.stringValue
case .bool:
return (self.object as? Bool).map { String($0) } ?? ""
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .number:
return self.rawNumber
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .string:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber { // indicates parse error
return NSDecimalNumber.zero
}
return decimal
case .number:
return self.object as? NSNumber ?? NSNumber(value: 0)
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return NSNumber(value: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func exists() -> Bool{
if let errorValue = error, errorValue.code == ErrorNotExist ||
errorValue.code == ErrorIndexOutOfBounds ||
errorValue.code == ErrorWrongType {
return false
}
return true
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: URL? {
get {
switch self.type {
case .string:
if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int: Int?
{
get
{
return self.number?.intValue
}
set
{
if let newValue = newValue
{
self.object = NSNumber(value: newValue)
} else
{
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.uintValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.uintValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.int8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.int8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.uint8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.uint8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.int16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.int16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.uint16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.uint16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.int32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.int32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.uint32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.uint32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.int64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.int64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.uint64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.uint64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber == rhs.rawNumber
case (.string, .string):
return lhs.rawString == rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber <= rhs.rawNumber
case (.string, .string):
return lhs.rawString <= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber >= rhs.rawNumber
case (.string, .string):
return lhs.rawString >= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber > rhs.rawNumber
case (.string, .string):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber < rhs.rawNumber
case (.string, .string):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool:Bool {
get {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedSame
}
}
func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedAscending
}
}
func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedDescending
}
}
func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedAscending
}
}
| 4f7cf9a3116e610c99220b4a66b84b42 | 25.550613 | 265 | 0.526457 | false | false | false | false |
kdawgwilk/vapor | refs/heads/master | Sources/Vapor/Content/Content.swift | mit | 1 | @_exported import PathIndexable
public protocol RequestContentSubscript {}
extension String: RequestContentSubscript { }
extension Int: RequestContentSubscript {}
/**
The data received from the request in json body or url query
Can be extended by third party droplets and middleware
*/
public final class Content {
public typealias ContentLoader = ([PathIndex]) -> Polymorphic?
// MARK: Initialization
private var content: [ContentLoader] = []
public init() {}
// Some closure weirdness to allow more complex capturing or lazy loading internally
public func append<E where E: PathIndexable, E: Polymorphic>(_ element: (Void) -> E?) {
let finder: ContentLoader = { indexes in return element()?[indexes] }
content.append(finder)
}
public func append(_ element: ContentLoader) {
content.append(element)
}
public func append<E where E: PathIndexable, E: Polymorphic>(_ element: E?) {
guard let element = element else { return }
let finder: ContentLoader = { indexes in return element[indexes] }
content.append(finder)
}
// MARK: Subscripting
public subscript(index: Int) -> Polymorphic? {
return self[[index]] ?? self [["\(index)"]]
}
public subscript(key: String) -> Polymorphic? {
return self[[key]]
}
public subscript(indexes: PathIndex...) -> Polymorphic? {
return self[indexes]
}
public subscript(indexes: [PathIndex]) -> Polymorphic? {
return content.lazy.flatMap { finder in finder(indexes) } .first
}
}
| f7cb306919c45fcda1729f2a876908af | 26.947368 | 91 | 0.657878 | false | false | false | false |
ReSwift/ReSwift-Recorder | refs/heads/master | ReSwiftRecorder/StandardAction.swift | mit | 2 | //
// StandardAction.swift
// ReSwiftRecorder
//
// Created by Malcolm Jarvis on 2017-06-28.
// Copyright © 2017 Benjamin Encz. All rights reserved.
//
import Foundation
import ReSwift
/**
It is recommended that you define your own types that conform to `Action` - if you want to be able
to serialize your custom action types, you can implement `StandardActionConvertible` which will
make it possible to generate a `StandardAction` from your typed action - the best of both worlds!
*/
public struct StandardAction: Action {
/// A String that identifies the type of this `StandardAction`
public let type: String
/// An untyped, JSON-compatible payload
public let payload: [String: AnyObject]?
/// Indicates whether this action will be deserialized as a typed action or as a standard action
public let isTypedAction: Bool
/**
Initializes this `StandardAction` with a type, a payload and information about whether this is
a typed action or not.
- parameter type: String representation of the Action type
- parameter payload: Payload convertable to JSON
- parameter isTypedAction: Is Action a subclassed type
*/
public init(type: String, payload: [String: AnyObject]? = nil, isTypedAction: Bool = false) {
self.type = type
self.payload = payload
self.isTypedAction = isTypedAction
}
}
// MARK: Coding Extension
private let typeKey = "type"
private let payloadKey = "payload"
private let isTypedActionKey = "isTypedAction"
let reSwiftNull = "ReSwift_Null"
extension StandardAction: Coding {
public init?(dictionary: [String: AnyObject]) {
guard let type = dictionary[typeKey] as? String,
let isTypedAction = dictionary[isTypedActionKey] as? Bool else { return nil }
self.type = type
self.payload = dictionary[payloadKey] as? [String: AnyObject]
self.isTypedAction = isTypedAction
}
public var dictionaryRepresentation: [String: AnyObject] {
let payload: AnyObject = self.payload as AnyObject? ?? reSwiftNull as AnyObject
return [typeKey: type as NSString,
payloadKey: payload,
isTypedActionKey: isTypedAction as NSNumber]
}
}
/// Implement this protocol on your custom `Action` type if you want to make the action
/// serializable.
/// - Note: We are working on a tool to automatically generate the implementation of this protocol
/// for your custom action types.
public protocol StandardActionConvertible: Action {
/**
Within this initializer you need to use the payload from the `StandardAction` to configure the
state of your custom action type.
Example:
```
init(_ standardAction: StandardAction) {
self.twitterUser = decode(standardAction.payload!["twitterUser"]!)
}
```
- Note: If you, as most developers, only use action serialization/deserialization during
development, you can feel free to use the unsafe `!` operator.
*/
init (_ standardAction: StandardAction)
/**
Use the information from your custom action to generate a `StandardAction`. The `type` of the
StandardAction should typically match the type name of your custom action type. You also need
to set `isTypedAction` to `true`. Use the information from your action's properties to
configure the payload of the `StandardAction`.
Example:
```
func toStandardAction() -> StandardAction {
let payload = ["twitterUser": encode(self.twitterUser)]
return StandardAction(type: SearchTwitterScene.SetSelectedTwitterUser.type,
payload: payload, isTypedAction: true)
}
```
*/
func toStandardAction() -> StandardAction
}
| 66c80fb3b64b3274ac1eab4c2cffb3c1 | 34.084112 | 100 | 0.696058 | false | false | false | false |
slavasemeniuk/SVLoader | refs/heads/master | SVLoader/Classes/SVLoader.swift | mit | 1 | //
// Loader.swift
// Loader
//
// Created by Slava Semeniuk on 12/12/16.
// Copyright © 2016 Slava Semeniuk. All rights reserved.
//
import UIKit
open class SVLoader: NSObject {
internal static let sharedLoader = SVLoader()
internal var holderView: HolderView!
open static fileprivate(set) var animating = false {
didSet {
sharedLoader.holderView.shouldAnimate = animating
}
}
override init() {
super.init()
holderView = HolderView(frame: UIScreen.main.bounds)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
//MARK: - Window
fileprivate func addHolderView() {
guard let window = frontWindow() else { return }
SVLoader.animating = true
holderView.alpha = 0
window.addSubview(holderView)
UIView.animate(withDuration: 0.4, animations: {
self.holderView!.alpha = 1
})
}
fileprivate func hideHolderView(completion: (()->Void)?) {
UIView.animate(withDuration: 0.4, animations: {
self.holderView?.alpha = 0
}, completion: {
if $0 {
SVLoader.animating = false
SVLoader.sharedLoader.holderView.resetAllLayers()
self.holderView.removeFromSuperview()
completion?()
}
})
}
fileprivate func frontWindow() -> UIWindow? {
for window in UIApplication.shared.windows.reversed() {
let onMainScreen = window.screen == UIScreen.main
let windowLevelSupported = window.windowLevel <= UIWindowLevelNormal
let windowsIsVisible = !window.isHidden && window.alpha > 0
if onMainScreen && windowsIsVisible && windowLevelSupported {
return window
}
}
return nil
}
//MARK: - Appication actions
@objc fileprivate func applicationDidBecomeActive() {
guard SVLoader.animating else { return }
holderView.animateDots()
}
//MARK: - Interface
open class func showLoaderWith(message: String) {
if SVLoader.animating { return }
sharedLoader.addHolderView()
sharedLoader.holderView.showWith(message)
}
open class func show() {
showLoaderWith(message: SVLoaderSettings.defaultLoadingMessage)
}
open class func showLoaderWith(messages: [String], changeInA seconds: TimeInterval) {
if SVLoader.animating { return }
sharedLoader.addHolderView()
sharedLoader.holderView.showWith(messages: messages, timeInterval: seconds)
}
open class func hideWithSuccess(message: String? = nil, completion: (() -> Void)? = nil) {
if !SVLoader.animating {
completion?()
return
}
var successMessage = ""
if let text = message {
successMessage = text
} else {
successMessage = SVLoaderSettings.defaultSuccessMessage
}
sharedLoader.holderView.hideWithSuccess(message: successMessage, completion: {
sharedLoader.hideHolderView(completion: completion)
})
}
open class func hideLoader(_ completion: (() -> Void)? = nil) {
guard SVLoader.animating else {
completion?()
return
}
sharedLoader.hideHolderView(completion: completion)
}
}
| 2893e0808305cc4b20d3b3b822b7dc83 | 30.973214 | 170 | 0.603183 | false | false | false | false |
anhnc55/fantastic-swift-library | refs/heads/master | Example/Pods/Material/Sources/iOS/SearchBarController.swift | mit | 2 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material 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 UIKit
public extension UIViewController {
/**
A convenience property that provides access to the SearchBarController.
This is the recommended method of accessing the SearchBarController
through child UIViewControllers.
*/
public var searchBarController: SearchBarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is SearchBarController {
return viewController as? SearchBarController
}
viewController = viewController?.parentViewController
}
return nil
}
}
public class SearchBarController : BarViewController {
/// Reference to the SearchBar.
public private(set) var searchBar: SearchBar!
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutSubviews()
}
/// Layout subviews.
public func layoutSubviews() {
let w: CGFloat = MaterialDevice.width
let h: CGFloat = MaterialDevice.height
if .iPhone == MaterialDevice.type && MaterialDevice.isLandscape {
searchBar.contentInset.top = 4
} else {
searchBar.contentInset.top = 24
}
searchBar.width = w
let p: CGFloat = searchBar.intrinsicContentSize().height
rootViewController.view.frame.origin.y = p
rootViewController.view.frame.size.height = h - p
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
public override func prepareView() {
super.prepareView()
prepareSearchBar()
}
/// Prepares the SearchBar.
private func prepareSearchBar() {
if nil == searchBar {
searchBar = SearchBar()
searchBar.zPosition = 1000
view.addSubview(searchBar)
}
}
}
| dea1d7cb7975025d251bdebb01bfd295 | 33.632653 | 86 | 0.765468 | false | false | false | false |
NeilNie/Done- | refs/heads/master | Pods/Eureka/Source/Rows/ActionSheetRow.swift | apache-2.0 | 1 | // ActionSheetRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class AlertSelectorCell<T> : Cell<T>, CellType where T: Equatable {
required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
accessoryType = .none
editingAccessoryType = accessoryType
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
open class _ActionSheetRow<Cell: CellType>: AlertOptionsRow<Cell>, PresenterRowType where Cell: BaseCell {
public typealias ProviderType = SelectorAlertController<_ActionSheetRow<Cell>>
public var onPresentCallback: ((FormViewController, ProviderType) -> Void)?
lazy public var presentationMode: PresentationMode<ProviderType>? = {
return .presentModally(controllerProvider: ControllerProvider.callback { [weak self] in
let vc = SelectorAlertController<_ActionSheetRow<Cell>>(title: self?.selectorTitle, message: nil, preferredStyle: .actionSheet)
if let popView = vc.popoverPresentationController {
guard let cell = self?.cell, let tableView = cell.formViewController()?.tableView else { fatalError() }
popView.sourceView = tableView
popView.sourceRect = tableView.convert(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, from: cell)
}
vc.row = self
return vc
},
onDismiss: { [weak self] in
$0.dismiss(animated: true)
self?.cell?.formViewController()?.tableView?.reloadData()
})
}()
public required init(tag: String?) {
super.init(tag: tag)
}
open override func customDidSelect() {
super.customDidSelect()
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.makeController() {
controller.row = self
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: cell.formViewController()!)
} else {
presentationMode.present(nil, row: self, presentingController: cell.formViewController()!)
}
}
}
}
/// An options row where the user can select an option from an ActionSheet
public final class ActionSheetRow<T>: _ActionSheetRow<AlertSelectorCell<T>>, RowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| f664fe2dd462b78e507534e2055f5c9f | 41.084211 | 146 | 0.684592 | false | false | false | false |
ReiVerdugo/uikit-fundamentals | refs/heads/master | step2.1-dice-incomplete/Dice Incomplete/RollViewController.swift | mit | 1 | //
// RollViewController.swift
// Dice
//
// Created by Jason Schatz on 11/6/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - RollViewController: UIViewController
class RollViewController: UIViewController {
// MARK: Generate Dice Value
// randomly generates a Int from 1 to 6
func randomDiceValue() -> Int {
// generate a random Int32 using arc4Random
let randomValue = 1 + arc4random() % 6
// return a more convenient Int, initialized with the random value
return Int(randomValue)
}
// MARK: Actions
@IBAction func rollTheDice() {
// var controller: DiceViewController
//
// controller = self.storyboard?.instantiateViewControllerWithIdentifier("DiceViewController") as! DiceViewController
//
// controller.firstValue = self.randomDiceValue()
// controller.secondValue = self.randomDiceValue()
//
// presentViewController(controller, animated: true, completion: nil)
self.performSegueWithIdentifier("rollDice", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "rollDice" {
let controller = segue.destinationViewController as! DiceViewController
controller.firstValue = self.randomDiceValue()
controller.secondValue = self.randomDiceValue()
}
}
}
| 114358988c543de6d16ad5c99adc3a7a | 30.340426 | 124 | 0.655126 | false | false | false | false |
siemensikkema/Fairness | refs/heads/master | Fairness/TransactionCalculator.swift | mit | 1 | import Foundation
protocol TransactionCalculatorInterface: class {
var amounts: [Double] { get }
var cost: Double { get set }
var hasPayer: Bool { get }
var isValid: Bool { get }
var participantTransactionModels: [ParticipantTransactionModel] { get set }
func togglePayeeAtIndex(index: Int)
func togglePayerAtIndex(index: Int)
}
class TransactionCalculator: TransactionCalculatorInterface {
private let notificationCenter: FairnessNotificationCenter
var amounts: [Double] {
return participantTransactionModels.map { $0.amountOrNil ?? 0 }
}
var cost: Double = 0.0 {
didSet { update() }
}
var hasPayer: Bool {
for participantViewModel in participantTransactionModels {
if participantViewModel.isPayer { return true }
}
return false
}
var isValid: Bool {
return cost > 0 && participantTransactionModels.filter { $0.isPayer || $0.isPayee }.count > 1
}
var participantTransactionModels: [ParticipantTransactionModel] = []
convenience init() {
self.init(notificationCenter: NotificationCenter())
}
init(notificationCenter: FairnessNotificationCenter) {
self.notificationCenter = notificationCenter
notificationCenter.observeTransactionDidEnd {
self.cost = 0.0
self.participantTransactionModels.map { $0.reset() }
}
}
func togglePayeeAtIndex(index: Int) {
participantTransactionModels[index].isPayee = !participantTransactionModels[index].isPayee
update()
}
func togglePayerAtIndex(index: Int) {
participantTransactionModels[index].isPayer = !participantTransactionModels[index].isPayer
update()
}
private func update() {
let numberOfPayees = Double(participantTransactionModels.reduce(0) { $0 + ($1.isPayee ? 1 : 0) })
for index in 0..<participantTransactionModels.count {
var amountOrNil: Double?
if (self.isValid) {
let participantTransactionModel = participantTransactionModels[index]
if participantTransactionModel.isPayee {
amountOrNil = -self.cost/numberOfPayees
}
if participantTransactionModel.isPayer {
amountOrNil = (amountOrNil ?? 0) + self.cost
}
}
participantTransactionModels[index].amountOrNil = amountOrNil
}
}
} | f84e1d3c5d566f69afe0be776c7728b5 | 30.1 | 105 | 0.645356 | false | false | false | false |
BanyaKrylov/Learn-Swift | refs/heads/master | Skill/test/test/ThreeOneViewController.swift | apache-2.0 | 1 | //
// ThreeOneViewController.swift
// test
//
// Created by Ivan Krylov on 04.02.2020.
// Copyright © 2020 Ivan Krylov. All rights reserved.
//
import UIKit
protocol ThreeOneControllerDelegate {
func setBackgroundColor(_ color: UIColor)
}
class ThreeOneViewController: UIViewController {
var colorBackground = UIColor() {
didSet {
baskgroundContainer.backgroundColor = colorBackground
}
}
var delegate: ThreeOneControllerDelegate?
@IBOutlet var baskgroundContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ThreeViewController, segue.identifier == "EditBackgroundThreeOne" {
vc.delegate = self
}
}
@IBAction func greenButtonContainer(_ sender: Any) {
delegate?.setBackgroundColor(UIColor.green)
}
@IBAction func yellowButtonContainer(_ sender: Any) {
delegate?.setBackgroundColor(UIColor.yellow)
}
@IBAction func purpleButtonContainer(_ sender: Any) {
delegate?.setBackgroundColor(UIColor.purple)
}
}
extension ThreeOneViewController: ThreeControllerDelegate {
func setBackgroundColor(_ color: UIColor) {
baskgroundContainer.backgroundColor = color
}
}
| 3c68118e828212092992cc6a2686c07b | 26.76 | 113 | 0.670029 | false | false | false | false |
joelrorseth/AtMe | refs/heads/master | AtMe/Constants.swift | apache-2.0 | 1 | //
// Constants.swift
// AtMe
//
// Created by Joel Rorseth on 2017-02-20.
// Copyright © 2017 Joel Rorseth. All rights reserved.
//
import UIKit
struct Constants {
struct App {
static let oneSignalAppId = "8bf018c1-5a99-4ab8-8652-70a4fc149019"
}
struct Assets {
static let purpleUserImage = "user_purple"
}
struct CellIdentifiers {
static let blockedUserCell = "BlockedUserCell"
}
struct Colors {
static let tableViewBackground = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0)
static let primaryLight = UIColor(red: 180/255, green: 93/255, blue: 231/255, alpha: 1)
static let primaryDark = UIColor(red: 115/255, green: 22/255, blue: 231/255, alpha: 1)
static let primaryAccent = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
static let whiteText = UIColor.white
}
struct Errors {
static let changeEmailError = "A problem occured while changing your email address. Please try again."
static let changePasswordError = "A problem occured while changing your password. Please try again."
static let createConversationError = "There was an error attempting to start the conversation. Please try again or contact support."
static let missingFields = "Please fill in all required information."
static let invalidCharacters = "Your fields must not contain any of the following: . $ # [ ] /"
static let loadProfileError = "An error occured while loading this profile. Please try again once dismissed."
static let passwordLength = "Your password must be 6 or more characters."
static let usernameLength = "Your username must be 4 or more valid characters."
static let usernameTaken = "Your @Me username must be unique, please choose another."
static let signInBadConfig = "Sign In configuration was unsuccessful. Please try again."
static let displayPictureMissing = "An error occured while setting your new picture. Please try again."
static let unestablishedCurrentUser = "An error occured while authorizing. Please try signing in again."
static let conversationAlreadyExists = "You already have an open conversation with this user."
}
struct Fonts {
static let emptyViewMessageFont = UIFont(name: "Avenir Next", size: 18)!
static let lightTitle = UIFont(name: "AvenirNext-Medium", size: 20)!
static let regularText = UIFont(name: "AvenirNext-Regular", size: 14)!
static let boldButtonText = UIFont(name: "AvenirNext-DemiBold", size: 17)!
}
struct Limits {
static let messageCountStandardLimit = 40
static let messageCountIncreaseLimit = 20
static let resultsCount = UInt(16)
}
struct Messages {
static let cacheClearedSuccess = "Image cache was successfully emptied."
static let confirmBlockMessage = "Are you sure you want to block this user? You will be unable to contact each other while blocked."
static let confirmLogout = "Are you sure you want to logout?"
static let didReportUser = "Thank you for your report. We will investigate this issue and take appropriate action within 24 hours."
static let noBlockedUsersMessage = "You have not blocked any users."
}
struct Placeholders {
static let messagePlaceholder = "Enter a message"
static let pictureMessagePlaceholder = "Picture Message"
}
struct Radius {
static let regularRadius = CGFloat(12)
}
struct Segues {
static let createAccountSuccessSegue = "CreateAccountSuccessSegue"
static let loadConvoSegue = "LoadConvoSegue"
static let newConvoSegue = "NewConvoSegue"
static let reportUserSegue = "ReportUserSegue"
static let settingsSegue = "SettingsSegue"
static let showAuxSegue = "ShowAuxSegue"
static let showBlockedUsersSegue = "ShowBlockedUsersSegue"
static let showLegalSegue = "ShowLegalSegue"
static let showPromptSegue = "ShowPrompt"
static let signInSuccessSegue = "SignInSuccessSegue"
static let signUpSuccessSegue = "SignUpSuccessSegue"
static let unwindToChatListSegue = "UnwindToChatListSegue"
static let unwindToSignInSegue = "UnwindToSignIn"
}
struct Sizes {
static let pictureMessageDefaultHeight = 200
static let pictureMessageDefaultWidth = 200
}
struct Storyboard {
static let messageId = "messageId"
}
enum UserAttribute: Int { case none = 0, firstName, lastName, email, password }
struct UserAttributes {
static let UserAttributeNames = ["None", "first name", "last name", "email address", "password"]
}
}
| 307ba4819d67eca3ef5a576a51866978 | 40.851852 | 136 | 0.727434 | false | false | false | false |
younata/RSSClient | refs/heads/master | TethysKitSpecs/Services/ArticleService/ArticleServiceShared.swift | mit | 1 | import Quick
import Nimble
@testable import TethysKit
func articleService_authors_returnsTheAuthors(line: UInt = #line, file: String = #file,
subjectFactory: @escaping () -> ArticleService) {
var subject: ArticleService!
beforeEach {
subject = subjectFactory()
}
context("with one author") {
it("returns the author's name") {
let article = articleFactory(authors: [
Author("An Author")
])
expect(subject.authors(of: article), file: file, line: line).to(equal("An Author"))
}
it("returns the author's name and email, if present") {
let article = articleFactory(authors: [
Author(name: "An Author", email: URL(string: "mailto:[email protected]"))
])
expect(subject.authors(of: article), file: file, line: line).to(equal("An Author <[email protected]>"))
}
}
context("with two authors") {
it("returns both authors names") {
let article = articleFactory(authors: [
Author("An Author"),
Author("Other Author", email: URL(string: "mailto:[email protected]"))
])
expect(subject.authors(of: article), file: file, line: line).to(equal("An Author, Other Author <[email protected]>"))
}
}
context("with more authors") {
it("returns them combined with commas") {
let article = articleFactory(authors: [
Author("An Author"),
Author("Other Author", email: URL(string: "mailto:[email protected]")),
Author("Third Author", email: URL(string: "mailto:[email protected]"))
])
expect(subject.authors(of: article), file: file, line: line).to(equal(
"An Author, Other Author <[email protected]>, Third Author <[email protected]>"
))
}
}
}
| dc1040d0ecbea194aa8dd158773ba7bd | 35.240741 | 128 | 0.551354 | false | false | false | false |
AnthonyMDev/Nimble | refs/heads/TableViewCells | Carthage/Checkouts/Quick/Externals/Nimble/Sources/Nimble/Matchers/PostNotification.swift | apache-2.0 | 13 | import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
private var token: NSObjectProtocol?
required init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
}
func startObserving() {
// swiftlint:disable:next line_length
self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] notification in
// linux-swift gets confused by .append(n)
self?.observedNotifications.append(notification)
}
}
deinit {
if let token = self.token {
self.notificationCenter.removeObserver(token)
}
}
}
private let mainThread = pthread_self()
public func postNotifications(
_ predicate: Predicate<[Notification]>,
fromNotificationCenter center: NotificationCenter = .default
) -> Predicate<Any> {
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(
memoizedExpression: { _ in
return collector.observedNotifications
},
location: actualExpression.location,
withoutCaching: true
)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let actualValue: String
if collector.observedNotifications.isEmpty {
actualValue = "no notifications"
} else {
actualValue = "<\(stringify(collector.observedNotifications))>"
}
var result = try predicate.satisfies(collectorNotificationsExpression)
result.message = result.message.replacedExpectation { message in
return .expectedCustomValueTo(message.expectedMessage, actualValue)
}
return result
}
}
public func postNotifications<T>(
_ notificationsMatcher: T,
fromNotificationCenter center: NotificationCenter = .default)
-> Predicate<Any>
where T: Matcher, T.ValueType == [Notification]
{
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
return collector.observedNotifications
}, location: actualExpression.location, withoutCaching: true)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let failureMessage = FailureMessage()
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
if collector.observedNotifications.isEmpty {
failureMessage.actualValue = "no notifications"
} else {
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
}
return PredicateResult(bool: match, message: failureMessage.toExpectationMessage())
}
}
| 8f4ec68b18724ddb7788a0bbfeb79467 | 35.18 | 125 | 0.670813 | false | false | false | false |
pksprojects/ElasticSwift | refs/heads/master | Sources/ElasticSwift/Responses/Response.swift | mit | 1 | //
// Response.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 5/30/17.
//
//
import ElasticSwiftCodableUtils
import ElasticSwiftCore
import Foundation
// MARK: - Get Response
/// A response for get request
public struct GetResponse<T: Codable>: Codable, Equatable where T: Equatable {
public let index: String
public let type: String?
public let id: String
public let version: Int?
public let found: Bool
public let source: T?
public let seqNumber: Int?
public let primaryTerm: Int?
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case version = "_version"
case source = "_source"
case found
case seqNumber = "_seq_no"
case primaryTerm = "_primary_term"
}
}
// MARK: - Index Response
public struct IndexResponse: Codable, Equatable {
public let shards: Shards
public let index: String
public let type: String
public let id: String
public let version: Int
public let seqNumber: Int
public let primaryTerm: Int
public let result: String
enum CodingKeys: String, CodingKey {
case shards = "_shards"
case index = "_index"
case type = "_type"
case id = "_id"
case version = "_version"
case seqNumber = "_seq_no"
case primaryTerm = "_primary_term"
case result
}
}
// MARK: - Search Response
public struct SearchResponse<T: Codable>: Codable, Equatable where T: Equatable {
public let took: Int
public let timedOut: Bool
public let shards: Shards
public let hits: SearchHits<T>
public let scrollId: String?
public let profile: SearchProfileShardResults?
public let suggest: [String: [SuggestEntry]]?
enum CodingKeys: String, CodingKey {
case took
case timedOut = "timed_out"
case shards = "_shards"
case hits
case scrollId = "_scroll_id"
case profile
case suggest
}
}
public struct SuggestEntry: Codable, Equatable {
public let text: String
public let offset: Int
public let length: Int
public let options: [SuggestEntryOption]
}
public struct SuggestEntryOption: Codable, Equatable {
public let text: String
public let highlighted: String?
public let score: Decimal?
public let collateMatch: Bool?
public let freq: Int?
public let contexts: [String: [String]]?
public let index: String?
public let type: String?
public let id: String?
public let _score: Decimal?
public let source: CodableValue?
enum CodingKeys: String, CodingKey {
case text
case highlighted
case score
case collateMatch = "collate_match"
case freq
case contexts
case index = "_index"
case type = "_type"
case id = "_id"
case _score
case source = "_source"
}
}
public struct Shards: Codable, Equatable {
public let total: Int
public let successful: Int
public let skipped: Int?
public let failed: Int
public let failures: [ShardSearchFailure]?
}
public struct SearchProfileShardResults: Codable, Equatable {
public let shards: [ProfileShardResult]
}
public struct ProfileShardResult: Codable, Equatable {
public let id: String
public let searches: [QueryProfileShardResult]
public let aggregations: [ProfileResult]
}
public struct QueryProfileShardResult {
public let queryProfileResults: [ProfileResult]
public let rewriteTime: Int
public let collector: [CollectorResult]
}
extension QueryProfileShardResult: Codable {
enum CodingKeys: String, CodingKey {
case queryProfileResults = "query"
case rewriteTime = "rewrite_time"
case collector
}
}
extension QueryProfileShardResult: Equatable {}
public struct ProfileResult {
public let type: String
public let description: String
public let nodeTime: Int
public let timings: [String: Int]
public let children: [ProfileResult]?
}
extension ProfileResult: Codable {
enum CodingKeys: String, CodingKey {
case type
case description
case nodeTime = "time_in_nanos"
case timings = "breakdown"
case children
}
}
extension ProfileResult: Equatable {}
public struct CollectorResult {
public let name: String
public let reason: String
public let time: Int
public let children: [CollectorResult]?
}
extension CollectorResult: Codable {
enum CodingKeys: String, CodingKey {
case name
case reason
case time = "time_in_nanos"
case children
}
}
extension CollectorResult: Equatable {}
public struct SearchHits<T: Codable>: Codable, Equatable where T: Equatable {
public let total: Int
public let maxScore: Decimal?
public let hits: [SearchHit<T>]
public init(total: Int, maxScore: Decimal?, hits: [SearchHit<T>] = []) {
self.total = total
self.maxScore = maxScore
self.hits = hits
}
enum CodingKeys: String, CodingKey {
case total
case maxScore = "max_score"
case hits
}
}
public struct SearchHit<T: Codable> where T: Equatable {
public let index: String
public let type: String?
public let id: String?
public let score: Decimal?
public let source: T?
public let sort: [CodableValue]?
public let version: Int?
public let seqNo: Int?
public let primaryTerm: Int?
public let fields: [String: SearchHitField]?
public let explanation: Explanation?
public let matchedQueries: [String]?
public let innerHits: [String: SearchHits<CodableValue>]?
public let node: String?
public let shard: String?
public let highlightFields: [String: HighlightField]?
public let nested: NestedIdentity?
public var searchSearchTarget: SearchSearchTarget? {
if let node = self.node, let shard = self.shard {
return .init(nodeId: node, shardId: shard)
}
return nil
}
}
extension SearchHit: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
index = try container.decodeString(forKey: .index)
type = try container.decodeStringIfPresent(forKey: .type)
id = try container.decodeStringIfPresent(forKey: .id)
score = try container.decodeDecimalIfPresent(forKey: .score)
version = try container.decodeIntIfPresent(forKey: .version)
seqNo = try container.decodeIntIfPresent(forKey: .seqNo)
primaryTerm = try container.decodeIntIfPresent(forKey: .primaryTerm)
node = try container.decodeStringIfPresent(forKey: .node)
shard = try container.decodeStringIfPresent(forKey: .shard)
nested = try container.decodeIfPresent(NestedIdentity.self, forKey: .nested)
matchedQueries = try container.decodeArrayIfPresent(forKey: .matchedQueries)
sort = try container.decodeArrayIfPresent(forKey: .sort)
source = try container.decodeIfPresent(T.self, forKey: .source)
explanation = try container.decodeIfPresent(Explanation.self, forKey: .explanation)
// self.innerHits = try container.decodeDicIfPresent(forKey: .innerHits)
// let fieldsDic = try container.decodeIfPresent([String: [CodableValue]].self, forKey: .fields)
// if let fieldsDic = fieldsDic {
// var dic = [String: SearchHitField]()
// fieldsDic.map { SearchHitField(name: $0.key, values: $0.value) }.forEach { dic[$0.name] = $0 }
// self.fields = dic
// } else {
// self.fields = nil
// }
fields = try SearchHit.decodeDicOf([String: [CodableValue]].self, in: container, forKey: .fields, flattern: { SearchHitField(name: $0.key, values: $0.value) }, reduce: { $1[$0.name] = $0 })
highlightFields = try SearchHit.decodeDicOf([String: [String]].self, in: container, forKey: .highlightFields, flattern: { HighlightField(name: $0.key, fragments: $0.value) }, reduce: { $1[$0.name] = $0 })
innerHits = try SearchHit.decodeDicOf([String: InnerHitWrapper].self, in: container, forKey: .innerHits, flattern: { ($0.key, $0.value.hits) }, reduce: { $1[$0.0] = $0.1 })
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(index, forKey: .index)
try container.encodeIfPresent(type, forKey: .type)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(score, forKey: .score)
try container.encodeIfPresent(source, forKey: .source)
try container.encodeIfPresent(sort, forKey: .sort)
try container.encodeIfPresent(version, forKey: .version)
try container.encodeIfPresent(seqNo, forKey: .seqNo)
try container.encodeIfPresent(primaryTerm, forKey: .primaryTerm)
try container.encodeIfPresent(explanation, forKey: .explanation)
try container.encodeIfPresent(matchedQueries, forKey: .matchedQueries)
try container.encodeIfPresent(innerHits?.mapValues { InnerHitWrapper(hits: $0) }, forKey: .innerHits)
try container.encodeIfPresent(shard, forKey: .shard)
try container.encodeIfPresent(node, forKey: .node)
try container.encodeIfPresent(nested, forKey: .nested)
if let fields = self.fields {
try container.encode(fields.mapValues { $0.values }, forKey: .fields)
}
if let highlight = highlightFields {
try container.encode(highlight.mapValues { $0.fragments }, forKey: .highlightFields)
}
}
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case score = "_score"
case source = "_source"
case sort
case version = "_version"
case seqNo = "_seq_no"
case primaryTerm = "_primary_term"
case fields
case explanation = "_explanation"
case matchedQueries = "matched_queries"
case innerHits = "inner_hits"
case shard = "_shard"
case node = "_node"
case highlightFields = "highlight"
case nested = "_nested"
}
private static func decodeDicOf<K, V, R, X, Y>(_ decodeDic: [K: V].Type, in container: KeyedDecodingContainer<CodingKeys>, forKey key: CodingKeys, flattern mapper: ((key: K, value: V)) throws -> R, reduce reducer: (R, SharedDic<X, Y>) -> Void) throws -> [X: Y]? where K: Codable, V: Codable {
let decodedDic: [K: V]? = try container.decodeDicIfPresent(forKey: key)
if let decodeDic = decodedDic {
let dic = SharedDic<X, Y>()
try decodeDic.map(mapper).forEach { e in reducer(e, dic) }
return dic.dict
}
return nil
}
private struct InnerHitWrapper: Codable, Equatable {
public let hits: SearchHits<CodableValue>
}
}
extension SearchHit: Equatable {}
public struct SearchHitField: Codable, Equatable {
public let name: String
public let values: [CodableValue]
}
public struct Explanation: Codable, Equatable {
public let match: Bool?
public let value: Decimal
public let description: String
public let details: [Explanation]
}
public struct SearchSearchTarget: Codable, Equatable {
public let nodeId: String
public let shardId: String
enum CodingKeys: String, CodingKey {
case nodeId = "_node"
case shardId = "_shard"
}
}
public struct HighlightField: Codable, Equatable {
public let name: String
public let fragments: [String]
}
public struct NestedIdentity {
public let field: String
public let offset: Int
private let _nested: [NestedIdentity]?
public init(field: String, offset: Int, nested: NestedIdentity?) {
self.field = field
self.offset = offset
if let nested = nested {
_nested = [nested]
} else {
_nested = nil
}
}
public var child: NestedIdentity? {
if let nested = _nested, !nested.isEmpty {
return nested[0]
}
return nil
}
}
extension NestedIdentity: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(field, forKey: .field)
try container.encode(offset, forKey: .offset)
if let nested = _nested, !nested.isEmpty {
try container.encode(nested[0], forKey: .nested)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
field = try container.decodeString(forKey: .field)
offset = try container.decodeInt(forKey: .offset)
let nested = try container.decodeIfPresent(NestedIdentity.self, forKey: .nested)
if let nested = nested {
_nested = [nested]
} else {
_nested = nil
}
}
enum CodingKeys: String, CodingKey {
case field
case offset
case nested = "_nested"
}
}
extension NestedIdentity: Equatable {
public static func == (lhs: NestedIdentity, rhs: NestedIdentity) -> Bool {
return lhs.field == rhs.field && lhs.offset == rhs.offset
&& lhs.child == rhs.child
}
}
// MARK: - Delete Response
public struct DeleteResponse: Codable, Equatable {
public let shards: Shards
public let index: String
public let type: String
public let id: String
public let version: Int
public let seqNumber: Int
public let primaryTerm: Int
public let result: String
enum CodingKeys: String, CodingKey {
case shards = "_shards"
case index = "_index"
case type = "_type"
case id = "_id"
case version = "_version"
case seqNumber = "_seq_no"
case primaryTerm = "_primary_term"
case result
}
}
// MARK: - Delete By Query Response
public struct DeleteByQueryResponse: Codable, Equatable {
public let took: Int
public let timedOut: Bool
public let total: Int
public let deleted: Int
public let batches: Int
public let versionConflicts: Int
public let noops: Int
public let retries: Retires
public let throlledMillis: Int
public let requestsPerSecond: Int
public let throlledUntilMillis: Int
public let failures: [CodableValue]
enum CodingKeys: String, CodingKey {
case took
case timedOut = "timed_out"
case total
case deleted
case batches
case versionConflicts = "version_conflicts"
case noops
case retries
case throlledMillis = "throttled_millis"
case requestsPerSecond = "requests_per_second"
case throlledUntilMillis = "throttled_until_millis"
case failures
}
}
public struct Retires: Codable, Equatable {
public let bulk: Int
public let search: Int
}
// MARK: - Update By Query Response
public struct UpdateByQueryResponse: Codable, Equatable {
public let took: Int
public let timedOut: Bool
public let total: Int
public let updated: Int
public let deleted: Int
public let batches: Int
public let versionConflicts: Int
public let noops: Int
public let retries: Retires
public let throlledMillis: Int
public let requestsPerSecond: Int
public let throlledUntilMillis: Int
public let failures: [CodableValue]
enum CodingKeys: String, CodingKey {
case took
case timedOut = "timed_out"
case total
case deleted
case updated
case batches
case versionConflicts = "version_conflicts"
case noops
case retries
case throlledMillis = "throttled_millis"
case requestsPerSecond = "requests_per_second"
case throlledUntilMillis = "throttled_until_millis"
case failures
}
}
// MARK: - Multi Get Response
public struct MultiGetResponse: Codable, Equatable {
public let responses: [MultiGetItemResponse]
public struct Failure: Codable, Equatable {
public let index: String
public let id: String
public let type: String?
public let error: ElasticError
enum CodingKeys: String, CodingKey {
case index = "_index"
case id = "_id"
case type = "_type"
case error
}
}
enum CodingKeys: String, CodingKey {
case responses = "docs"
}
}
public struct MultiGetItemResponse: Codable, Equatable {
public let response: GetResponse<CodableValue>?
public let failure: MultiGetResponse.Failure?
public func encode(to encoder: Encoder) throws {
if let response = self.response {
try response.encode(to: encoder)
} else {
try failure.encode(to: encoder)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
response = try container.decode(GetResponse<CodableValue>.self)
failure = nil
} catch {
failure = try container.decode(MultiGetResponse.Failure.self)
response = nil
}
}
}
// MARK: - UPDATE RESPONSE
public struct UpdateResponse: Codable, Equatable {
public let shards: Shards
public let index: String
public let type: String
public let id: String
public let version: Int
public let result: String
private enum CodingKeys: String, CodingKey {
case shards = "_shards"
case index = "_index"
case type = "_type"
case id = "_id"
case version = "_version"
case result
}
}
// MARK: - ReIndex Response
public struct ReIndexResponse: Codable, Equatable {
public let took: Int
public let timeout: Bool
public let created: Int
public let updated: Int
public let deleted: Int
public let batches: Int
public let versionConflicts: Int
public let noops: Int
public let retries: Retries
public let throttledMillis: Int
public let requestsPerSecond: Int
public let throttledUntilMillis: Int
public let total: Int
public let failures: [CodableValue]
public struct Retries: Codable, Equatable {
public let bulk: Int
public let search: Int
}
enum CodingKeys: String, CodingKey {
case took
case timeout = "timed_out"
case created
case updated
case deleted
case batches
case versionConflicts = "version_conflicts"
case noops
case retries
case throttledMillis = "throttled_millis"
case requestsPerSecond = "requests_per_second"
case throttledUntilMillis = "throttled_until_millis"
case total
case failures
}
}
// MARK: - TermVectors Response
public struct TermVectorsResponse: Codable, Equatable {
public let id: String?
public let index: String
public let type: String
public let version: Int?
public let found: Bool
public let took: Int
public let termVerctors: [TermVector]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeStringIfPresent(forKey: .id)
index = try container.decodeString(forKey: .index)
type = try container.decodeString(forKey: .type)
version = try container.decodeIntIfPresent(forKey: .version)
found = try container.decodeBool(forKey: .found)
took = try container.decodeInt(forKey: .took)
do {
let dic = try container.decode([String: TermVectorMetaData].self, forKey: .termVerctors)
termVerctors = dic.map { key, value -> TermVector in
TermVector(field: key, fieldStatistics: value.fieldStatistics, terms: value.terms)
}
} catch let Swift.DecodingError.keyNotFound(key, context) {
if key.stringValue == CodingKeys.termVerctors.stringValue {
self.termVerctors = []
} else {
throw Swift.DecodingError.keyNotFound(key, context)
}
}
}
enum CodingKeys: String, CodingKey {
case id = "_id"
case index = "_index"
case type = "_type"
case version
case found
case took
case termVerctors = "term_vectors"
}
public struct TermVector: Codable, Equatable {
public let field: String
public let fieldStatistics: FieldStatistics?
public let terms: [Term]
enum CodingKeys: String, CodingKey {
case field
case fieldStatistics = "field_statistics"
case terms
}
}
public struct TermVectorMetaData: Codable, Equatable {
public let fieldStatistics: FieldStatistics?
public let terms: [Term]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
fieldStatistics = try container.decodeIfPresent(FieldStatistics.self, forKey: .fieldStatistics)
let dic = try container.decode([String: TermStatistics].self, forKey: .terms)
terms = dic.map { key, value -> Term in
Term(term: key, termStatistics: value)
}
}
enum CodingKeys: String, CodingKey {
case fieldStatistics = "field_statistics"
case terms
}
}
public struct FieldStatistics: Codable, Equatable {
public let docCount: Int
public let sumDocFreq: Int
public let sumTtf: Int
enum CodingKeys: String, CodingKey {
case docCount = "doc_count"
case sumDocFreq = "sum_doc_freq"
case sumTtf = "sum_ttf"
}
}
public struct Term: Codable, Equatable {
public let term: String
public let docFreq: Int?
public let termFreq: Int
public let tokens: [Token]
public let ttf: Int?
public init(term: String, termStatistics: TermStatistics) {
self.term = term
docFreq = termStatistics.docFreq
termFreq = termStatistics.termFreq
tokens = termStatistics.tokens ?? []
ttf = termStatistics.ttf
}
}
public struct TermStatistics: Codable, Equatable {
public let docFreq: Int?
public let termFreq: Int
public let tokens: [Token]?
public let ttf: Int?
enum CodingKeys: String, CodingKey {
case docFreq = "doc_freq"
case termFreq = "term_freq"
case tokens
case ttf
}
}
public struct Token: Codable, Equatable {
public let payload: String?
public let position: Int
public let startOffset: Int
public let endOffset: Int
enum CodingKeys: String, CodingKey {
case payload
case position
case startOffset = "start_offset"
case endOffset = "end_offset"
}
}
}
// MARK: - Multi Term Vectors Response
public struct MultiTermVectorsResponse: Codable {
public let responses: [TermVectorsResponse]
enum CodingKeys: String, CodingKey {
case responses = "docs"
}
}
extension MultiTermVectorsResponse: Equatable {}
// MARK: - Bulk Response
public struct BulkResponse: Codable {
public let took: Int
public let errors: Bool
public let items: [BulkResponseItem]
public struct BulkResponseItem: Codable, Equatable {
public let opType: OpType
public let response: SuccessResponse?
public let failure: Failure?
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
guard container.allKeys.first != nil else {
throw Swift.DecodingError.dataCorrupted(.init(codingPath: container.codingPath, debugDescription: "Unable to Determine OpType CodingKey in \(container.allKeys)"))
}
let opTypeKey = container.allKeys.first!
if let opType = OpType(rawValue: opTypeKey.stringValue) {
self.opType = opType
} else {
throw Swift.DecodingError.dataCorruptedError(forKey: container.allKeys.first!, in: container, debugDescription: "Unable to determine OpType from value: \(opTypeKey.stringValue)")
}
do {
response = try container.decode(SuccessResponse.self, forKey: opTypeKey)
failure = nil
} catch {
response = nil
failure = try container.decode(Failure.self, forKey: opTypeKey)
}
}
}
public struct SuccessResponse: Codable, Equatable {
public let index: String
public let type: String
public let id: String
public let status: Int
public let result: Result
public let shards: Shards
public let version: Int
public let seqNo: Int
public let primaryTerm: Int
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case status
case result
case shards = "_shards"
case seqNo = "_seq_no"
case primaryTerm = "_primary_term"
case version = "_version"
}
}
public struct Failure: Codable, Equatable {
public let index: String
public let type: String
public let id: String
public let cause: ElasticError
public let status: Int
public let aborted: Bool?
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case cause = "error"
case status
case aborted
}
}
public enum Result: String, Codable {
case created
case updated
case deleted
case notFount = "not_found"
case noop
}
}
extension BulkResponse: Equatable {}
// MARK: - Clear Scroll Response
public struct ClearScrollResponse: Codable {
public let succeeded: Bool
public let numFreed: Int
enum CodingKeys: String, CodingKey {
case succeeded
case numFreed = "num_freed"
}
}
extension ClearScrollResponse: Equatable {}
// MARK: - Count Response
/// A response to _count API request.
public struct CountResponse: Codable {
public let count: Int
public let shards: Shards
public let terminatedEarly: Bool?
enum CodingKeys: String, CodingKey {
case count
case shards = "_shards"
case terminatedEarly = "terminated_early"
}
}
extension CountResponse: Equatable {}
// MARK: - Explain Response
public struct ExplainResponse: Codable {
public let index: String
public let type: String
public let id: String
public let matched: Bool
public let explanation: Explanation
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case matched
case explanation
}
}
extension ExplainResponse: Equatable {}
// MARK: - Field Capabilities Response
/// Response for FieldCapabilitiesIndexRequest requests.
public struct FieldCapabilitiesResponse {
public let fields: [String: [String: FieldCapabilities]]
}
extension FieldCapabilitiesResponse: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let fieldsResponse = try container.decode([String: [String: FieldCaps]].self, forKey: .fields)
var fields = [String: [String: FieldCapabilities]]()
for field in fieldsResponse.keys {
for type in fieldsResponse[field]!.keys {
let fieldCaps = fieldsResponse[field]![type]!
if fields.keys.contains(field) {
fields[field]![type] = fieldCaps.toFieldCapabilities(field, type: type)
} else {
fields[field] = [String: FieldCapabilities]()
fields[field]![type] = fieldCaps.toFieldCapabilities(field, type: type)
}
}
}
self.fields = fields
}
public func encode(to encoder: Encoder) throws {
var fields = [String: [String: FieldCaps]]()
for field in self.fields.keys {
for type in self.fields[field]!.keys {
let fieldCaps = self.fields[field]![type]!
if fields.keys.contains(field) {
fields[field]![type] = FieldCaps.fromFieldCapabilities(fieldCaps)
} else {
fields[field] = [String: FieldCaps]()
fields[field]![type] = FieldCaps.fromFieldCapabilities(fieldCaps)
}
}
}
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(fields, forKey: .fields)
}
internal struct FieldCaps: Codable, Equatable {
public let type: String?
public let searchable: Bool
public let aggregatable: Bool
public let indices: [String]?
public let nonSearchableIndices: [String]?
public let nonAggregatableIndicies: [String]?
func toFieldCapabilities(_ name: String, type: String) -> FieldCapabilities {
return FieldCapabilities(name: name, type: type, isSearchable: searchable, isAggregatable: aggregatable, indices: indices, nonSearchableIndices: nonSearchableIndices, nonAggregatableIndicies: nonAggregatableIndicies)
}
static func fromFieldCapabilities(_ caps: FieldCapabilities) -> FieldCaps {
return FieldCaps(type: caps.type, searchable: caps.isSearchable, aggregatable: caps.isAggregatable, indices: caps.indices, nonSearchableIndices: caps.nonSearchableIndices, nonAggregatableIndicies: caps.nonAggregatableIndicies)
}
enum CodingKeys: String, CodingKey {
case type
case searchable
case aggregatable
case indices
case nonSearchableIndices = "non_searchable_indices"
case nonAggregatableIndicies = "non_aggregatable_indices"
}
}
enum CodingKeys: String, CodingKey {
case fields
}
}
extension FieldCapabilitiesResponse: Equatable {}
/// Describes the capabilities of a field optionally merged across multiple indices.
public struct FieldCapabilities: Codable {
public let name: String
public let type: String
public let isSearchable: Bool
public let isAggregatable: Bool
public let indices: [String]?
public let nonSearchableIndices: [String]?
public let nonAggregatableIndicies: [String]?
}
extension FieldCapabilities: Equatable {}
// MARK: - RankEvalResponse
public struct RankEvalResponse: Codable {
public let metricScore: Decimal
public let details: [String: EvalQueryQuality]
public let failures: [String: ElasticError]
enum CodingKeys: String, CodingKey {
case metricScore = "metric_score"
case details
case failures
}
}
extension RankEvalResponse: Equatable {}
public struct EvalQueryQuality {
public let queryId: String?
public let metricScore: Decimal
public let metricDetails: MetricDetail?
public let ratedHits: [RatedSearchHit]
public let unratedDocs: [UnratedDocument]
}
extension EvalQueryQuality: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
metricScore = try container.decodeDecimal(forKey: .metricScore)
metricDetails = try container.decodeMetricDetailIfPresent(forKey: .metricDetails)
ratedHits = try container.decodeArray(forKey: .ratedHits)
unratedDocs = try container.decode([UnratedDocument].self, forKey: .unratedDocs)
queryId = nil
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(metricScore, forKey: .metricScore)
try container.encodeIfPresent(metricDetails, forKey: .metricDetails)
try container.encode(ratedHits, forKey: .ratedHits)
try container.encode(unratedDocs, forKey: .unratedDocs)
}
enum CodingKeys: String, CodingKey {
case metricScore = "metric_score"
case unratedDocs = "unrated_docs"
case metricDetails = "metric_details"
case ratedHits = "hits"
}
}
extension EvalQueryQuality: Equatable {
public static func == (lhs: EvalQueryQuality, rhs: EvalQueryQuality) -> Bool {
return lhs.queryId == rhs.queryId
&& lhs.metricScore == rhs.metricScore
&& lhs.ratedHits == rhs.ratedHits
&& isEqualMetricDetails(lhs.metricDetails, rhs.metricDetails)
&& lhs.unratedDocs == rhs.unratedDocs
}
}
public struct RatedSearchHit {
public let searchHit: SearchHit<CodableValue>
public let rating: Int?
}
extension RatedSearchHit: Codable {
enum CodingKeys: String, CodingKey {
case searchHit = "hit"
case rating
}
}
extension RatedSearchHit: Equatable {}
public struct UnratedDocument {
public let index: String
public let id: String
}
extension UnratedDocument: Codable {
enum CodingKeys: String, CodingKey {
case index = "_index"
case id = "_id"
}
}
extension UnratedDocument: Equatable {}
// MARK: - Get StoredScript Response
public struct GetStoredScriptResponse {
public let id: String
public let found: Bool
public let script: StoredScriptSource?
}
extension GetStoredScriptResponse: Codable {
enum CodingKeys: String, CodingKey {
case id = "_id"
case found
case script
}
}
extension GetStoredScriptResponse: Equatable {}
// MARK: - Cluster Health Response
public struct ClusterHealthResponse {
public let clusterName: String
public let status: ClusterHealthStatus
public let timedOut: Bool
public let numberOfNodes: Int
public let numberOfDataNodes: Int
public let activePrimaryShards: Int
public let activeShards: Int
public let relocatingShards: Int
public let initializingShards: Int
public let unassignedShards: Int
public let delayedUnassignedShards: Int
public let numberOfPendingTasks: Int
public let numberOfInFlightFetch: Int
public let taskMaxWaitingInQueueMillis: Int
public let activeShardsPercentAsNumber: Decimal
public let indices: [String: ClusterIndexHealth]?
}
extension ClusterHealthResponse: Codable {
enum CodingKeys: String, CodingKey {
case clusterName = "cluster_name"
case status
case timedOut = "timed_out"
case numberOfNodes = "number_of_nodes"
case numberOfDataNodes = "number_of_data_nodes"
case activePrimaryShards = "active_primary_shards"
case activeShards = "active_shards"
case relocatingShards = "relocating_shards"
case initializingShards = "initializing_shards"
case unassignedShards = "unassigned_shards"
case delayedUnassignedShards = "delayed_unassigned_shards"
case numberOfPendingTasks = "number_of_pending_tasks"
case numberOfInFlightFetch = "number_of_in_flight_fetch"
case taskMaxWaitingInQueueMillis = "task_max_waiting_in_queue_millis"
case activeShardsPercentAsNumber = "active_shards_percent_as_number"
case indices
}
}
extension ClusterHealthResponse: Equatable {}
public struct ClusterIndexHealth {
public let status: ClusterHealthStatus
public let numberOfShards: Int
public let numberOfReplicas: Int
public let activePrimaryShards: Int
public let activeShards: Int
public let relocatingShards: Int
public let initializingShards: Int
public let unassignedShards: Int
public let shards: [String: ClusterShardHealth]?
}
extension ClusterIndexHealth: Codable {
enum CodingKeys: String, CodingKey {
case status
case numberOfShards = "number_of_shards"
case numberOfReplicas = "number_of_replicas"
case activePrimaryShards = "active_primary_shards"
case activeShards = "active_shards"
case relocatingShards = "relocating_shards"
case initializingShards = "initializing_shards"
case unassignedShards = "unassigned_shards"
case shards
}
}
extension ClusterIndexHealth: Equatable {}
public struct ClusterShardHealth {
public let status: ClusterHealthStatus
public let primaryActive: Bool
public let activeShards: Int
public let relocatingShards: Int
public let initializingShards: Int
public let unassignedShards: Int
}
extension ClusterShardHealth: Codable {
enum CodingKeys: String, CodingKey {
case status
case primaryActive = "primary_active"
case activeShards = "active_shards"
case relocatingShards = "relocating_shards"
case initializingShards = "initializing_shards"
case unassignedShards = "unassigned_shards"
}
}
extension ClusterShardHealth: Equatable {}
public struct ClusterGetSettingsResponse {
public let persistent: [String: CodableValue]
public let transient: [String: CodableValue]
public let defaults: [String: CodableValue]?
}
extension ClusterGetSettingsResponse: Codable {}
extension ClusterGetSettingsResponse: Equatable {}
public struct ClusterUpdateSettingsResponse {
public let acknowledged: Bool
public let persistent: [String: CodableValue]
public let transient: [String: CodableValue]
}
extension ClusterUpdateSettingsResponse: Codable {}
extension ClusterUpdateSettingsResponse: Equatable {}
| 125733d37636751e229eb71b9912a453 | 30.408753 | 296 | 0.64878 | false | false | false | false |
aleffert/dials | refs/heads/master | Desktop/Source/FormattingUtilities.swift | mit | 1 | //
// FormattingUtilities.swift
// Dials-Desktop
//
// Created by Akiva Leffert on 3/22/15.
//
//
import Foundation
func stringFromNumber(_ value : Float, requireIntegerPart : Bool = false) -> String {
return stringFromNumber(NSNumber(value: value as Float), requireIntegerPart : requireIntegerPart)
}
func stringFromNumber(_ value : CGFloat, requireIntegerPart : Bool = false) -> String {
return stringFromNumber(NSNumber(value: Double(value)), requireIntegerPart : requireIntegerPart)
}
func stringFromNumber(_ value : Double, requireIntegerPart : Bool = false) -> String {
return stringFromNumber(NSNumber(value: value as Double), requireIntegerPart : requireIntegerPart)
}
func stringFromNumber(_ value : NSNumber, requireIntegerPart : Bool = false) -> String {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.alwaysShowsDecimalSeparator = false
formatter.minimumIntegerDigits = requireIntegerPart ? 1 : 0
return formatter.string(from: value)!
}
extension String {
func formatWithParameters(_ parameters : [String:Any]) -> String {
let result = self.mutableCopy() as! NSMutableString
for (key, value) in parameters {
let range = NSMakeRange(0, result.length)
let token = "{\(key)}"
result.replaceOccurrences(of: token, with: "\(value)", options: NSString.CompareOptions(), range: range)
}
return result as String
}
}
| 44a8ba4e273f1b5b5cee40558ae2526c | 34.853659 | 116 | 0.704082 | false | false | false | false |
ianfelzer1/ifelzer-advprog | refs/heads/master | Last Year/IOS Development- J Term 2017/Stopwatch/Stopwatch/Stopwatch.swift | gpl-3.0 | 1 | //
// File.swift
// Stopwatch
//
// Created by Programming on 1/18/17.
// Copyright © 2017 Ian Felzer. All rights reserved.
//
import Foundation
class Stopwatch {
var totalTime : TimeInterval = 0
var startTime: NSDate?
var elapsedTime: TimeInterval {
if self.startTime != nil {
return -self.startTime!.timeIntervalSinceNow + totalTime
} else {
return self.totalTime
}
}
var formattedElapsedTime: String {
let miliseconds = Int(round(self.elapsedTime * 100).truncatingRemainder(dividingBy: 100))
let millizero = miliseconds < 10 ? "0" : ""
let seconds = Int(round(self.elapsedTime).truncatingRemainder(dividingBy: 60))
let seczero = seconds < 10 ? "0" : ""
let minutes = Int(elapsedTime / 60)
let minzero = minutes < 10 ? "0" : ""
return String("\(minzero)\(minutes):\(seczero)\(seconds):\(millizero)\(miliseconds)")
}
var isRunning = false
func start() {
self.startTime = NSDate()
self.isRunning = true
}
func stop() {
if self.isRunning {
self.totalTime = self.totalTime - self.startTime!.timeIntervalSinceNow
}
self.isRunning = false
}
func reset() {
self.totalTime = 0
self.startTime = nil
}
}
| 0c07182241f16d6f080b2d889164b128 | 25.607843 | 97 | 0.582167 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-payload_size.swift | apache-2.0 | 3 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -enable-library-evolution -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOySiGWV" = linkonce_odr hidden constant %swift.enum_vwtable
// CHECK: @"$s4main5ValueOySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// Payload size.
// CHECK-SAME: [[INT]] 8,
// Trailing flags.
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
public struct First<Tag> {
public let value: Int64
}
public struct Second {
public let value: Int64
}
@frozen
public enum Value<Tag> {
case first(First<Tag>)
case second(Second)
static func only(_ int: Int) -> Self {
return .second(Second(value: Int64(int)))
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOySiGMf" to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value<Int>.only(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define{{( protected)?}} swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOySiGMf" to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* %2,
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| ff6826eff92ec083d1acfc0560944dfa | 35.649573 | 183 | 0.571129 | false | false | false | false |
TempoDiValse/DCHelper | refs/heads/master | DCHelper/SafariExtensionHandler.swift | mit | 1 | //
// SafariExtensionHandler.swift
// DCHelper
//
// Created by LaValse on 2016. 11. 1..
// Copyright © 2016년 LaValse. All rights reserved.
//
import SafariServices
class SafariExtensionHandler: SFSafariExtensionHandler {
let BRIDGE_FUNC = "fromExtension"
let defaults = UserDefaults.standard
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
page.getPropertiesWithCompletionHandler({
let url = $0?.url?.absoluteString
if (url?.hasPrefix(Const.Page.DOMAIN_PREFIX))! {
if((url?.contains(Const.Page.List))! || (url?.contains(Const.Page.View))!){
/* specific function of its page */
guard messageName != Const.MessageType.SendURLFromWeb else {
let href = userInfo!["href"] as! String
let urls = userInfo!["urls"] as! [[String:String]]
/* 이미 꺼져 버린 페이지에서 호출이 일어나 URL 대조가 필요 */
guard href == url else {
return
}
let ctrlr = ImageDownloadController()
ctrlr.setURLs(url: urls)
self.performSelector(onMainThread: #selector(self.openDownloadList), with: ctrlr, waitUntilDone: true)
return
}
guard messageName != Const.MessageType.RecentVisited else {
let list = userInfo?["list"]!
self.defaults.set(list, forKey: Const.USER_RECENT_VISITED)
self.defaults.synchronize()
return
}
/* common function of its page */
let bPerson = self.defaults.array(forKey: Const.USER_BLOCK_ARRAY) as! [String]?
let bTitle = self.defaults.array(forKey: Const.USER_TITLE_BLOCK_ARRAY) as! [String]?
if bPerson?.count != 0 && bTitle?.count != 0 {
let joinPerson = bPerson?.joined(separator:"|") ?? ""
let regTitle = self.arrayToReg(_arr: bTitle)
page.dispatchMessageToScript(withName: self.BRIDGE_FUNC, userInfo: [
"type": Const.MessageType.Block,
"person": joinPerson,
"title": regTitle
])
}
}else if(url?.contains(Const.Page.Write))!{
guard messageName != Const.MessageType.GetImage else{
self.sendFixImage()
return
}
let isAutoAdd = self.defaults.bool(forKey: Const.USER_IMG_ADD_AUTO)
if isAutoAdd {
self.sendFixImage()
}else{
page.dispatchMessageToScript(withName: self.BRIDGE_FUNC, userInfo: ["type": Const.MessageType.AddButton])
}
}
}
})
}
private func arrayToReg(_arr:[String]?) -> String {
guard _arr != nil else{
return ""
}
var buf = "("
for i in 0 ... _arr!.count-1{
let _o = _arr![i]
buf += "\(_o)"
if i < _arr!.count-1 {
buf += "|"
}
}
buf += ")"
return buf;
}
func openDownloadList(sender: Any){
let pVC = self.popoverViewController()
pVC.presentViewController(sender as! ImageDownloadController, asPopoverRelativeTo: NSRect(x: 0, y: 0, width: 0, height: 0), of: pVC.view, preferredEdge: NSRectEdge.maxX, behavior: .transient)
}
func sendFixImage(){
let url = defaults.string(forKey: Const.USER_IMG_SRC)
if url != nil {
do{
let fileName = URL(string:url!)?.lastPathComponent
let data = try Data.init(contentsOf: URL(string:url!)!).base64EncodedString()
let datas = [
"type": Const.MessageType.AutoImage,
"args": [
"fileName": fileName,
"data": data
]
] as [String : Any]
SFSafariApplication.getActiveWindow(completionHandler: {
$0?.getActiveTab(completionHandler: {
$0?.getActivePage(completionHandler: {
$0?.dispatchMessageToScript(withName: self.BRIDGE_FUNC, userInfo: datas)
})
})
})
}catch{
print(error)
}
}
}
override func toolbarItemClicked(in window: SFSafariWindow) {
}
override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) {
validationHandler(true, "")
}
override func popoverWillShow(in window: SFSafariWindow) {}
override func popoverDidClose(in window: SFSafariWindow) {}
override func popoverViewController() -> SFSafariExtensionViewController {
return SafariExtensionViewController.shared
}
}
| 4db68b7cbe5d3c64b5f6ce1831bb173f | 36.425806 | 199 | 0.460955 | false | false | false | false |
laszlokorte/reform-swift | refs/heads/master | ReformCore/ReformCore/VM.swift | mit | 1 | //
// VM.swift
// ReformCore
//
// Created by Laszlo Korte on 09.09.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
typealias VMInstruction = Int
typealias VMProgramm = [VMInstruction]
enum VMError : Error {
case invalidInstruction
}
class VM {
fileprivate var memory = [Int]()
fileprivate var stack = [Int]()
fileprivate var halt = true
fileprivate var programCounter: Int = 0
fileprivate var nextPC : Int? = nil
func run(_ program: VMProgramm) throws {
programCounter = 0
halt = false
while !halt && programCounter < program.count {
guard let instruction = VMOperatation(rawValue: program[programCounter]) else {
throw VMError.invalidInstruction
}
instruction.executeOn(self)
programCounter = nextPC ?? programCounter + 1
}
}
}
enum VMOperatation : VMInstruction {
case pushImmediate
case load
case store
case pop
case mulInt
case addInt
case subInt
case divInt
case mulFloat
case addFloat
case subFloat
case divFloat
case sin
case cos
case tan
case arcSin
case arcCos
case arcTan
case sqrt
case lessThan
case equal
case intToFloat
case floatToInt
case halt
fileprivate func executeOn(_ vm: VM) {
switch self {
case .pushImmediate:
vm.nextPC = vm.programCounter + 1
case .load:
vm.nextPC = vm.programCounter + 1
case .store:
vm.nextPC = vm.programCounter + 1
case .pop:
vm.nextPC = vm.programCounter + 1
case .mulInt:
vm.nextPC = vm.programCounter + 1
case .addInt:
vm.nextPC = vm.programCounter + 1
case .subInt:
vm.nextPC = vm.programCounter + 1
case .divInt:
vm.nextPC = vm.programCounter + 1
case .mulFloat:
vm.nextPC = vm.programCounter + 1
case .addFloat:
vm.nextPC = vm.programCounter + 1
case .subFloat:
vm.nextPC = vm.programCounter + 1
case .divFloat:
vm.nextPC = vm.programCounter + 1
case .sin:
vm.nextPC = vm.programCounter + 1
case .cos:
vm.nextPC = vm.programCounter + 1
case .tan:
vm.nextPC = vm.programCounter + 1
case .arcSin:
vm.nextPC = vm.programCounter + 1
case .arcCos:
vm.nextPC = vm.programCounter + 1
case .arcTan:
vm.nextPC = vm.programCounter + 1
case .sqrt:
vm.nextPC = vm.programCounter + 1
case .lessThan:
vm.nextPC = vm.programCounter + 1
case .equal:
vm.nextPC = vm.programCounter + 1
case .intToFloat:
vm.nextPC = vm.programCounter + 1
case .floatToInt:
vm.nextPC = vm.programCounter + 1
case .halt:
vm.halt = true
}
}
}
| 8b26d084f616b8b1de72af5bc0ed99e5 | 22.546154 | 91 | 0.555047 | false | false | false | false |
lovemo/MVVMFramework-Swift | refs/heads/master | SwiftMVVMKitDemo/SwiftMVVMKitDemo/Classes/Src/secondExample/View/BQCollectionCell.swift | mit | 1 | //
// BQCollectionCell.swift
// MVVMFramework-Swift
//
// Created by momo on 15/12/29.
// Copyright © 2015年 momo. All rights reserved.
//
import UIKit
class BQCollectionCell: UICollectionViewCell {
@IBOutlet weak var lbTitle: UILabel!
@IBOutlet weak var lbHeight: UILabel!
override func configure(cell: UICollectionViewCell, customObj obj: AnyObject, indexPath: NSIndexPath) {
let mycell = cell as! BQCollectionCell
mycell.lbTitle.text = "CollectionCell"
mycell.lbHeight.text = "Swift is a powerful and intuitive programming language for iOS, OS X, tvOS, and watchOS. "
}
override func awakeFromNib() {
super.awakeFromNib()
self.layer.borderColor = UIColor.brownColor().CGColor
self.layer.borderWidth = 2.0;
self.layer.cornerRadius = 5.0;
}
}
| 9d36c54cb19cd7e382cb0901ab7e87a4 | 28.137931 | 122 | 0.676923 | false | false | false | false |
cloudant/swift-cloudant | refs/heads/master | Source/SwiftCloudant/HTTP/RequestExecutor.swift | apache-2.0 | 1 | //
// RequestExecutor.swift
// SwiftCloudant
//
// Created by Rhys Short on 03/03/2016.
// Copyright (c) 2016 IBM Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
import Foundation
/**
Contains HTTP response information.
*/
public struct HTTPInfo {
/**
The status code of the HTTP request.
*/
public let statusCode: Int
/**
The headers that were returned by the server.
*/
public let headers: [String: String]
}
/**
Executes a `HTTPRequestOperation`'s HTTP request.
*/
class OperationRequestExecutor: InterceptableSessionDelegate {
/**
The HTTP task currently processing
*/
var task: URLSessionTask?
/**
The operation which this OperationRequestExecutor is Executing.
*/
let operation: HTTPRequestOperation
var buffer: Data
var response: HTTPURLResponse?
/**
Creates an OperationRequestExecutor.
- parameter operation: The operation that this OperationRequestExecutor will execute
*/
init(operation: HTTPRequestOperation) {
self.operation = operation
task = nil
buffer = Data()
}
func received(data: Data) {
// This class doesn't support streaming of data
// so we buffer until the request completes
// and then we will deliver it to the
// operation in chunk.
buffer.append(data)
}
func received(response: HTTPURLResponse) {
// Store the response to deliver with the data when the task completes.
self.response = response
}
func completed(error: Error?) {
self.task = nil // allow task to be deallocated.
// task has completed, handle the operation canceling etc.
if self.operation.isCancelled {
self.operation.completeOperation()
return
}
let httpInfo: HTTPInfo?
if let response = response {
var headers:[String: String] = [:]
for (key, value) in response.allHeaderFields {
headers["\(key)"] = "\(value)"
}
httpInfo = HTTPInfo(statusCode: response.statusCode, headers: headers)
} else {
httpInfo = nil
}
self.operation.processResponse(data: buffer, httpInfo: httpInfo, error: error)
self.operation.completeOperation()
}
/**
Executes the HTTP request for the operation held in the `operation` property
*/
func executeRequest () {
do {
let builder = OperationRequestBuilder(operation: self.operation)
let request = try builder.makeRequest()
self.task = self.operation.session.dataTask(request: request, delegate: self)
self.task?.resume()
} catch {
self.operation.processResponse(data: nil, httpInfo: nil, error: error)
self.operation.completeOperation()
}
}
/**
Cancels the currently processing HTTP task.
*/
func cancel() {
if let task = task {
task.cancel()
}
}
}
| fba58d7d03276b355144b6f5afb3114a | 28.064 | 94 | 0.618772 | false | false | false | false |
everald/JetPack | refs/heads/master | Sources/UI/Label.swift | mit | 1 | import UIKit
@objc(JetPack_Label)
open class Label: View {
private lazy var delegateProxy: DelegateProxy = DelegateProxy(label: self)
private let linkTapRecognizer = UITapGestureRecognizer()
private let textLayer = TextLayer()
open var linkTapped: ((URL) -> Void)?
public override init() {
super.init()
clipsToBounds = false
textLayer.contentsScale = gridScaleFactor
layer.addSublayer(textLayer)
setUpLinkTapRecognizer()
}
@available(*, deprecated: 1, message: "Use init() instead of init(highPrecision: true) since this is the new default. 'false' is deprecated.", renamed: "init()")
public convenience init(highPrecision: Bool) {
self.init()
textLayer.highPrecision = highPrecision
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open var additionalLinkHitZone: UIEdgeInsets {
get { return textLayer.additionalLinkHitZone }
set { textLayer.additionalLinkHitZone = newValue }
}
open var attributedText: NSAttributedString {
get { return textLayer.attributedText }
set {
guard newValue != textLayer.attributedText else {
return
}
textLayer.attributedText = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
textLayer.contentsScale = gridScaleFactor
}
}
open var font: UIFont {
get { return textLayer.font }
set {
guard newValue != textLayer.font else {
return
}
textLayer.font = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
@objc
private func handleLinkTapRecognizer() {
guard let link = link(at: linkTapRecognizer.location(in: self)) else {
return
}
linkTapped?(link)
}
open var horizontalAlignment: TextAlignment.Horizontal {
get { return textLayer.horizontalAlignment }
set {
guard newValue != textLayer.horizontalAlignment else {
return
}
textLayer.horizontalAlignment = newValue
setNeedsLayout()
}
}
open var kerning: TextKerning? {
get { return textLayer.kerning }
set {
guard newValue != textLayer.kerning else {
return
}
textLayer.kerning = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open override func layoutSubviews() {
super.layoutSubviews()
let maximumTextLayerFrame = bounds.insetBy(padding)
guard maximumTextLayerFrame.size.isPositive else {
textLayer.isHidden = true
return
}
textLayer.isHidden = false
var textLayerFrame = CGRect()
textLayerFrame.size = textLayer.textSize(thatFits: maximumTextLayerFrame.size)
switch horizontalAlignment {
case .left,
.natural where effectiveUserInterfaceLayoutDirection == .leftToRight:
textLayerFrame.left = maximumTextLayerFrame.left
case .center:
textLayerFrame.horizontalCenter = maximumTextLayerFrame.horizontalCenter
case .right, .natural:
textLayerFrame.right = maximumTextLayerFrame.right
case .justified:
textLayerFrame.left = maximumTextLayerFrame.left
textLayerFrame.width = maximumTextLayerFrame.width
}
textLayer.textSize = textLayerFrame.size
switch verticalAlignment {
case .top: textLayerFrame.top = maximumTextLayerFrame.top
case .center: textLayerFrame.verticalCenter = maximumTextLayerFrame.verticalCenter
case .bottom: textLayerFrame.bottom = maximumTextLayerFrame.bottom
}
textLayerFrame.insetInPlace(textLayer.contentInsets)
textLayer.frame = alignToGrid(textLayerFrame)
}
open var lineBreakMode: NSLineBreakMode {
get { return textLayer.lineBreakMode }
set {
guard newValue != textLayer.lineBreakMode else {
return
}
textLayer.lineBreakMode = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open var lineHeightMultiple: CGFloat {
get { return textLayer.lineHeightMultiple }
set {
guard newValue != textLayer.lineHeightMultiple else {
return
}
textLayer.lineHeightMultiple = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
public func link(at point: CGPoint) -> URL? {
return textLayer.link(at: layer.convert(point, to: textLayer))?.url
}
open var maximumLineHeight: CGFloat? {
get { return textLayer.maximumLineHeight }
set {
guard newValue != textLayer.maximumLineHeight else {
return
}
textLayer.maximumLineHeight = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open var maximumNumberOfLines: Int? {
get { return textLayer.maximumNumberOfLines }
set {
guard newValue != textLayer.maximumNumberOfLines else {
return
}
textLayer.maximumNumberOfLines = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open override func measureOptimalSize(forAvailableSize availableSize: CGSize) -> CGSize {
let availableSize = availableSize.insetBy(padding)
guard availableSize.isPositive else {
return .zero
}
return textLayer.textSize(thatFits: availableSize).insetBy(padding.inverse)
}
open var minimumLineHeight: CGFloat? {
get { return textLayer.minimumLineHeight }
set {
guard newValue != textLayer.minimumLineHeight else {
return
}
textLayer.minimumLineHeight = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open var minimumScaleFactor: CGFloat {
get { return textLayer.minimumScaleFactor }
set {
guard newValue != textLayer.minimumScaleFactor else {
return
}
textLayer.minimumScaleFactor = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open var numberOfLines: Int {
layoutIfNeeded()
return textLayer.numberOfLines
}
open var padding = UIEdgeInsets.zero {
didSet {
guard padding != oldValue else {
return
}
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open var paragraphSpacing: CGFloat {
get { return textLayer.paragraphSpacing }
set {
guard newValue != textLayer.paragraphSpacing else {
return
}
textLayer.paragraphSpacing = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open override func pointInside(_ point: CGPoint, withEvent event: UIEvent?, additionalHitZone: UIEdgeInsets) -> Bool {
let isInsideLabel = super.pointInside(point, withEvent: event, additionalHitZone: additionalHitZone)
guard isInsideLabel || textLayer.contains(layer.convert(point, to: textLayer)) else {
return false
}
guard userInteractionLimitedToLinks else {
return isInsideLabel
}
return link(at: point) != nil
}
public func rect(forLine line: Int, in referenceView: UIView) -> CGRect {
layoutIfNeeded()
return textLayer.rect(forLine: line, in: referenceView.layer)
}
private func setUpLinkTapRecognizer() {
let recognizer = linkTapRecognizer
recognizer.delegate = delegateProxy
recognizer.addTarget(self, action: #selector(handleLinkTapRecognizer))
addGestureRecognizer(recognizer)
}
open var text: String {
get { return attributedText.string }
set { attributedText = NSAttributedString(string: newValue) }
}
open var textColor: UIColor {
get { return textLayer.normalTextColor }
set { textLayer.normalTextColor = newValue }
}
public var textColorDimsWithTint: Bool {
get { return textLayer.textColorDimsWithTint }
set { textLayer.textColorDimsWithTint = newValue }
}
open var textTransform: TextTransform? {
get { return textLayer.textTransform }
set {
guard newValue != textLayer.textTransform else {
return
}
textLayer.textTransform = newValue
invalidateIntrinsicContentSize()
setNeedsLayout()
}
}
open override func tintColorDidChange() {
super.tintColorDidChange()
textLayer.updateTintColor(tintColor, adjustmentMode: tintAdjustmentMode)
}
open var userInteractionLimitedToLinks = true
open var verticalAlignment = TextAlignment.Vertical.center {
didSet {
guard verticalAlignment != oldValue else {
return
}
setNeedsLayout()
}
}
private final class DelegateProxy: NSObject, UIGestureRecognizerDelegate {
private unowned var label: Label
init(label: Label) {
self.label = label
}
@objc
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return label.link(at: touch.location(in: label)) != nil
}
}
}
| 6af800928246ebf9417041110203736d | 19.606436 | 162 | 0.732853 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/ReadingListsFunnel.swift | mit | 3 | // https://meta.wikimedia.org/wiki/Schema:MobileWikiAppiOSReadingLists
@objc final class ReadingListsFunnel: EventLoggingFunnel, EventLoggingStandardEventProviding {
@objc public static let shared = ReadingListsFunnel()
private enum Action: String {
case save
case unsave
case createList = "createlist"
case deleteList = "deletelist"
case readStart = "read_start"
}
private override init() {
super.init(schema: "MobileWikiAppiOSReadingLists", version: 18280648)
}
private func event(category: EventLoggingCategory, label: EventLoggingLabel?, action: Action, measure: Int = 1, measureAge: Int? = nil, measurePosition: Int? = nil) -> Dictionary<String, Any> {
let category = category.rawValue
let action = action.rawValue
var event: [String: Any] = ["category": category, "action": action, "measure": measure, "primary_language": primaryLanguage(), "is_anon": isAnon]
if let label = label?.rawValue {
event["label"] = label
}
if let measurePosition = measurePosition {
event["measure_position"] = measurePosition
}
if let measureAge = measureAge {
event["measure_age"] = measureAge
}
return event
}
override func preprocessData(_ eventData: [AnyHashable: Any]) -> [AnyHashable: Any] {
return wholeEvent(with: eventData)
}
// - MARK: Article
@objc public func logArticleSaveInCurrentArticle(_ articleURL: URL) {
logSave(category: .article, label: .default, articleURL: articleURL)
}
@objc public func logArticleUnsaveInCurrentArticle(_ articleURL: URL) {
logUnsave(category: .article, label: .default, articleURL: articleURL)
}
// - MARK: Read more
@objc public func logArticleSaveInReadMore(_ articleURL: URL) {
logSave(category: .article, label: .readMore, articleURL: articleURL)
}
@objc public func logArticleUnsaveInReadMore(_ articleURL: URL) {
logUnsave(category: .article, label: .readMore, articleURL: articleURL)
}
// - MARK: Feed
@objc public func logSaveInFeed(saveButton: SaveButton?, articleURL: URL, kind: WMFContentGroupKind, index: Int, date: Date) {
logSave(category: .feed, label: saveButton?.eventLoggingLabel ?? .none, articleURL: articleURL, measureAge: daysSince(date), measurePosition: index)
}
@objc public func logUnsaveInFeed(saveButton: SaveButton?, articleURL: URL, kind: WMFContentGroupKind, index: Int, date: Date) {
logUnsave(category: .feed, label: saveButton?.eventLoggingLabel, articleURL: articleURL, measureAge: daysSince(date), measurePosition: index)
}
public func logSaveInFeed(context: FeedFunnelContext?, articleURL: URL, index: Int?) {
logSave(category: .feed, label: context?.label ?? .none, articleURL: articleURL, measureAge: daysSince(context?.midnightUTCDate), measurePosition: index)
}
public func logUnsaveInFeed(context: FeedFunnelContext?, articleURL: URL, index: Int?) {
logUnsave(category: .feed, label: context?.label, articleURL: articleURL, measureAge: daysSince(context?.midnightUTCDate), measurePosition: index)
}
private func daysSince(_ date: Date?) -> Int? {
let now = NSDate().wmf_midnightUTCDateFromLocal
let daysSince = NSCalendar.wmf_gregorian().wmf_days(from: date, to: now)
return daysSince
}
// - MARK: Places
@objc public func logSaveInPlaces(_ articleURL: URL) {
logSave(category: .places, articleURL: articleURL)
}
@objc public func logUnsaveInPlaces(_ articleURL: URL) {
logUnsave(category: .places, articleURL: articleURL)
}
// - MARK: Generic article save & unsave actions
private func logSave(category: EventLoggingCategory, label: EventLoggingLabel? = nil, measure: Int = 1, language: String?, measureAge: Int? = nil, measurePosition: Int? = nil) {
log(event(category: category, label: label, action: .save, measure: measure, measureAge: measureAge, measurePosition: measurePosition), language: language)
}
private func logSave(category: EventLoggingCategory, label: EventLoggingLabel? = nil, measure: Int = 1, articleURL: URL, measureAge: Int? = nil, measurePosition: Int? = nil) {
log(event(category: category, label: label, action: .save, measure: measure, measureAge: measureAge, measurePosition: measurePosition), language: articleURL.wmf_language)
}
@objc public func logSave(category: EventLoggingCategory, label: EventLoggingLabel?, articleURL: URL?) {
log(event(category: category, label: label, action: .save, measure: 1), language: articleURL?.wmf_language)
}
@objc public func logUnsave(category: EventLoggingCategory, label: EventLoggingLabel?, articleURL: URL?) {
log(event(category: category, label: label, action: .unsave, measure: 1), language: articleURL?.wmf_language)
}
private func logUnsave(category: EventLoggingCategory, label: EventLoggingLabel? = nil, measure: Int = 1, language: String?, measureAge: Int? = nil, measurePosition: Int? = nil) {
log(event(category: category, label: label, action: .unsave, measure: measure, measureAge: measureAge, measurePosition: measurePosition), language: language)
}
private func logUnsave(category: EventLoggingCategory, label: EventLoggingLabel? = nil, measure: Int = 1, articleURL: URL, measureAge: Int? = nil, measurePosition: Int? = nil) {
log(event(category: category, label: label, action: .unsave, measure: measure, measureAge: measureAge, measurePosition: measurePosition), language: articleURL.wmf_language)
}
public func logUnsave(category: EventLoggingCategory, label: EventLoggingLabel? = nil, measure: Int = 1, articleURL: URL, date: Date?, measurePosition: Int) {
log(event(category: category, label: label, action: .unsave, measure: measure, measureAge: daysSince(date), measurePosition: measurePosition), language: articleURL.wmf_language)
}
public func logSave(category: EventLoggingCategory, label: EventLoggingLabel? = nil, measure: Int = 1, articleURL: URL, date: Date?, measurePosition: Int) {
log(event(category: category, label: label, action: .save, measure: measure, measureAge: daysSince(date), measurePosition: measurePosition), language: articleURL.wmf_language)
}
// - MARK: Saved - default reading list
public func logUnsaveInReadingList(articlesCount: Int = 1, language: String?) {
logUnsave(category: .saved, label: .items, measure: articlesCount, language: language)
}
public func logReadStartIReadingList(_ articleURL: URL) {
log(event(category: .saved, label: .items, action: .readStart), language: articleURL.wmf_language)
}
// - MARK: Saved - reading lists
public func logDeleteInReadingLists(readingListsCount: Int = 1) {
log(event(category: .saved, label: .lists, action: .deleteList, measure: readingListsCount))
}
public func logCreateInReadingLists() {
log(event(category: .saved, label: .lists, action: .createList))
}
// - MARK: Add articles to reading list
public func logDeleteInAddToReadingList(readingListsCount: Int = 1) {
log(event(category: .addToList, label: nil, action: .deleteList, measure: readingListsCount))
}
public func logCreateInAddToReadingList() {
log(event(category: .addToList, label: nil, action: .createList))
}
}
| 0a5e190ce0d81e5e146dfe33efca35a5 | 48.096154 | 197 | 0.684032 | false | false | false | false |
jengelsma/cis657-summer2016-class-demos | refs/heads/master | Lecture08-PuppyFlixDemo/Lecture08-PuppyFlixDemo/MasterViewController.swift | mit | 1 | //
// MasterViewController.swift
// Lecture08-PuppyFlixDemo
//
// Created by Jonathan Engelsma on 5/31/16.
// Copyright © 2016 Jonathan Engelsma. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
self.loadVideos()
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func refreshVideos(sender: UIRefreshControl) {
sender.endRefreshing()
self.loadVideos()
}
func loadVideos()
{
// Get ready to fetch the list of dog videos from YouTube V3 Data API.
let url = NSURL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=30&q=puppies&type=youtube%23video&key=\(YOUTUBE_API_KEY_GOES_HERE)")
let session = NSURLSession.sharedSession()
let task = session.downloadTaskWithURL(url!) {
(loc:NSURL?, response:NSURLResponse?, error:NSError?) in
if error != nil {
print(error)
return
}
// print out the fetched string for debug purposes.
let d = NSData(contentsOfURL: loc!)!
print("got data")
let datastring = NSString(data: d, encoding: NSUTF8StringEncoding)
print(datastring)
// Parse the top level JSON object.
let parsedObject: AnyObject?
do {
parsedObject = try NSJSONSerialization.JSONObjectWithData(d,
options: NSJSONReadingOptions.AllowFragments)
} catch let error as NSError {
print(error)
return
} catch {
fatalError()
}
// retrieve the individual videos from the JSON document.
if let topLevelObj = parsedObject as? Dictionary<String,AnyObject> {
if let items = topLevelObj["items"] as? Array<Dictionary<String,AnyObject>> {
for i in items {
self.objects.append(i)
}
dispatch_async(dispatch_get_main_queue()) {
(UIApplication.sharedApplication().delegate as! AppDelegate).decrementNetworkActivity()
self.tableView.reloadData()
}
}
}
}
(UIApplication.sharedApplication().delegate as! AppDelegate).incrementNetworkActivity()
task.resume()
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! Dictionary<String,AnyObject>
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// let object = objects[indexPath.row] as! NSDate
// cell.textLabel!.text = object.description
if let object = objects[indexPath.row] as? Dictionary<String, AnyObject> {
if let snippet = object["snippet"] as? Dictionary<String, AnyObject> {
// setup text.
cell.textLabel!.text = snippet["title"] as? String
cell.detailTextLabel!.text = snippet["description"] as? String
// fetch image
cell.imageView?.image = UIImage(named:"YouTubeIcon")
if let images = snippet["thumbnails"] as? Dictionary<String, AnyObject> {
if let firstImage = images["default"] as? Dictionary<String, AnyObject> {
if let imageUrl : String = firstImage["url"] as? String {
cell.imageView?.loadImageFromURL(NSURL(string:imageUrl), placeholderImage: cell.imageView?.image, cachingKey: imageUrl)
}
}
}
}
}
return cell
}
}
| 63ae37e4f901c07e0336f1ca3e99f376 | 35.393548 | 170 | 0.58323 | false | false | false | false |
ingresse/ios-sdk | refs/heads/dev | IngresseSDK/Model/CoverAd.swift | mit | 1 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
public class CoverAd: NSObject, Codable {
public var image: String = ""
public var url: String = ""
enum CodingKeys: String, CodingKey {
case image
case url
}
public required init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return }
image = container.decodeKey(.image, ofType: String.self)
url = container.decodeKey(.url, ofType: String.self)
}
}
| 3b0203bd1c8c09544a16604e3b1b09a4 | 27.315789 | 94 | 0.644981 | false | false | false | false |
redcirclegame/vz-pie-chart | refs/heads/master | Charts/Classes/Data/ChartData.swift | apache-2.0 | 1 | //
// ChartData.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
import UIKit
public class ChartData: NSObject
{
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
internal var _leftAxisMax = Double(0.0)
internal var _leftAxisMin = Double(0.0)
internal var _rightAxisMax = Double(0.0)
internal var _rightAxisMin = Double(0.0)
private var _yValueSum = Double(0.0)
private var _yValCount = Int(0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
/// the average length (in characters) across all x-value strings
private var _xValAverageLength = Double(0.0)
internal var _xVals: [String?]!
internal var _dataSets: [ChartDataSet]!
public override init()
{
super.init();
_xVals = [String?]();
_dataSets = [ChartDataSet]();
}
public init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : xVals;
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets;
self.initialize(_dataSets)
}
public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!);
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets;
self.initialize(_dataSets)
}
public convenience init(xVals: [String?]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]());
}
public convenience init(xVals: [NSObject]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]());
}
public convenience init(xVals: [String?]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]);
}
public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]);
}
internal func initialize(dataSets: [ChartDataSet])
{
checkIsLegal(dataSets);
calcMinMax(start: _lastStart, end: _lastEnd);
calcYValueSum();
calcYValueCount();
calcXValAverageLength()
}
// calculates the average length (in characters) across all x-value strings
internal func calcXValAverageLength()
{
if (_xVals.count == 0)
{
_xValAverageLength = 1;
return;
}
var sum = 1;
for (var i = 0; i < _xVals.count; i++)
{
sum += _xVals[i] == nil ? 0 : count(_xVals[i]!);
}
_xValAverageLength = Double(sum) / Double(_xVals.count);
}
// Checks if the combination of x-values array and DataSet array is legal or not.
// :param: dataSets
internal func checkIsLegal(dataSets: [ChartDataSet]!)
{
if (dataSets == nil)
{
return;
}
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].yVals.count > _xVals.count)
{
println("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.");
return;
}
}
}
public func notifyDataChanged()
{
initialize(_dataSets);
}
/// calc minimum and maximum y value over all datasets
internal func calcMinMax(#start: Int, end: Int)
{
if (_dataSets == nil || _dataSets.count < 1)
{
_yMax = 0.0;
_yMin = 0.0;
}
else
{
_lastStart = start;
_lastEnd = end;
_yMin = DBL_MAX;
_yMax = DBL_MIN;
for (var i = 0; i < _dataSets.count; i++)
{
_dataSets[i].calcMinMax(start: start, end: end);
if (_dataSets[i].yMin < _yMin)
{
_yMin = _dataSets[i].yMin;
}
if (_dataSets[i].yMax > _yMax)
{
_yMax = _dataSets[i].yMax;
}
}
}
}
/// calculates the sum of all y-values in all datasets
internal func calcYValueSum()
{
_yValueSum = 0;
if (_dataSets == nil)
{
return;
}
for (var i = 0; i < _dataSets.count; i++)
{
_yValueSum += fabs(_dataSets[i].yValueSum);
}
}
/// Calculates the total number of y-values across all ChartDataSets the ChartData represents.
internal func calcYValueCount()
{
_yValCount = 0;
if (_dataSets == nil)
{
return;
}
var count = 0;
for (var i = 0; i < _dataSets.count; i++)
{
count += _dataSets[i].entryCount;
}
_yValCount = count;
}
/// returns the number of LineDataSets this object contains
public var dataSetCount: Int
{
if (_dataSets == nil)
{
return 0;
}
return _dataSets.count;
}
/// returns the smallest y-value the data object contains.
public var yMin: Double
{
return _yMin;
}
public func getYMin() -> Double
{
return _yMin;
}
/// returns the greatest y-value the data object contains.
public var yMax: Double
{
return _yMax;
}
public func getYMax() -> Double
{
return _yMax;
}
/// returns the average length (in characters) across all values in the x-vals array
public var xValAverageLength: Double
{
return _xValAverageLength;
}
/// returns the total y-value sum across all DataSet objects the this object represents.
public var yValueSum: Double
{
return _yValueSum;
}
/// Returns the total number of y-values across all DataSet objects the this object represents.
public var yValCount: Int
{
return _yValCount;
}
/// returns the x-values the chart represents
public var xVals: [String?]
{
return _xVals;
}
///Adds a new x-value to the chart data.
public func addXValue(xVal: String?)
{
_xVals.append(xVal);
}
/// Removes the x-value at the specified index.
public func removeXValue(index: Int)
{
_xVals.removeAtIndex(index);
}
/// Returns the array of ChartDataSets this object holds.
public var dataSets: [ChartDataSet]
{
get
{
return _dataSets;
}
set
{
_dataSets = newValue;
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
/// IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.
///
/// :param: dataSets the DataSet array to search
/// :param: type
/// :param: ignorecase if true, the search is not case-sensitive
/// :returns:
internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int
{
if (ignorecase)
{
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue;
}
if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame)
{
return i;
}
}
}
else
{
for (var i = 0; i < dataSets.count; i++)
{
if (label == dataSets[i].label)
{
return i;
}
}
}
return -1;
}
/// returns the total number of x-values this ChartData object represents (the size of the x-values array)
public var xValCount: Int
{
return _xVals.count;
}
/// Returns the labels of all DataSets as a string array.
internal func dataSetLabels() -> [String]
{
var types = [String]();
for (var i = 0; i < _dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue;
}
types[i] = _dataSets[i].label!;
}
return types;
}
/// Get the Entry for a corresponding highlight object
///
/// :param: highlight
/// :returns: the entry that is highlighted
public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry
{
return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex);
}
/// Returns the DataSet object with the given label.
/// sensitive or not.
/// IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.
///
/// :param: label
/// :param: ignorecase
public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet?
{
var index = getDataSetIndexByLabel(label, ignorecase: ignorecase);
if (index < 0 || index >= _dataSets.count)
{
return nil;
}
else
{
return _dataSets[index];
}
}
public func getDataSetByIndex(index: Int) -> ChartDataSet!
{
if (_dataSets == nil || index < 0 || index >= _dataSets.count)
{
return nil;
}
return _dataSets[index];
}
public func addDataSet(d: ChartDataSet!)
{
if (_dataSets == nil)
{
return;
}
_yValCount += d.entryCount;
_yValueSum += d.yValueSum;
if (_dataSets.count == 0)
{
_yMax = d.yMax;
_yMin = d.yMin;
_rightAxisMax = d.yMax;
_rightAxisMin = d.yMin;
}
else
{
if (_yMax < d.yMax)
{
_yMax = d.yMax;
}
if (_yMin > d.yMin)
{
_yMin = d.yMin;
}
if (_rightAxisMax < d.yMax)
{
_rightAxisMax = d.yMax;
}
if (_rightAxisMin > d.yMin)
{
_rightAxisMin = d.yMin;
}
}
_dataSets.append(d);
}
public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?)
{
// in case there is only one axis, adjust the second axis
if (firstLeft === nil)
{
_leftAxisMax = _rightAxisMax;
_leftAxisMin = _rightAxisMin;
}
else if (firstRight === nil)
{
_rightAxisMax = _leftAxisMax;
_rightAxisMin = _leftAxisMin;
}
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// :returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSet(dataSet: ChartDataSet!) -> Bool
{
if (_dataSets == nil || dataSet === nil)
{
return false;
}
var removed = false;
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return removeDataSetByIndex(i);
}
}
return false;
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// :returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSetByIndex(index: Int) -> Bool
{
if (_dataSets == nil || index >= _dataSets.count || index < 0)
{
return false;
}
var d = _dataSets.removeAtIndex(index);
_yValCount -= d.entryCount;
_yValueSum -= d.yValueSum;
calcMinMax(start: _lastStart, end: _lastEnd);
return true;
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
public func addEntry(e: ChartDataEntry, dataSetIndex: Int)
{
if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0)
{
var val = e.value;
_yValCount += 1;
_yValueSum += val;
if (_yMax < val)
{
_yMax = val;
}
if (_yMin > val)
{
_yMin = val;
}
var set = _dataSets[dataSetIndex];
if (_rightAxisMax < e.value)
{
_rightAxisMax = e.value;
}
if (_rightAxisMin > e.value)
{
_rightAxisMin = e.value;
}
set.addEntry(e);
}
else
{
println("ChartData.addEntry() - dataSetIndex our of range.");
}
}
/// Removes the given Entry object from the DataSet at the specified index.
public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool
{
// entry null, outofbounds
if (entry === nil || dataSetIndex >= _dataSets.count)
{
return false;
}
// remove the entry from the dataset
var removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex);
if (removed)
{
var val = entry.value;
_yValCount -= 1;
_yValueSum -= val;
calcMinMax(start: _lastStart, end: _lastEnd);
}
return removed;
}
/// Removes the Entry object at the given xIndex from the ChartDataSet at the
/// specified index. Returns true if an entry was removed, false if no Entry
/// was found that meets the specified requirements.
public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool
{
if (dataSetIndex >= _dataSets.count)
{
return false;
}
var entry = _dataSets[dataSetIndex].entryForXIndex(xIndex);
return removeEntry(entry, dataSetIndex: dataSetIndex);
}
/// Returns the DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet?
{
if (e == nil)
{
return nil;
}
for (var i = 0; i < _dataSets.count; i++)
{
var set = _dataSets[i];
for (var j = 0; j < set.entryCount; j++)
{
if (e === set.entryForXIndex(e.xIndex))
{
return set;
}
}
}
return nil;
}
/// Returns the index of the provided DataSet inside the DataSets array of
/// this data object. Returns -1 if the DataSet was not found.
public func indexOfDataSet(dataSet: ChartDataSet) -> Int
{
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return i;
}
}
return -1;
}
/// Returns all colors used across all DataSet objects this object represents.
public func getColors() -> [UIColor]?
{
if (_dataSets == nil)
{
return nil;
}
var clrcnt = 0;
for (var i = 0; i < _dataSets.count; i++)
{
clrcnt += _dataSets[i].colors.count;
}
var colors = [UIColor]();
for (var i = 0; i < _dataSets.count; i++)
{
var clrs = _dataSets[i].colors;
for clr in clrs
{
colors.append(clr);
}
}
return colors;
}
/// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience.
public func generateXVals(from: Int, to: Int) -> [String]
{
var xvals = [String]();
for (var i = from; i < to; i++)
{
xvals.append(String(i));
}
return xvals;
}
/// Sets a custom ValueFormatter for all DataSets this data object contains.
public func setValueFormatter(formatter: NSNumberFormatter!)
{
for set in dataSets
{
set.valueFormatter = formatter;
}
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
public func setValueTextColor(color: UIColor!)
{
for set in dataSets
{
set.valueTextColor = color ?? set.valueTextColor;
}
}
/// Sets the font for all value-labels for all DataSets this data object contains.
public func setValueFont(font: UIFont!)
{
for set in dataSets
{
set.valueFont = font ?? set.valueFont;
}
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
public func setDrawValues(enabled: Bool)
{
for set in dataSets
{
set.drawValuesEnabled = enabled;
}
}
/// Enables / disables highlighting values for all DataSets this data object contains.
public var highlightEnabled: Bool
{
get
{
for set in dataSets
{
if (!set.highlightEnabled)
{
return false;
}
}
return true;
}
set
{
for set in dataSets
{
set.highlightEnabled = newValue;
}
}
}
/// if true, value highlightning is enabled
public var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
public func clearValues()
{
dataSets.removeAll(keepCapacity: false);
notifyDataChanged();
}
/// Checks if this data object contains the specified Entry. Returns true if so, false if not.
public func contains(#entry: ChartDataEntry) -> Bool
{
for set in dataSets
{
if (set.contains(entry))
{
return true;
}
}
return false;
}
/// Checks if this data object contains the specified DataSet. Returns true if so, false if not.
public func contains(#dataSet: ChartDataSet) -> Bool
{
for set in dataSets
{
if (set.isEqual(dataSet))
{
return true;
}
}
return false;
}
/// MARK: - ObjC compatibility
/// returns the average length (in characters) across all values in the x-vals array
public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); }
}
| a60c2f101288035611505af788098279 | 25.500659 | 128 | 0.502884 | false | false | false | false |
SuperJerry/Swift | refs/heads/master | triangle.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
//var str = "Hello, playground"
//for index in 0...100{
// var result = sin(CGFloat(index))
//
//}
for var i: Double = 0; i < 50; i += 0.1{
var result1 = sin(i)
var result2 = sin(2 * i)
var result3 = sin(3 * i)
var result4 = result1 + result2 + result3
} | 7b227aa5d2e5fd1c3d0f36cbc3907603 | 22.066667 | 52 | 0.588406 | false | false | false | false |
steelwheels/Amber | refs/heads/master | Test/AmberParser/main.swift | gpl-2.0 | 1 | /**
* @file main.swift
* @brief Main function for AmberParser
* @par Copyright
* Copyright (C) 2020-2022 Steel Wheels Project
*/
import Amber
import CoconutData
import KiwiEngine
import JavaScriptCore
import Foundation
let console = CNFileConsole()
public func main() -> Int
{
if let infile = parseCommandLine() {
guard let source = infile.loadContents() as String? else {
console.error(string: "[Error] Failed to read from \(infile.path)\n")
return -1
}
console.print(string: "[SOURCE] \(source)\n")
let frame: AMBFrame
let parser = AMBParser()
switch parser.parse(source: source, sourceFile: infile){
case .success(let val):
if let frm = val as? AMBFrame {
let txt = frm.toScript().toStrings().joined(separator: "\n")
console.print(string: "[FRAME] \(txt)\n")
frame = frm
} else {
console.error(string: "Frame is required but it is not given.")
return -1
}
case .failure(let err):
console.error(string: "[Error] \(err.toString())\n")
return -1
}
let compiler = AMBFrameCompiler()
let mapper = AMBComponentMapper()
let context = KEContext(virtualMachine: JSVirtualMachine())
let manager = CNProcessManager()
let packdir = URL(fileURLWithPath: "../Test/AmberParser/Resource", isDirectory: true)
let resource = KEResource(packageDirectory: packdir)
let environ = CNEnvironment()
let config = KEConfig(applicationType: .terminal, doStrict: true, logLevel: .detail)
switch compiler.compile(frame: frame, mapper: mapper, context: context, processManager: manager, resource: resource, environment: environ, config: config, console: console) {
case .success(let comp):
let txt = comp.toText().toStrings().joined(separator: "\n")
console.print(string: "[COMPONENT] \(txt)\n")
case .failure(let err):
console.error(string: "[Error] \(err.toString())")
}
return 0
} else {
return -1
}
}
private func parseCommandLine() -> URL?
{
let args = CommandLine.arguments
if args.count == 2 {
return URL(fileURLWithPath: args[1])
} else {
print("[Error] Invalid parameter")
usage()
return nil
}
}
private func usage()
{
print("usage: ambparser <amber-source-file>")
}
private class Dummy
{
}
let _ = main()
/*
CNPreference.shared.systemPreference.logLevel = .detail
let res1 = UTCompiler(console: cons)
let res2 = UTComponent(console: cons)
let result = res1 && res2
if result {
cons.print(string: "SUMMARY: OK\n")
} else {
cons.print(string: "SUMMARY: NG\n")
}
*/
| 13cce326a03ad687ec91ece296dc0c45 | 23.653465 | 176 | 0.685944 | false | false | false | false |
airbnb/lottie-ios | refs/heads/master | Sources/Public/Animation/LottieAnimationView.swift | apache-2.0 | 2 | //
// LottieAnimationView.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/23/19.
//
import Foundation
import QuartzCore
// MARK: - LottieBackgroundBehavior
/// Describes the behavior of an AnimationView when the app is moved to the background.
public enum LottieBackgroundBehavior {
/// Stop the animation and reset it to the beginning of its current play time. The completion block is called.
case stop
/// Pause the animation in its current state. The completion block is called.
case pause
/// Pause the animation and restart it when the application moves to the foreground.
/// The completion block is stored and called when the animation completes.
/// - This is the default when using the Main Thread rendering engine.
case pauseAndRestore
/// Stops the animation and sets it to the end of its current play time. The completion block is called.
case forceFinish
/// The animation continues playing in the background.
/// - This is the default when using the Core Animation rendering engine.
/// Playing an animation using the Core Animation engine doesn't come with any CPU overhead,
/// so using `.continuePlaying` avoids the need to stop and then resume the animation
/// (which does come with some CPU overhead).
/// - This mode should not be used with the Main Thread rendering engine.
case continuePlaying
// MARK: Public
/// The default background behavior, based on the rendering engine being used to play the animation.
/// - Playing an animation using the Main Thread rendering engine comes with CPU overhead,
/// so the animation should be paused or stopped when the `LottieAnimationView` is not visible.
/// - Playing an animation using the Core Animation rendering engine does not come with any
/// CPU overhead, so these animations do not need to be paused in the background.
public static func `default`(for renderingEngine: RenderingEngine) -> LottieBackgroundBehavior {
switch renderingEngine {
case .mainThread:
return .pauseAndRestore
case .coreAnimation:
return .continuePlaying
}
}
}
// MARK: - LottieLoopMode
/// Defines animation loop behavior
public enum LottieLoopMode {
/// Animation is played once then stops.
case playOnce
/// Animation will loop from beginning to end until stopped.
case loop
/// Animation will play forward, then backwards and loop until stopped.
case autoReverse
/// Animation will loop from beginning to end up to defined amount of times.
case `repeat`(Float)
/// Animation will play forward, then backwards a defined amount of times.
case repeatBackwards(Float)
}
// MARK: Equatable
extension LottieLoopMode: Equatable {
public static func == (lhs: LottieLoopMode, rhs: LottieLoopMode) -> Bool {
switch (lhs, rhs) {
case (.repeat(let lhsAmount), .repeat(let rhsAmount)),
(.repeatBackwards(let lhsAmount), .repeatBackwards(let rhsAmount)):
return lhsAmount == rhsAmount
case (.playOnce, .playOnce),
(.loop, .loop),
(.autoReverse, .autoReverse):
return true
default:
return false
}
}
}
// MARK: - LottieAnimationView
@IBDesignable
final public class LottieAnimationView: LottieAnimationViewBase {
// MARK: Lifecycle
// MARK: - Public (Initializers)
/// Initializes an AnimationView with an animation.
public init(
animation: LottieAnimation?,
imageProvider: AnimationImageProvider? = nil,
textProvider: AnimationTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
self.animation = animation
self.imageProvider = imageProvider ?? BundleImageProvider(bundle: Bundle.main, searchPath: nil)
self.textProvider = textProvider
self.fontProvider = fontProvider
self.configuration = configuration
self.logger = logger
super.init(frame: .zero)
commonInit()
makeAnimationLayer(usingEngine: configuration.renderingEngine)
if let animation = animation {
frame = animation.bounds
}
}
/// Initializes an AnimationView with a .lottie file.
public init(
dotLottie: DotLottieFile?,
animationId: String? = nil,
textProvider: AnimationTextProvider = DefaultTextProvider(),
fontProvider: AnimationFontProvider = DefaultFontProvider(),
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
let dotLottieAnimation = dotLottie?.animation(for: animationId)
animation = dotLottieAnimation?.animation
imageProvider = dotLottie?.imageProvider ?? BundleImageProvider(bundle: Bundle.main, searchPath: nil)
self.textProvider = textProvider
self.fontProvider = fontProvider
self.configuration = configuration
self.logger = logger
super.init(frame: .zero)
commonInit()
loopMode = dotLottieAnimation?.configuration.loopMode ?? .playOnce
animationSpeed = CGFloat(dotLottieAnimation?.configuration.speed ?? 1)
makeAnimationLayer(usingEngine: configuration.renderingEngine)
if let animation = animation {
frame = animation.bounds
}
}
public init(
configuration: LottieConfiguration = .shared,
logger: LottieLogger = .shared)
{
animation = nil
imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil)
textProvider = DefaultTextProvider()
fontProvider = DefaultFontProvider()
self.configuration = configuration
self.logger = logger
super.init(frame: .zero)
commonInit()
}
public override init(frame: CGRect) {
animation = nil
imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil)
textProvider = DefaultTextProvider()
fontProvider = DefaultFontProvider()
configuration = .shared
logger = .shared
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
imageProvider = BundleImageProvider(bundle: Bundle.main, searchPath: nil)
textProvider = DefaultTextProvider()
fontProvider = DefaultFontProvider()
configuration = .shared
logger = .shared
super.init(coder: aDecoder)
commonInit()
}
// MARK: Public
/// The configuration that this `LottieAnimationView` uses when playing its animation
public let configuration: LottieConfiguration
/// Value Providers that have been registered using `setValueProvider(_:keypath:)`
public private(set) var valueProviders = [AnimationKeypath: AnyValueProvider]()
/// Describes the behavior of an AnimationView when the app is moved to the background.
///
/// The default for the Main Thread animation engine is `pause`,
/// which pauses the animation when the application moves to
/// the background. This prevents the animation from consuming CPU
/// resources when not on-screen. The completion block is called with
/// `false` for completed.
///
/// The default for the Core Animation engine is `continuePlaying`,
/// since the Core Animation engine does not have any CPU overhead.
public var backgroundBehavior: LottieBackgroundBehavior {
get {
let currentBackgroundBehavior = _backgroundBehavior ?? .default(for: currentRenderingEngine ?? .mainThread)
if
currentRenderingEngine == .mainThread,
_backgroundBehavior == .continuePlaying
{
logger.assertionFailure("""
`LottieBackgroundBehavior.continuePlaying` should not be used with the Main Thread
rendering engine, since this would waste CPU resources on playing an animation
that is not visible. Consider using a different background mode, or switching to
the Core Animation rendering engine (which does not have any CPU overhead).
""")
}
return currentBackgroundBehavior
}
set {
_backgroundBehavior = newValue
}
}
/// Sets the animation backing the animation view. Setting this will clear the
/// view's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
public var animation: LottieAnimation? {
didSet {
makeAnimationLayer(usingEngine: configuration.renderingEngine)
}
}
/// Sets the image provider for the animation view. An image provider provides the
/// animation with its required image data.
///
/// Setting this will cause the animation to reload its image contents.
public var imageProvider: AnimationImageProvider {
didSet {
animationLayer?.imageProvider = imageProvider.cachedImageProvider
reloadImages()
}
}
/// Sets the text provider for animation view. A text provider provides the
/// animation with values for text layers
public var textProvider: AnimationTextProvider {
didSet {
animationLayer?.textProvider = textProvider
}
}
/// Sets the text provider for animation view. A text provider provides the
/// animation with values for text layers
public var fontProvider: AnimationFontProvider {
didSet {
animationLayer?.fontProvider = fontProvider
}
}
/// Returns `true` if the animation is currently playing.
public var isAnimationPlaying: Bool {
guard let animationLayer = animationLayer else {
return false
}
if let valueFromLayer = animationLayer.isAnimationPlaying {
return valueFromLayer
} else {
return animationLayer.animation(forKey: activeAnimationName) != nil
}
}
/// Returns `true` if the animation will start playing when this view is added to a window.
public var isAnimationQueued: Bool {
animationContext != nil && waitingToPlayAnimation
}
/// Sets the loop behavior for `play` calls. Defaults to `playOnce`
public var loopMode: LottieLoopMode = .playOnce {
didSet {
updateInFlightAnimation()
}
}
/// When `true` the animation view will rasterize its contents when not animating.
/// Rasterizing will improve performance of static animations.
///
/// Note: this will not produce crisp results at resolutions above the animations natural resolution.
///
/// Defaults to `false`
public var shouldRasterizeWhenIdle = false {
didSet {
updateRasterizationState()
}
}
/// Sets the current animation time with a Progress Time
///
/// Note: Setting this will stop the current animation, if any.
/// Note 2: If `animation` is nil, setting this will fallback to 0
public var currentProgress: AnimationProgressTime {
set {
if let animation = animation {
currentFrame = animation.frameTime(forProgress: newValue)
} else {
currentFrame = 0
}
}
get {
if let animation = animation {
return animation.progressTime(forFrame: currentFrame)
} else {
return 0
}
}
}
/// Sets the current animation time with a time in seconds.
///
/// Note: Setting this will stop the current animation, if any.
/// Note 2: If `animation` is nil, setting this will fallback to 0
public var currentTime: TimeInterval {
set {
if let animation = animation {
currentFrame = animation.frameTime(forTime: newValue)
} else {
currentFrame = 0
}
}
get {
if let animation = animation {
return animation.time(forFrame: currentFrame)
} else {
return 0
}
}
}
/// Sets the current animation time with a frame in the animations framerate.
///
/// Note: Setting this will stop the current animation, if any.
public var currentFrame: AnimationFrameTime {
set {
removeCurrentAnimationIfNecessary()
updateAnimationFrame(newValue)
}
get {
animationLayer?.currentFrame ?? 0
}
}
/// Returns the current animation frame while an animation is playing.
public var realtimeAnimationFrame: AnimationFrameTime {
isAnimationPlaying ? animationLayer?.presentation()?.currentFrame ?? currentFrame : currentFrame
}
/// Returns the current animation frame while an animation is playing.
public var realtimeAnimationProgress: AnimationProgressTime {
if let animation = animation {
return animation.progressTime(forFrame: realtimeAnimationFrame)
}
return 0
}
/// Sets the speed of the animation playback. Defaults to 1
public var animationSpeed: CGFloat = 1 {
didSet {
updateInFlightAnimation()
}
}
/// When `true` the animation will play back at the framerate encoded in the
/// `LottieAnimation` model. When `false` the animation will play at the framerate
/// of the device.
///
/// Defaults to false
public var respectAnimationFrameRate = false {
didSet {
animationLayer?.respectAnimationFrameRate = respectAnimationFrameRate
}
}
/// Controls the cropping of an Animation. Setting this property will crop the animation
/// to the current views bounds by the viewport frame. The coordinate space is specified
/// in the animation's coordinate space.
///
/// Animatable.
public var viewportFrame: CGRect? = nil {
didSet {
// This is really ugly, but is needed to trigger a layout pass within an animation block.
// Typically this happens automatically, when layout objects are UIView based.
// The animation layer is a CALayer which will not implicitly grab the animation
// duration of a UIView animation block.
//
// By setting bounds and then resetting bounds the UIView animation block's
// duration and curve are captured and added to the layer. This is used in the
// layout block to animate the animationLayer's position and size.
let rect = bounds
self.bounds = CGRect.zero
self.bounds = rect
self.setNeedsLayout()
}
}
override public var intrinsicContentSize: CGSize {
if let animation = animation {
return animation.bounds.size
}
return .zero
}
/// The rendering engine currently being used by this view.
/// - This will only be `nil` in cases where the configuration is `automatic`
/// but a `RootAnimationLayer` hasn't been constructed yet
public var currentRenderingEngine: RenderingEngine? {
switch configuration.renderingEngine {
case .specific(let engine):
return engine
case .automatic:
guard let animationLayer = animationLayer else {
return nil
}
if animationLayer is CoreAnimationLayer {
return .coreAnimation
} else {
return .mainThread
}
}
}
/// Sets the lottie file backing the animation view. Setting this will clear the
/// view's contents, completion blocks and current state. The new animation will
/// be loaded up and set to the beginning of its timeline.
/// The loopMode, animationSpeed and imageProvider will be set according
/// to lottie file settings
/// - Parameters:
/// - animationId: Internal animation id to play. Optional
/// Defaults to play first animation in file.
/// - dotLottieFile: Lottie file to play
public func loadAnimation(
_ animationId: String? = nil,
from dotLottieFile: DotLottieFile)
{
guard let dotLottieAnimation = dotLottieFile.animation(for: animationId) else { return }
loopMode = dotLottieAnimation.configuration.loopMode
animationSpeed = CGFloat(dotLottieAnimation.configuration.speed)
if let imageProvider = dotLottieAnimation.configuration.imageProvider {
self.imageProvider = imageProvider
}
animation = dotLottieAnimation.animation
}
/// Plays the animation from its current state to the end.
///
/// - Parameter completion: An optional completion closure to be called when the animation completes playing.
public func play(completion: LottieCompletionBlock? = nil) {
guard let animation = animation else {
return
}
/// Build a context for the animation.
let context = AnimationContext(
playFrom: CGFloat(animation.startFrame),
playTo: CGFloat(animation.endFrame),
closure: completion)
removeCurrentAnimationIfNecessary()
addNewAnimationForContext(context)
}
/// Plays the animation from a progress (0-1) to a progress (0-1).
///
/// - Parameter fromProgress: The start progress of the animation. If `nil` the animation will start at the current progress.
/// - Parameter toProgress: The end progress of the animation.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
public func play(
fromProgress: AnimationProgressTime? = nil,
toProgress: AnimationProgressTime,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
guard let animation = animation else {
return
}
removeCurrentAnimationIfNecessary()
if let loopMode = loopMode {
/// Set the loop mode, if one was supplied
self.loopMode = loopMode
}
let context = AnimationContext(
playFrom: animation.frameTime(forProgress: fromProgress ?? currentProgress),
playTo: animation.frameTime(forProgress: toProgress),
closure: completion)
addNewAnimationForContext(context)
}
/// Plays the animation from a start frame to an end frame in the animation's framerate.
///
/// - Parameter fromFrame: The start frame of the animation. If `nil` the animation will start at the current frame.
/// - Parameter toFrame: The end frame of the animation.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
public func play(
fromFrame: AnimationFrameTime? = nil,
toFrame: AnimationFrameTime,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
removeCurrentAnimationIfNecessary()
if let loopMode = loopMode {
/// Set the loop mode, if one was supplied
self.loopMode = loopMode
}
let context = AnimationContext(
playFrom: fromFrame ?? currentFrame,
playTo: toFrame,
closure: completion)
addNewAnimationForContext(context)
}
/// Plays the animation from a named marker to another marker.
///
/// Markers are point in time that are encoded into the Animation data and assigned
/// a name.
///
/// NOTE: If markers are not found the play command will exit.
///
/// - Parameter fromMarker: The start marker for the animation playback. If `nil` the
/// animation will start at the current progress.
/// - Parameter toMarker: The end marker for the animation playback.
/// - Parameter playEndMarkerFrame: A flag to determine whether or not to play the frame of the end marker. If the
/// end marker represents the end of the section to play, it should be to true. If the provided end marker
/// represents the beginning of the next section, it should be false.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
public func play(
fromMarker: String? = nil,
toMarker: String,
playEndMarkerFrame: Bool = true,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
guard let animation = animation, let markers = animation.markerMap, let to = markers[toMarker] else {
return
}
removeCurrentAnimationIfNecessary()
if let loopMode = loopMode {
/// Set the loop mode, if one was supplied
self.loopMode = loopMode
}
let fromTime: CGFloat
if let fromName = fromMarker, let from = markers[fromName] {
fromTime = CGFloat(from.frameTime)
} else {
fromTime = currentFrame
}
let playTo = playEndMarkerFrame ? CGFloat(to.frameTime) : CGFloat(to.frameTime) - 1
let context = AnimationContext(
playFrom: fromTime,
playTo: playTo,
closure: completion)
addNewAnimationForContext(context)
}
/// Plays the animation from a named marker to the end of the marker's duration.
///
/// A marker is a point in time with an associated duration that is encoded into the
/// animation data and assigned a name.
///
/// NOTE: If marker is not found the play command will exit.
///
/// - Parameter marker: The start marker for the animation playback.
/// - Parameter loopMode: The loop behavior of the animation. If `nil` the view's `loopMode` property will be used.
/// - Parameter completion: An optional completion closure to be called when the animation stops.
public func play(
marker: String,
loopMode: LottieLoopMode? = nil,
completion: LottieCompletionBlock? = nil)
{
guard let from = animation?.markerMap?[marker] else {
return
}
play(
fromFrame: from.frameTime,
toFrame: from.frameTime + from.durationFrameTime,
loopMode: loopMode,
completion: completion)
}
/// Stops the animation and resets the view to its start frame.
///
/// The completion closure will be called with `false`
public func stop() {
removeCurrentAnimation()
currentFrame = 0
}
/// Pauses the animation in its current state.
///
/// The completion closure will be called with `false`
public func pause() {
removeCurrentAnimation()
}
/// Reloads the images supplied to the animation from the `imageProvider`
public func reloadImages() {
animationLayer?.reloadImages()
}
/// Forces the LottieAnimationView to redraw its contents.
public func forceDisplayUpdate() {
animationLayer?.forceDisplayUpdate()
}
/// Sets a ValueProvider for the specified keypath. The value provider will be set
/// on all properties that match the keypath.
///
/// Nearly all properties of a Lottie animation can be changed at runtime using a
/// combination of `Animation Keypaths` and `Value Providers`.
/// Setting a ValueProvider on a keypath will cause the animation to update its
/// contents and read the new Value Provider.
///
/// A value provider provides a typed value on a frame by frame basis.
///
/// - Parameter valueProvider: The new value provider for the properties.
/// - Parameter keypath: The keypath used to search for properties.
///
/// Example:
/// ```
/// /// A keypath that finds the color value for all `Fill 1` nodes.
/// let fillKeypath = AnimationKeypath(keypath: "**.Fill 1.Color")
/// /// A Color Value provider that returns a reddish color.
/// let redValueProvider = ColorValueProvider(Color(r: 1, g: 0.2, b: 0.3, a: 1))
/// /// Set the provider on the animationView.
/// animationView.setValueProvider(redValueProvider, keypath: fillKeypath)
/// ```
public func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
guard let animationLayer = animationLayer else { return }
valueProviders[keypath] = valueProvider
animationLayer.setValueProvider(valueProvider, keypath: keypath)
}
/// Reads the value of a property specified by the Keypath.
/// Returns nil if no property is found.
///
/// - Parameter for: The keypath used to search for the property.
/// - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used.
public func getValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
animationLayer?.getValue(for: keypath, atFrame: atFrame)
}
/// Reads the original value of a property specified by the Keypath.
/// This will ignore any value providers and can be useful when implementing a value providers that makes change to the original value from the animation.
/// Returns nil if no property is found.
///
/// - Parameter for: The keypath used to search for the property.
/// - Parameter atFrame: The Frame Time of the value to query. If nil then the current frame is used.
public func getOriginalValue(for keypath: AnimationKeypath, atFrame: AnimationFrameTime?) -> Any? {
animationLayer?.getOriginalValue(for: keypath, atFrame: atFrame)
}
/// Logs all child keypaths.
public func logHierarchyKeypaths() {
animationLayer?.logHierarchyKeypaths()
}
/// Searches for the nearest child layer to the first Keypath and adds the subview
/// to that layer. The subview will move and animate with the child layer.
/// Furthermore the subview will be in the child layers coordinate space.
///
/// Note: if no layer is found for the keypath, then nothing happens.
///
/// - Parameter subview: The subview to add to the found animation layer.
/// - Parameter keypath: The keypath used to find the animation layer.
///
/// Example:
/// ```
/// /// A keypath that finds `Layer 1`
/// let layerKeypath = AnimationKeypath(keypath: "Layer 1")
///
/// /// Wrap the custom view in an `AnimationSubview`
/// let subview = AnimationSubview()
/// subview.addSubview(customView)
///
/// /// Set the provider on the animationView.
/// animationView.addSubview(subview, forLayerAt: layerKeypath)
/// ```
public func addSubview(_ subview: AnimationSubview, forLayerAt keypath: AnimationKeypath) {
guard let sublayer = animationLayer?.layer(for: keypath) else {
return
}
setNeedsLayout()
layoutIfNeeded()
forceDisplayUpdate()
addSubview(subview)
if let subViewLayer = subview.viewLayer {
sublayer.addSublayer(subViewLayer)
}
}
/// Converts a CGRect from the LottieAnimationView's coordinate space into the
/// coordinate space of the layer found at Keypath.
///
/// If no layer is found, nil is returned
///
/// - Parameter rect: The CGRect to convert.
/// - Parameter toLayerAt: The keypath used to find the layer.
public func convert(_ rect: CGRect, toLayerAt keypath: AnimationKeypath?) -> CGRect? {
guard let animationLayer = animationLayer else { return nil }
guard let keypath = keypath else {
return viewLayer?.convert(rect, to: animationLayer)
}
guard let sublayer = animationLayer.layer(for: keypath) else {
return nil
}
setNeedsLayout()
layoutIfNeeded()
forceDisplayUpdate()
return animationLayer.convert(rect, to: sublayer)
}
/// Converts a CGPoint from the LottieAnimationView's coordinate space into the
/// coordinate space of the layer found at Keypath.
///
/// If no layer is found, nil is returned
///
/// - Parameter point: The CGPoint to convert.
/// - Parameter toLayerAt: The keypath used to find the layer.
public func convert(_ point: CGPoint, toLayerAt keypath: AnimationKeypath?) -> CGPoint? {
guard let animationLayer = animationLayer else { return nil }
guard let keypath = keypath else {
return viewLayer?.convert(point, to: animationLayer)
}
guard let sublayer = animationLayer.layer(for: keypath) else {
return nil
}
setNeedsLayout()
layoutIfNeeded()
forceDisplayUpdate()
return animationLayer.convert(point, to: sublayer)
}
/// Sets the enabled state of all animator nodes found with the keypath search.
/// This can be used to interactively enable / disable parts of the animation.
///
/// - Parameter isEnabled: When true the animator nodes affect the rendering tree. When false the node is removed from the tree.
/// - Parameter keypath: The keypath used to find the node(s).
public func setNodeIsEnabled(isEnabled: Bool, keypath: AnimationKeypath) {
guard let animationLayer = animationLayer else { return }
let nodes = animationLayer.animatorNodes(for: keypath)
if let nodes = nodes {
for node in nodes {
node.isEnabled = isEnabled
}
forceDisplayUpdate()
}
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Progress Time for the marker named. Returns nil if no marker found.
public func progressTime(forMarker named: String) -> AnimationProgressTime? {
guard let animation = animation else {
return nil
}
return animation.progressTime(forMarker: named)
}
/// Markers are a way to describe a point in time by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// Returns the Frame Time for the marker named. Returns nil if no marker found.
public func frameTime(forMarker named: String) -> AnimationFrameTime? {
guard let animation = animation else {
return nil
}
return animation.frameTime(forMarker: named)
}
/// Markers are a way to describe a point in time and a duration by a key name.
///
/// Markers are encoded into animation JSON. By using markers a designer can mark
/// playback points for a developer to use without having to worry about keeping
/// track of animation frames. If the animation file is updated, the developer
/// does not need to update playback code.
///
/// - Returns: The duration frame time for the marker, or `nil` if no marker found.
public func durationFrameTime(forMarker named: String) -> AnimationFrameTime? {
guard let animation = animation else {
return nil
}
return animation.durationFrameTime(forMarker: named)
}
// MARK: Internal
var animationLayer: RootAnimationLayer? = nil
/// Set animation name from Interface Builder
@IBInspectable var animationName: String? {
didSet {
self.animation = animationName.flatMap {
LottieAnimation.named($0, animationCache: nil)
}
}
}
override func layoutAnimation() {
guard let animation = animation, let animationLayer = animationLayer else { return }
var position = animation.bounds.center
let xform: CATransform3D
var shouldForceUpdates = false
if let viewportFrame = viewportFrame {
shouldForceUpdates = contentMode == .redraw
let compAspect = viewportFrame.size.width / viewportFrame.size.height
let viewAspect = bounds.size.width / bounds.size.height
let dominantDimension = compAspect > viewAspect ? bounds.size.width : bounds.size.height
let compDimension = compAspect > viewAspect ? viewportFrame.size.width : viewportFrame.size.height
let scale = dominantDimension / compDimension
let viewportOffset = animation.bounds.center - viewportFrame.center
xform = CATransform3DTranslate(CATransform3DMakeScale(scale, scale, 1), viewportOffset.x, viewportOffset.y, 0)
position = bounds.center
} else {
switch contentMode {
case .scaleToFill:
position = bounds.center
xform = CATransform3DMakeScale(
bounds.size.width / animation.size.width,
bounds.size.height / animation.size.height,
1);
case .scaleAspectFit:
position = bounds.center
let compAspect = animation.size.width / animation.size.height
let viewAspect = bounds.size.width / bounds.size.height
let dominantDimension = compAspect > viewAspect ? bounds.size.width : bounds.size.height
let compDimension = compAspect > viewAspect ? animation.size.width : animation.size.height
let scale = dominantDimension / compDimension
xform = CATransform3DMakeScale(scale, scale, 1)
case .scaleAspectFill:
position = bounds.center
let compAspect = animation.size.width / animation.size.height
let viewAspect = bounds.size.width / bounds.size.height
let scaleWidth = compAspect < viewAspect
let dominantDimension = scaleWidth ? bounds.size.width : bounds.size.height
let compDimension = scaleWidth ? animation.size.width : animation.size.height
let scale = dominantDimension / compDimension
xform = CATransform3DMakeScale(scale, scale, 1)
case .redraw:
shouldForceUpdates = true
xform = CATransform3DIdentity
case .center:
position = bounds.center
xform = CATransform3DIdentity
case .top:
position.x = bounds.center.x
xform = CATransform3DIdentity
case .bottom:
position.x = bounds.center.x
position.y = bounds.maxY - animation.bounds.midY
xform = CATransform3DIdentity
case .left:
position.y = bounds.center.y
xform = CATransform3DIdentity
case .right:
position.y = bounds.center.y
position.x = bounds.maxX - animation.bounds.midX
xform = CATransform3DIdentity
case .topLeft:
xform = CATransform3DIdentity
case .topRight:
position.x = bounds.maxX - animation.bounds.midX
xform = CATransform3DIdentity
case .bottomLeft:
position.y = bounds.maxY - animation.bounds.midY
xform = CATransform3DIdentity
case .bottomRight:
position.x = bounds.maxX - animation.bounds.midX
position.y = bounds.maxY - animation.bounds.midY
xform = CATransform3DIdentity
#if os(iOS) || os(tvOS)
@unknown default:
logger.assertionFailure("unsupported contentMode: \(contentMode.rawValue)")
xform = CATransform3DIdentity
#endif
}
}
// UIView Animation does not implicitly set CAAnimation time or timing fuctions.
// If layout is changed in an animation we must get the current animation duration
// and timing function and then manually create a CAAnimation to match the UIView animation.
// If layout is changed without animation, explicitly set animation duration to 0.0
// inside CATransaction to avoid unwanted artifacts.
/// Check if any animation exist on the view's layer, and match it.
if let key = viewLayer?.animationKeys()?.first, let animation = viewLayer?.animation(forKey: key) {
// The layout is happening within an animation block. Grab the animation data.
let positionKey = "LayoutPositionAnimation"
let transformKey = "LayoutTransformAnimation"
animationLayer.removeAnimation(forKey: positionKey)
animationLayer.removeAnimation(forKey: transformKey)
let positionAnimation = animation.copy() as? CABasicAnimation ?? CABasicAnimation(keyPath: "position")
positionAnimation.keyPath = "position"
positionAnimation.isAdditive = false
positionAnimation.fromValue = (animationLayer.presentation() ?? animationLayer).position
positionAnimation.toValue = position
positionAnimation.isRemovedOnCompletion = true
let xformAnimation = animation.copy() as? CABasicAnimation ?? CABasicAnimation(keyPath: "transform")
xformAnimation.keyPath = "transform"
xformAnimation.isAdditive = false
xformAnimation.fromValue = (animationLayer.presentation() ?? animationLayer).transform
xformAnimation.toValue = xform
xformAnimation.isRemovedOnCompletion = true
animationLayer.position = position
animationLayer.transform = xform
#if os(OSX)
animationLayer.anchorPoint = layer?.anchorPoint ?? CGPoint.zero
#else
animationLayer.anchorPoint = layer.anchorPoint
#endif
animationLayer.add(positionAnimation, forKey: positionKey)
animationLayer.add(xformAnimation, forKey: transformKey)
} else {
// In performance tests, we have to wrap the animation view setup
// in a `CATransaction` in order for the layers to be deallocated at
// the correct time. The `CATransaction`s in this method interfere
// with the ones managed by the performance test, and aren't actually
// necessary in a headless environment, so we disable them.
if TestHelpers.performanceTestsAreRunning {
animationLayer.position = position
animationLayer.transform = xform
} else {
CATransaction.begin()
CATransaction.setAnimationDuration(0.0)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .linear))
animationLayer.position = position
animationLayer.transform = xform
CATransaction.commit()
}
}
if shouldForceUpdates {
animationLayer.forceDisplayUpdate()
}
}
func updateRasterizationState() {
if isAnimationPlaying {
animationLayer?.shouldRasterize = false
} else {
animationLayer?.shouldRasterize = shouldRasterizeWhenIdle
}
}
/// Updates the animation frame. Does not affect any current animations
func updateAnimationFrame(_ newFrame: CGFloat) {
// In performance tests, we have to wrap the animation view setup
// in a `CATransaction` in order for the layers to be deallocated at
// the correct time. The `CATransaction`s in this method interfere
// with the ones managed by the performance test, and aren't actually
// necessary in a headless environment, so we disable them.
if TestHelpers.performanceTestsAreRunning {
animationLayer?.currentFrame = newFrame
animationLayer?.forceDisplayUpdate()
return
}
CATransaction.begin()
CATransaction.setCompletionBlock {
self.animationLayer?.forceDisplayUpdate()
}
CATransaction.setDisableActions(true)
animationLayer?.currentFrame = newFrame
CATransaction.commit()
}
@objc
override func animationWillMoveToBackground() {
updateAnimationForBackgroundState()
}
@objc
override func animationWillEnterForeground() {
updateAnimationForForegroundState()
}
override func animationMovedToWindow() {
/// Don't update any state if the `superview` is `nil`
/// When A viewA owns superViewB, it removes the superViewB from the window. At this point, viewA still owns superViewB and triggers the viewA method: -didmovetowindow
guard superview != nil else { return }
if window != nil {
updateAnimationForForegroundState()
} else {
updateAnimationForBackgroundState()
}
}
// MARK: Fileprivate
/// Context describing the animation that is currently playing in this `LottieAnimationView`
/// - When non-nil, an animation is currently playing in this view. Otherwise,
/// the view is paused on a specific frame.
fileprivate var animationContext: AnimationContext?
fileprivate var _activeAnimationName: String = LottieAnimationView.animationName
fileprivate var animationID = 0
fileprivate var waitingToPlayAnimation = false
fileprivate var activeAnimationName: String {
switch animationLayer?.primaryAnimationKey {
case .specific(let animationKey):
return animationKey
case .managed, nil:
return _activeAnimationName
}
}
fileprivate func makeAnimationLayer(usingEngine renderingEngine: RenderingEngineOption) {
/// Remove current animation if any
removeCurrentAnimation()
if let oldAnimation = animationLayer {
oldAnimation.removeFromSuperlayer()
}
invalidateIntrinsicContentSize()
guard let animation = animation else {
return
}
let rootAnimationLayer: RootAnimationLayer?
switch renderingEngine {
case .automatic:
rootAnimationLayer = makeAutomaticEngineLayer(for: animation)
case .specific(.coreAnimation):
rootAnimationLayer = makeCoreAnimationLayer(for: animation)
case .specific(.mainThread):
rootAnimationLayer = makeMainThreadAnimationLayer(for: animation)
}
guard let animationLayer = rootAnimationLayer else {
return
}
animationLayer.renderScale = screenScale
viewLayer?.addSublayer(animationLayer)
self.animationLayer = animationLayer
reloadImages()
animationLayer.setNeedsDisplay()
setNeedsLayout()
currentFrame = CGFloat(animation.startFrame)
}
fileprivate func makeMainThreadAnimationLayer(for animation: LottieAnimation) -> MainThreadAnimationLayer {
MainThreadAnimationLayer(
animation: animation,
imageProvider: imageProvider.cachedImageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
logger: logger)
}
fileprivate func makeCoreAnimationLayer(for animation: LottieAnimation) -> CoreAnimationLayer? {
do {
let coreAnimationLayer = try CoreAnimationLayer(
animation: animation,
imageProvider: imageProvider.cachedImageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
compatibilityTrackerMode: .track,
logger: logger)
coreAnimationLayer.didSetUpAnimation = { [logger] compatibilityIssues in
logger.assert(
compatibilityIssues.isEmpty,
"Encountered Core Animation compatibility issues while setting up animation:\n"
+ compatibilityIssues.map { $0.description }.joined(separator: "\n") + "\n\n"
+ """
This animation cannot be rendered correctly by the Core Animation engine.
To resolve this issue, you can use `RenderingEngineOption.automatic`, which automatically falls back
to the Main Thread rendering engine when necessary, or just use `RenderingEngineOption.mainThread`.
""")
}
return coreAnimationLayer
} catch {
// This should never happen, because we initialize the `CoreAnimationLayer` with
// `CompatibilityTracker.Mode.track` (which reports errors in `didSetUpAnimation`,
// not by throwing).
logger.assertionFailure("Encountered unexpected error \(error)")
return nil
}
}
fileprivate func makeAutomaticEngineLayer(for animation: LottieAnimation) -> CoreAnimationLayer? {
do {
// Attempt to set up the Core Animation layer. This can either throw immediately in `init`,
// or throw an error later in `CALayer.display()` that will be reported in `didSetUpAnimation`.
let coreAnimationLayer = try CoreAnimationLayer(
animation: animation,
imageProvider: imageProvider.cachedImageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
compatibilityTrackerMode: .abort,
logger: logger)
coreAnimationLayer.didSetUpAnimation = { [weak self] issues in
self?.automaticEngineLayerDidSetUpAnimation(issues)
}
return coreAnimationLayer
} catch {
if case CompatibilityTracker.Error.encounteredCompatibilityIssue(let compatibilityIssue) = error {
automaticEngineLayerDidSetUpAnimation([compatibilityIssue])
} else {
// This should never happen, because we expect `CoreAnimationLayer` to only throw
// `CompatibilityTracker.Error.encounteredCompatibilityIssue` errors.
logger.assertionFailure("Encountered unexpected error \(error)")
automaticEngineLayerDidSetUpAnimation([])
}
return nil
}
}
// Handles any compatibility issues with the Core Animation engine
// by falling back to the Main Thread engine
fileprivate func automaticEngineLayerDidSetUpAnimation(_ compatibilityIssues: [CompatibilityIssue]) {
// If there weren't any compatibility issues, then there's nothing else to do
if compatibilityIssues.isEmpty {
return
}
logger.warn(
"Encountered Core Animation compatibility issue while setting up animation:\n"
+ compatibilityIssues.map { $0.description }.joined(separator: "\n") + "\n"
+ """
This animation may have additional compatibility issues, but animation setup was cancelled early to avoid wasted work.
Automatically falling back to Main Thread rendering engine. This fallback comes with some additional performance
overhead, which can be reduced by manually specifying that this animation should always use the Main Thread engine.
""")
let animationContext = animationContext
let currentFrame = currentFrame
makeAnimationLayer(usingEngine: .mainThread)
// Set up the Main Thread animation layer using the same configuration that
// was being used by the previous Core Animation layer
self.currentFrame = currentFrame
if let animationContext = animationContext {
// `AnimationContext.closure` (`AnimationCompletionDelegate`) is a reference type
// that is the animation layer's `CAAnimationDelegate`, and holds a reference to
// the animation layer. Reusing a single instance across different animation layers
// can cause the animation setup to fail, so we create a copy of the `animationContext`:
addNewAnimationForContext(AnimationContext(
playFrom: animationContext.playFrom,
playTo: animationContext.playTo,
closure: animationContext.closure.completionBlock))
}
}
fileprivate func updateAnimationForBackgroundState() {
if let currentContext = animationContext {
switch backgroundBehavior {
case .stop:
removeCurrentAnimation()
updateAnimationFrame(currentContext.playFrom)
case .pause:
removeCurrentAnimation()
case .pauseAndRestore:
currentContext.closure.ignoreDelegate = true
removeCurrentAnimation()
/// Keep the stale context around for when the app enters the foreground.
animationContext = currentContext
case .forceFinish:
removeCurrentAnimation()
updateAnimationFrame(currentContext.playTo)
case .continuePlaying:
break
}
}
}
fileprivate func updateAnimationForForegroundState() {
if let currentContext = animationContext {
if waitingToPlayAnimation {
waitingToPlayAnimation = false
addNewAnimationForContext(currentContext)
} else if backgroundBehavior == .pauseAndRestore {
/// Restore animation from saved state
updateInFlightAnimation()
}
}
}
/// Removes the current animation and pauses the animation at the current frame
/// if necessary before setting up a new animation.
/// - This is not necessary with the Core Animation engine, and skipping
/// this step lets us avoid building the animations twice (once paused
/// and once again playing)
/// - This method should only be called immediately before setting up another
/// animation -- otherwise this LottieAnimationView could be put in an inconsistent state.
fileprivate func removeCurrentAnimationIfNecessary() {
switch currentRenderingEngine {
case .mainThread:
removeCurrentAnimation()
case .coreAnimation, nil:
// We still need to remove the `animationContext`, since it should only be present
// when an animation is actually playing. Without this calling `removeCurrentAnimationIfNecessary()`
// and then setting the animation to a specific paused frame would put this
// `LottieAnimationView` in an inconsistent state.
animationContext = nil
}
}
/// Stops the current in flight animation and freezes the animation in its current state.
fileprivate func removeCurrentAnimation() {
guard animationContext != nil else { return }
let pauseFrame = realtimeAnimationFrame
animationLayer?.removeAnimation(forKey: activeAnimationName)
updateAnimationFrame(pauseFrame)
animationContext = nil
}
/// Updates an in flight animation.
fileprivate func updateInFlightAnimation() {
guard let animationContext = animationContext else { return }
guard animationContext.closure.animationState != .complete else {
// Tried to re-add an already completed animation. Cancel.
self.animationContext = nil
return
}
/// Tell existing context to ignore its closure
animationContext.closure.ignoreDelegate = true
/// Make a new context, stealing the completion block from the previous.
let newContext = AnimationContext(
playFrom: animationContext.playFrom,
playTo: animationContext.playTo,
closure: animationContext.closure.completionBlock)
/// Remove current animation, and freeze the current frame.
let pauseFrame = realtimeAnimationFrame
animationLayer?.removeAnimation(forKey: activeAnimationName)
animationLayer?.currentFrame = pauseFrame
addNewAnimationForContext(newContext)
}
/// Adds animation to animation layer and sets the delegate. If animation layer or animation are nil, exits.
fileprivate func addNewAnimationForContext(_ animationContext: AnimationContext) {
guard let animationlayer = animationLayer, let animation = animation else {
return
}
self.animationContext = animationContext
switch currentRenderingEngine {
case .mainThread:
guard window != nil else {
waitingToPlayAnimation = true
return
}
case .coreAnimation, nil:
// The Core Animation engine automatically batches animation setup to happen
// in `CALayer.display()`, which won't be called until the layer is on-screen,
// so we don't need to defer animation setup at this layer.
break
}
animationID = animationID + 1
_activeAnimationName = LottieAnimationView.animationName + String(animationID)
if let coreAnimationLayer = animationlayer as? CoreAnimationLayer {
var animationContext = animationContext
// Core Animation doesn't natively support negative speed values,
// so instead we can swap `playFrom` / `playTo`
if animationSpeed < 0 {
let temp = animationContext.playFrom
animationContext.playFrom = animationContext.playTo
animationContext.playTo = temp
}
var timingConfiguration = CoreAnimationLayer.CAMediaTimingConfiguration(
autoreverses: loopMode.caAnimationConfiguration.autoreverses,
repeatCount: loopMode.caAnimationConfiguration.repeatCount,
speed: abs(Float(animationSpeed)))
// The animation should start playing from the `currentFrame`,
// if `currentFrame` is included in the time range being played.
let lowerBoundTime = min(animationContext.playFrom, animationContext.playTo)
let upperBoundTime = max(animationContext.playFrom, animationContext.playTo)
if (lowerBoundTime ..< upperBoundTime).contains(round(currentFrame)) {
// We have to configure this differently depending on the loop mode:
switch loopMode {
// When playing exactly once (and not looping), we can just set the
// `playFrom` time to be the `currentFrame`. Since the animation duration
// is based on `playFrom` and `playTo`, this automatically truncates the
// duration (so the animation stops playing at `playFrom`).
case .playOnce:
animationContext.playFrom = currentFrame
// When looping, we specifically _don't_ want to affect the duration of the animation,
// since that would affect the duration of all subsequent loops. We just want to adjust
// the duration of the _first_ loop. Instead of setting `playFrom`, we just add a `timeOffset`
// so the first loop begins at `currentTime` but all subsequent loops are the standard duration.
default:
if animationSpeed < 0 {
timingConfiguration.timeOffset = animation.time(forFrame: animationContext.playFrom) - currentTime
} else {
timingConfiguration.timeOffset = currentTime - animation.time(forFrame: animationContext.playFrom)
}
}
}
coreAnimationLayer.playAnimation(configuration: .init(
animationContext: animationContext,
timingConfiguration: timingConfiguration))
return
}
/// At this point there is no animation on animationLayer and its state is set.
let framerate = animation.framerate
let playFrom = animationContext.playFrom.clamp(animation.startFrame, animation.endFrame)
let playTo = animationContext.playTo.clamp(animation.startFrame, animation.endFrame)
let duration = ((max(playFrom, playTo) - min(playFrom, playTo)) / CGFloat(framerate))
let playingForward: Bool =
(
(animationSpeed > 0 && playFrom < playTo) ||
(animationSpeed < 0 && playTo < playFrom))
var startFrame = currentFrame.clamp(min(playFrom, playTo), max(playFrom, playTo))
if startFrame == playTo {
startFrame = playFrom
}
let timeOffset: TimeInterval = playingForward
? Double(startFrame - min(playFrom, playTo)) / framerate
: Double(max(playFrom, playTo) - startFrame) / framerate
let layerAnimation = CABasicAnimation(keyPath: "currentFrame")
layerAnimation.fromValue = playFrom
layerAnimation.toValue = playTo
layerAnimation.speed = Float(animationSpeed)
layerAnimation.duration = TimeInterval(duration)
layerAnimation.fillMode = CAMediaTimingFillMode.both
layerAnimation.repeatCount = loopMode.caAnimationConfiguration.repeatCount
layerAnimation.autoreverses = loopMode.caAnimationConfiguration.autoreverses
layerAnimation.isRemovedOnCompletion = false
if timeOffset != 0 {
let currentLayerTime = viewLayer?.convertTime(CACurrentMediaTime(), from: nil) ?? 0
layerAnimation.beginTime = currentLayerTime - (timeOffset * 1 / Double(abs(animationSpeed)))
}
layerAnimation.delegate = animationContext.closure
animationContext.closure.animationLayer = animationlayer
animationContext.closure.animationKey = activeAnimationName
animationlayer.add(layerAnimation, forKey: activeAnimationName)
updateRasterizationState()
}
// MARK: Private
static private let animationName = "Lottie"
private let logger: LottieLogger
/// The `LottieBackgroundBehavior` that was specified manually by setting `self.backgroundBehavior`
private var _backgroundBehavior: LottieBackgroundBehavior?
}
// MARK: - LottieLoopMode + caAnimationConfiguration
extension LottieLoopMode {
/// The `CAAnimation` configuration that reflects this mode
var caAnimationConfiguration: (repeatCount: Float, autoreverses: Bool) {
switch self {
case .playOnce:
return (repeatCount: 1, autoreverses: false)
case .loop:
return (repeatCount: .greatestFiniteMagnitude, autoreverses: false)
case .autoReverse:
return (repeatCount: .greatestFiniteMagnitude, autoreverses: true)
case .repeat(let amount):
return (repeatCount: amount, autoreverses: false)
case .repeatBackwards(let amount):
return (repeatCount: amount, autoreverses: true)
}
}
}
| 5e59205a603c260a061b9617c32360d6 | 37.160976 | 171 | 0.707493 | false | false | false | false |
lkzhao/YetAnotherAnimationLibrary | refs/heads/master | Sources/YetAnotherAnimationLibrary/Solvers/SpringSolver.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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 Foundation
public struct SpringSolver<Value: VectorConvertible>: RK4Solver {
public typealias Vector = Value.Vector
public let stiffness: Double
public let damping: Double
public let threshold: Double
public var current: AnimationProperty<Value>!
public var velocity: AnimationProperty<Value>!
public var target: AnimationProperty<Value>!
public init(stiffness: Double,
damping: Double,
threshold: Double) {
self.stiffness = stiffness
self.damping = damping
self.threshold = threshold
}
public func acceleration(current: Vector, velocity: Vector) -> Vector {
return stiffness * (target.vector - current) - damping * velocity
}
public func updateWith(newCurrent: Vector, newVelocity: Vector) -> Bool {
if newCurrent.distance(between: target.vector) < threshold,
newVelocity.distance(between: .zero) < threshold {
current.vector = target.vector
velocity.vector = .zero
return true
} else {
current.vector = newCurrent
velocity.vector = newVelocity
return false
}
}
}
| 793f2e9bcf422f8697c11bc65d4c7c44 | 39.551724 | 80 | 0.697704 | false | false | false | false |
flypaper0/ethereum-wallet | refs/heads/release/1.1 | ethereum-wallet/Common/Extensions/UIButton+Helpers.swift | gpl-3.0 | 1 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
extension UIButton {
func loadingIndicator(_ show: Bool) {
let indicatorTag = 808404
if show {
isEnabled = false
alpha = 0
let indicator = UIActivityIndicatorView(style: .gray)
indicator.center = center
indicator.tag = indicatorTag
addSubview(indicator)
indicator.startAnimating()
} else {
isEnabled = true
alpha = 1.0
if let indicator = viewWithTag(indicatorTag) as? UIActivityIndicatorView {
indicator.stopAnimating()
indicator.removeFromSuperview()
}
}
}
}
| f780090c44d87b2ffd85083d961cecb4 | 27.296296 | 86 | 0.566754 | false | false | false | false |
renshu16/DouyuSwift | refs/heads/master | DouyuSwift/DouyuSwift/Classes/Tools/Extention/UIBarButtonItem-Extension.swift | mit | 1 | //
// UIBarButtonItem-Extension.swift
// DouyuSwift
//
// Created by ToothBond on 16/11/10.
// Copyright © 2016年 ToothBond. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*
class func createItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
btn.setImage(UIImage(named: highImageName), for: .highlighted)
btn.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
return UIBarButtonItem(customView: btn)
}
*/
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named:imageName), for: .normal)
if highImageName != "" {
btn.setImage(UIImage(named:highImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView : btn)
}
}
| 0a7564668121942aa85bc6f4df02aafc | 27.219512 | 102 | 0.592913 | false | false | false | false |
JGiola/swift | refs/heads/main | test/decl/nested/type_in_function.swift | apache-2.0 | 10 | // RUN: %target-typecheck-verify-swift -parse-as-library
// Generic class locally defined in non-generic function (rdar://problem/20116710)
func f3() {
class B<T> {}
class C : B<Int> {}
_ = B<Int>()
_ = C()
}
// Type defined inside a closure (rdar://problem/31803589)
func hasAClosure() {
_ = {
enum E<T> { case a(T) }
let _ = E.a("hi")
let _ = E<String>.a("hi")
let _: E = .a("hi")
let _: E<String> = .a("hi")
}
}
protocol Racoon {
associatedtype Stripes
}
// Types inside generic functions -- not supported yet
func outerGenericFunction<T>(_ t: T) {
struct InnerNonGeneric { // expected-error{{type 'InnerNonGeneric' cannot be nested in generic function 'outerGenericFunction'}}
func nonGenericMethod(_ t: T) {}
func genericMethod<V>(_ t: T) -> V where V : Racoon, V.Stripes == T {}
}
struct InnerGeneric<U> { // expected-error{{type 'InnerGeneric' cannot be nested in generic function 'outerGenericFunction'}}
func nonGenericMethod(_ t: T, u: U) {}
func genericMethod<V>(_ t: T, u: U) -> V where V : Racoon, V.Stripes == T {}
}
_ = {
struct ConcreteInClosure { // expected-error{{type 'ConcreteInClosure' cannot be nested in closure in generic context}}
}
struct GenericInClosure<U> { // expected-error{{type 'GenericInClosure' cannot be nested in closure in generic context}}
}
}
}
class OuterNonGenericClass {
func genericFunction<T>(_ t: T) {
class InnerNonGenericClass : OuterNonGenericClass { // expected-error {{type 'InnerNonGenericClass' cannot be nested in generic function 'genericFunction'}}
let t: T
init(t: T) { super.init(); self.t = t }
}
class InnerGenericClass<U> : OuterNonGenericClass // expected-error {{type 'InnerGenericClass' cannot be nested in generic function 'genericFunction'}}
where U : Racoon, U.Stripes == T {
let t: T
init(t: T) { super.init(); self.t = t }
}
}
}
class OuterGenericClass<T> {
func genericFunction<U>(_ t: U) {
class InnerNonGenericClass1 : OuterGenericClass { // expected-error {{type 'InnerNonGenericClass1' cannot be nested in generic function 'genericFunction'}}
let t: T
init(t: T) { super.init(); self.t = t }
}
class InnerNonGenericClass2 : OuterGenericClass<Int> { // expected-error {{type 'InnerNonGenericClass2' cannot be nested in generic function 'genericFunction'}}
let t: T
init(t: T) { super.init(); self.t = t }
}
class InnerNonGenericClass3 : OuterGenericClass<T> { // expected-error {{type 'InnerNonGenericClass3' cannot be nested in generic function 'genericFunction'}}
let t: T
init(t: T) { super.init(); self.t = t }
}
class InnerGenericClass<U> : OuterGenericClass<U> // expected-error {{type 'InnerGenericClass' cannot be nested in generic function 'genericFunction'}}
where U : Racoon, U.Stripes == T {
let t: T
init(t: T) { super.init(); self.t = t }
}
}
}
// Name lookup within local classes.
func f5<T, U>(x: T, y: U) {
struct Local { // expected-error {{type 'Local' cannot be nested in generic function 'f5(x:y:)'}}
func f() {
_ = 17 as T // expected-error{{'Int' is not convertible to 'T'}}
// expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{14-16=as!}}
_ = 17 as U // okay: refers to 'U' declared within the local class
}
typealias U = Int
}
}
// Issue with gatherAllSubstitutions().
struct OuterGenericStruct<A> {
class MiddleNonGenericClass {
func nonGenericFunction() {
class InnerGenericClass<T> : MiddleNonGenericClass {
// expected-error@-1 {{type 'InnerGenericClass' cannot be nested in generic function 'nonGenericFunction()'}}
override init() { super.init() }
}
}
}
func middleFunction() {
struct ConformingType : Racoon {
// expected-error@-1 {{type 'ConformingType' cannot be nested in generic function 'middleFunction()'}}
typealias Stripes = A
}
}
}
// Issue with diagnoseUnknownType().
func genericFunction<T>(t: T) {
class First : Second<T>.UnknownType { }
// expected-error@-1 {{type 'First' cannot be nested in generic function 'genericFunction(t:)'}}
// expected-error@-2 {{'UnknownType' is not a member type of generic class 'type_in_function.Second<T>'}}
class Second<T> : Second { } // expected-note{{'Second' declared here}}
// expected-error@-1 {{type 'Second' cannot be nested in generic function 'genericFunction(t:)'}}
// expected-error@-2 {{'Second' inherits from itself}}
}
// Superclass lookup archetype vs interface type mixup
class Generic<T> {
struct Nested {}
func outerMethod() {
class Inner : Generic<T> { // expected-error {{type 'Inner' cannot be nested in generic function 'outerMethod()'}}
func innerMethod() -> Nested {}
}
}
}
| c03cf6549cb24410aaa461496c71b2d0 | 31.952381 | 164 | 0.649463 | false | false | false | false |
codeOfRobin/eSubziiOS | refs/heads/master | eSubzi/APIConstants.swift | mit | 1 |
import Foundation
//let APIPageSize = 20
//let botChannelId = 14
struct API {
struct Static {
static let apiProtocol = "http://"
// static let baseURL = "128.199.152.41"
static let baseURL = "localhost"
static let portNumber = "3000"
static let api = "api"
static let login = "login"
static let discounts = "discounts"
static let get = "get"
static let signup = "signup"
static let products = "products"
static let placeOrder = "placeOrder"
static let fetchOrder = "findOrders"
static let findOrdersNotDelivered = "findOrdersNotDelivered"
}
var fullUrl:String
{
return Static.apiProtocol + Static.baseURL + ":" + Static.portNumber
// return Static.apiProtocol + Static.baseURL
}
var loginURL:String
{
return ([fullUrl,Static.api,Static.login]).joinWithSeparator("/")
}
var signupURL:String
{
return ([fullUrl,Static.api,Static.signup]).joinWithSeparator("/")
}
var getAllNotificationsURL:String
{
return ([fullUrl,Static.api,Static.discounts,Static.get]).joinWithSeparator("/")
}
var getAllProductsURL:String
{
return([fullUrl,Static.api,Static.products,Static.get]).joinWithSeparator("/")
}
var placeOrderURL: String
{
return([fullUrl,Static.api,Static.placeOrder]).joinWithSeparator("/")
}
var fetchOrdersURL: String
{
return([fullUrl,Static.api,Static.fetchOrder]).joinWithSeparator("/")
}
var fetchLatestOrdersURL: String
{
return([fullUrl,Static.api,Static.findOrdersNotDelivered]).joinWithSeparator("/")
}
} | 34ef456dcc1548e269ab5b0bac545aef | 26.396825 | 89 | 0.623188 | false | false | false | false |
nuudles/GradientView | refs/heads/master | GradientView/GradientView.swift | mit | 1 | //
// GradientView.swift
// GradientView
//
// Created by Christopher Luu on 12/17/15.
// Copyright © 2015 Nuudles. All rights reserved.
//
import UIKit
open class GradientView: UIView {
// MARK: - Class methods
open override class var layerClass: AnyClass {
return CAGradientLayer.self
}
// MARK: - Public properties
open var gradientLayer: CAGradientLayer {
return layer as! CAGradientLayer
}
open var colors: [UIColor]? {
get {
guard let colors = gradientLayer.colors as? [CGColor] else { return nil }
return colors.map { UIColor(cgColor: $0) }
}
set {
gradientLayer.colors = newValue?.map { $0.cgColor }
}
}
open var locations: [Float]? {
get {
return gradientLayer.locations as? [Float]
}
set {
gradientLayer.locations = newValue as [NSNumber]?
}
}
open var endPoint: CGPoint {
get {
return gradientLayer.endPoint
}
set {
gradientLayer.endPoint = newValue
}
}
open var startPoint: CGPoint {
get {
return gradientLayer.startPoint
}
set {
gradientLayer.startPoint = newValue
}
}
}
| 435850a92dfa88c4d46c2b0357bc9fa8 | 18.777778 | 76 | 0.67603 | false | false | false | false |
eric1202/LZJ_Coin | refs/heads/master | LZJ_Coin/Pods/LeanCloud/Sources/Storage/Logger.swift | mit | 4 | //
// Logger.swift
// LeanCloud
//
// Created by Tang Tianyong on 10/19/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
class Logger {
static let defaultLogger = Logger()
static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'.'HH':'mm':'ss'.'SSS"
return dateFormatter
}()
public func log<T>(
_ value: @autoclosure () -> T,
_ file: String = #file,
_ function: String = #function,
_ line: Int = #line)
{
let date = Logger.dateFormatter.string(from: Date())
let file = NSURL(string: file)?.lastPathComponent ?? "Unknown"
print("[LeanCloud \(date) \(file) #\(line) \(function)]:", value())
}
}
| f9328a07037d3a58873d6da242759973 | 24.029412 | 75 | 0.591069 | false | false | false | false |
bryan1anderson/iMessage-to-Day-One-Importer | refs/heads/master | iMessage Importer/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// iMessage Importer
//
// Created by Bryan on 8/7/17.
// Copyright © 2017 Bryan Lloyd Anderson. All rights reserved.
//
import Cocoa
import NotificationCenter
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
@IBOutlet weak var window: NSWindow!
var statusItem: NSStatusItem!
let popover = NSPopover()
let importer = MessageImporter(date: Date())
var importDatesMenuItem: NSMenuItem?
var importedDates: [Date] {
get {
let defaults = UserDefaults.standard
let importedDates = defaults.object(forKey: "imported_dates") as? [Date] ?? []
return importedDates
}
set {
let defaults = UserDefaults.standard
defaults.set(newValue, forKey: "imported_dates")
defaults.synchronize()
}
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
// importer.delegate = self
let center = NSUserNotificationCenter.default
center.delegate = self
let nots = center.scheduledNotifications
// self.importedDates = []
// importMessages()
// scheduleNotification()
setMenu()
setPopover()
}
func setPopover() {
if let button = statusItem.button {
button.action = #selector(togglePopover(_:))
button.image = #imageLiteral(resourceName: "StatusBarButtonImage")
}
let storyboard = NSStoryboard(name: "Import", bundle: nil)
let wc = storyboard.instantiateInitialController() as! NSViewController
popover.contentViewController = wc
}
@objc func togglePopover(_ sender: Any?) {
if popover.isShown {
closePopover(sender: sender)
} else {
showPopover(sender: sender)
}
}
func showPopover(sender: Any?) {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
func closePopover(sender: Any?) {
popover.performClose(sender)
}
func setMenu() {
let statusItem = NSStatusBar.system().statusItem(withLength: -1)
self.statusItem = statusItem
if let button = statusItem.button {
button.image = #imageLiteral(resourceName: "StatusBarButtonImage")
// button.action = Selector("printQuote:")
}
let menu = NSMenu()
// menu.addItem(NSMenuItem(title: "Print Quote", action: Selector("printQuote:"), keyEquivalent: "P"))
let importDatesMenuItem = NSMenuItem(title: "Import Non-Imported Dates", action: #selector(AppDelegate.importMessagesForAllNonImportedDates), keyEquivalent: "i")
self.importDatesMenuItem = importDatesMenuItem
menu.addItem(importDatesMenuItem)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Settings", action: #selector(AppDelegate.openSettings), keyEquivalent: "s"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Manually Import Yesterday", action: #selector(AppDelegate.manuallyImport), keyEquivalent: "i"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Begin Import Old Messages", action: #selector(AppDelegate.importNonImportedOldMessages), keyEquivalent: "o"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit iMessage Importer", action: #selector(AppDelegate.terminate), keyEquivalent: "q"))
// statusItem.menu = menu
}
@objc func openSettings() {
let newWindow = NSWindow(contentRect: NSMakeRect(0, 0, NSScreen.main()!.frame.midX, NSScreen.main()!.frame.midY), styleMask: [.closable], backing: .buffered, defer: false)
newWindow.title = "New Window"
newWindow.isOpaque = false
newWindow.center()
newWindow.isMovableByWindowBackground = true
newWindow.backgroundColor = NSColor(calibratedHue: 0, saturation: 1.0, brightness: 0, alpha: 0.7)
newWindow.makeKeyAndOrderFront(nil)
let storyboard = NSStoryboard(name: "Settings", bundle: nil)
let wc = storyboard.instantiateInitialController() as! NSViewController
self.window.contentViewController?.presentViewControllerAsModalWindow(wc)
// let myWindow = wc.window
//// var myWindow = NSWindow(contentViewController: wc)
// myWindow?.makeKeyAndOrderFront(self)
//// let controller = NSWindowController(window: myWindow)
// wc.loadWindow()
// wc.showWindow(self)
//TODO: Create window
// let frame = NSScreen.main()?.frame ?? .zero
//
// let window = NSWindow(contentRect: frame, styleMask: .closable, backing: .buffered, defer: false)
//
// self.window.windowController?.showWindow(window)
}
func scheduleNotification() {
let defaults = UserDefaults.standard
var identifier = defaults.object(forKey: "notification_identifier") as? String
if let identifier = identifier {
} else {
identifier = NSUUID().uuidString
defaults.set(identifier, forKey: "notification_identifier")
}
let notification = NSUserNotification()
// All these values are optional
notification.title = "Began import of iMessages"
notification.subtitle = "Don't quit the app"
notification.informativeText = "If import has not already occurred for the day, this will begin now"
notification.soundName = NSUserNotificationDefaultSoundName
notification.identifier = identifier
var c = DateComponents()
c.hour = 3
notification.deliveryRepeatInterval = c
NSUserNotificationCenter.default.scheduleNotification(notification)
}
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
let defaults = UserDefaults.standard
let identifier = defaults.object(forKey: "notification_identifier") as? String
if notification.identifier == identifier {
importMessages(date: Date())
}
return true
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@objc func terminate() {
}
@objc func manuallyImport() {
print("beginning import")
let currentDate = Date().yesterday
// importer.getMessages()
var importedDates = self.importedDates
importedDates.append(currentDate)
self.importedDates = importedDates
}
@objc func importMessagesForAllNonImportedDates() {
self.importDatesMenuItem?.isEnabled = false
var startC = DateComponents()
startC.year = 2016
startC.month = 1
startC.day = 9
// var endC = DateComponents()
// endC.year = 2017
// endC.month = 6
// endC.day = 29
guard var date = Calendar.current.date(from: startC) else { return }
// let endDate = Calendar.current.date(from: endC) else { return } // first date
let endDate = Date().yesterday // last date
var importedDates = self.importedDates
while date <= endDate {
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
let contains = importedDates.contains(where: { Calendar.current.isDate($0, inSameDayAs: date) })
if !contains {
print("importing: \(date)")
importMessages(date: date)
importedDates.append(date)
self.importedDates = importedDates
} else {
print("already imported date: \(date)")
}
}
self.importDatesMenuItem?.isEnabled = false
}
func importMessages(date: Date) {
let importer = MessageImporter(date: date)
// importer.delegate = self
// importer.getMessages()
}
@objc func importNonImportedOldMessages() {
var startC = DateComponents()
startC.year = 2009
startC.month = 9
startC.day = 20
var endC = DateComponents()
endC.year = 2014
endC.month = 10
endC.day = 22
// var endC = DateComponents()
// endC.year = 2017
// endC.month = 6
// endC.day = 29
guard var date = Calendar.current.date(from: startC),
let endDate = Calendar.current.date(from: endC)?.yesterday else { return }
// let endDate = Calendar.current.date(from: endC) else { return } // first date
// let endDate = Date().yesterday // last date
// var importedDates = self.importedDates
while date <= endDate {
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
print("importing: \(date)")
self.importOldMessages(date: date)
// let contains = importedDates.contains(where: { Calendar.current.isDate($0, inSameDayAs: date) })
// if !contains {
// importMessages(date: date)
// importedDates.append(date)
// self.importedDates = importedDates
// } else {
// print("already imported date: \(date)")
// }
}
}
func importOldMessages(date: Date) {
let importer = SMSImporter(date: date)
importer.delegate = self
importer.importDbs()
}
}
extension AppDelegate: MessageImporterDelegate {
func didGet(chatMessageJoins: [ChatMessageJoin]) {
for chatMessageJoin in chatMessageJoins {
chatMessageJoin.getReadableString(completion: { (entry) in
guard let command = self.createEntryCommand(for: entry) else { return }
let returned = run(command: command)
print(returned)
})
}
}
func didGet(oldGroupJoins: [GroupMessageMemberJoin]) {
for chatMessageJoin in oldGroupJoins {
chatMessageJoin.getReadableString(completion: { (entry) in
guard let command = self.createEntryCommand(for: entry) else { return }
// print(command)
let returned = run(command: command)
print(returned)
})
}
}
func createEntryCommand(for entry: Entry) -> String? {
let c = Calendar.current.dateComponents([.day, .month, .year], from: entry.date)
guard let day = c.day,
let month = c.month,
let year = c.year else { return nil }
let tags = entry.tags.joined(separator: " ")
let body = "\(entry.title) \(entry.body)"
let command = "/usr/local/bin/dayone2 -j 'iMessages' --tags='\(tags)' --date='\(month)/\(day)/\(year)' new \'\(body)\'"
print(command)
return command
}
}
func run(command: String) -> String {
let pipe = Pipe()
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", command)]
task.standardOutput = pipe
let file = pipe.fileHandleForReading
task.launch()
if let result = NSString(data: file.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue) {
return result as String
}
else {
return "--- Error running command - Unable to initialize string from file data ---"
}
}
| 9c0a2380163ae9cd38936ced5cc8ab48 | 33.363897 | 179 | 0.599767 | false | false | false | false |
takaiwai/CGExtensions | refs/heads/master | Example/Tests/FloatingPointExtensionsSpec.swift | mit | 1 | import Quick
import Nimble
import CGExtensions
class FloatingPointExtensionsSpec: QuickSpec {
override func spec() {
describe("CGFloat+Extensions") {
describe("degreesInRadians") {
it("returns the angle in radians") {
let radians = 45.0.degreesInRadians
expect(radians) ≈ 0.78539816339
}
}
describe("radiansInDegrees") {
it("return the angle in degrees") {
let degrees = 0.78539816339.radiansInDegrees
expect(degrees) ≈ 45.0
}
}
describe("normalizedAngle(base:)") {
it("fits the angle within 0-base") {
let angle1 = 30.0.normanizedAngle(base: 360.0)
expect(angle1) ≈ 30.0
let angle2 = 410.0.normanizedAngle(base: 360.0)
expect(angle2) ≈ 50.0
let angle3 = 17305.0.normanizedAngle(base: 360.0)
expect(angle3) ≈ 25.0
}
it("add multiple of base to negative value to make it fit between 0-base") {
let angle1 = (-25.8).normanizedAngle(base: 360.0)
expect(angle1) ≈ 334.2
let angle2 = (-77025.0).normanizedAngle(base: 360.0)
expect(angle2) ≈ 15.0
}
it("can take any positive number as base") {
let angle1 = 32.0.normanizedAngle(base: 30.0)
expect(angle1) ≈ 2.0
}
it("will raise an exception if base is less then 0") {
expect {
20.0.normanizedAngle(base: -10.0)
}.to(raiseException(named: NSExceptionName.invalidArgumentException.rawValue))
expect {
20.0.normanizedAngle(base: 0.0)
}.to(raiseException(named: NSExceptionName.invalidArgumentException.rawValue))
}
}
describe("normalizedRadians") {
it("fits the angle within 0-2π") {
let angle1 = 10.0.normalizedRadians
expect(angle1) ≈ 3.71681469282
let angle2 = (-5.0).normalizedRadians
expect(angle2) ≈ 1.28318530718
}
}
describe("normalizedDegrees") {
it("fits the angle within 0-360") {
let angle1 = 410.0.normalizedDegrees
expect(angle1) ≈ 50.0
let angle2 = (-30.0).normalizedDegrees
expect(angle2) ≈ 330.0
}
}
}
}
}
| a0f25c3632e842a5ac7c344eee4158e3 | 35.987654 | 98 | 0.435581 | false | false | false | false |
crashoverride777/SwiftyAds | refs/heads/master | Sources/Internal/SwiftyAdsNative.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Dominik Ringler
//
// 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 GoogleMobileAds
protocol SwiftyAdsNativeType: AnyObject {
func load(from viewController: UIViewController,
adUnitIdType: SwiftyAdsAdUnitIdType,
loaderOptions: SwiftyAdsNativeAdLoaderOptions,
adTypes: [GADAdLoaderAdType],
onFinishLoading: (() -> Void)?,
onError: ((Error) -> Void)?,
onReceive: @escaping (GADNativeAd) -> Void)
func stopLoading()
}
final class SwiftyAdsNative: NSObject {
// MARK: - Properties
private let environment: SwiftyAdsEnvironment
private let adUnitId: String
private let request: () -> GADRequest
private var onFinishLoading: (() -> Void)?
private var onError: ((Error) -> Void)?
private var onReceive: ((GADNativeAd) -> Void)?
private var adLoader: GADAdLoader?
// MARK: - Initialization
init(environment: SwiftyAdsEnvironment, adUnitId: String, request: @escaping () -> GADRequest) {
self.environment = environment
self.adUnitId = adUnitId
self.request = request
}
}
// MARK: - SwiftyAdsNativeType
extension SwiftyAdsNative: SwiftyAdsNativeType {
func load(from viewController: UIViewController,
adUnitIdType: SwiftyAdsAdUnitIdType,
loaderOptions: SwiftyAdsNativeAdLoaderOptions,
adTypes: [GADAdLoaderAdType],
onFinishLoading: (() -> Void)?,
onError: ((Error) -> Void)?,
onReceive: @escaping (GADNativeAd) -> Void) {
self.onFinishLoading = onFinishLoading
self.onError = onError
self.onReceive = onReceive
// If AdLoader is already loading we should not make another request
if let adLoader = adLoader, adLoader.isLoading { return }
// Create multiple ads ad loader options
var multipleAdsAdLoaderOptions: [GADMultipleAdsAdLoaderOptions]? {
switch loaderOptions {
case .single:
return nil
case .multiple(let numberOfAds):
let options = GADMultipleAdsAdLoaderOptions()
options.numberOfAds = numberOfAds
return [options]
}
}
// Set the ad unit id
var adUnitId: String {
if case .development = environment {
return self.adUnitId
}
switch adUnitIdType {
case .plist:
return self.adUnitId
case .custom(let id):
return id
}
}
// Create GADAdLoader
adLoader = GADAdLoader(
adUnitID: adUnitId,
rootViewController: viewController,
adTypes: adTypes,
options: multipleAdsAdLoaderOptions
)
// Set the GADAdLoader delegate
adLoader?.delegate = self
// Load ad with request
adLoader?.load(request())
}
func stopLoading() {
adLoader?.delegate = nil
adLoader = nil
}
}
// MARK: - GADNativeAdLoaderDelegate
extension SwiftyAdsNative: GADNativeAdLoaderDelegate {
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
onReceive?(nativeAd)
}
func adLoaderDidFinishLoading(_ adLoader: GADAdLoader) {
onFinishLoading?()
}
func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
onError?(error)
}
}
| 7320cb36c9158e7d2989790d62a0605d | 33.066176 | 100 | 0.636736 | false | false | false | false |
grigaci/RateMyTalkAtMobOS | refs/heads/master | RateMyTalkAtMobOS/Classes/Helpers/Extensions/Float+Stars.swift | bsd-3-clause | 1 | //
// Float+Stars.swift
// RateMyTalkAtMobOS
//
// Created by Bogdan Iusco on 10/11/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import Foundation
let kRatingStarsMin: Float = 0
let kRatingStarsMax: Float = 4
extension Float {
func roundStars() -> Float {
var temp = round(2.0 * self)
temp = temp / 2.0
return temp
}
func isRatingValid() -> Bool {
let greater: NSComparisonResult = NSNumber(float: self).compare(NSNumber(float: kRatingStarsMin))
let lessOrEqual: NSComparisonResult = NSNumber(float: self).compare(NSNumber(float: kRatingStarsMax))
return greater == .OrderedDescending && lessOrEqual != .OrderedDescending
}
}
| 488afbade80f9dfce03ad12f1aade053 | 24.642857 | 109 | 0.662953 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/Views/Pagebar/QPagebar.swift | mit | 1 | //
// Quickly
//
open class QPagebarItem : QCollectionItem {
}
open class QPagebarCell< Item: QPagebarItem > : QCollectionCell< Item > {
}
open class QPagebar : QView {
public typealias ItemType = IQCollectionController.Cell
public weak var delegate: QPagebarDelegate?
public var edgeInsets: UIEdgeInsets = UIEdgeInsets() {
didSet(oldValue) { if self.edgeInsets != oldValue { self.setNeedsUpdateConstraints() } }
}
public private(set) var cellTypes: [ItemType.Type]
public var itemsSpacing: CGFloat {
set(value) { self._collectionLayout.minimumInteritemSpacing = value }
get { return self._collectionLayout.minimumInteritemSpacing }
}
public var items: [QPagebarItem] {
set(value) {
self._collectionSection.setItems(value)
self._collectionController.reload()
}
get { return self._collectionSection.items as! [QPagebarItem] }
}
public var selectedItem: QPagebarItem? {
get { return self._collectionController.selectedItems.first as? QPagebarItem }
}
private lazy var _collectionView: QCollectionView = {
let view = QCollectionView(frame: self.bounds.inset(by: self.edgeInsets), collectionViewLayout: self._collectionLayout)
view.translatesAutoresizingMaskIntoConstraints = false
view.showsHorizontalScrollIndicator = false
view.showsVerticalScrollIndicator = false
view.allowsMultipleSelection = false
view.collectionController = self._collectionController
return view
}()
private lazy var _collectionLayout: CollectionLayout = {
let layout = CollectionLayout()
layout.scrollDirection = .horizontal
return layout
}()
private lazy var _collectionController: CollectionController = {
let controller = CollectionController(self, cells: self.cellTypes)
controller.sections = [ self._collectionSection ]
return controller
}()
private lazy var _collectionSection: QCollectionSection = {
return QCollectionSection(items: [])
}()
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.removeConstraints(self._constraints) }
didSet { self.addConstraints(self._constraints) }
}
public required init() {
fatalError("init(coder:) has not been implemented")
}
public init(
cellTypes: [ItemType.Type]
) {
self.cellTypes = cellTypes
super.init(
frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)
)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
self.backgroundColor = UIColor.clear
self.addSubview(self._collectionView)
}
open override func updateConstraints() {
super.updateConstraints()
self._constraints = [
self._collectionView.topLayout == self.topLayout.offset(self.edgeInsets.top),
self._collectionView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left),
self._collectionView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right),
self._collectionView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom)
]
}
public func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil) {
self._collectionController.performBatchUpdates(updates, completion: completion)
}
public func prependItem(_ item: QPagebarItem) {
self._collectionSection.prependItem(item)
}
public func prependItem(_ items: [QPagebarItem]) {
self._collectionSection.prependItem(items)
}
public func appendItem(_ item: QPagebarItem) {
self._collectionSection.appendItem(item)
}
public func appendItem(_ items: [QPagebarItem]) {
self._collectionSection.appendItem(items)
}
public func insertItem(_ item: QPagebarItem, index: Int) {
self._collectionSection.insertItem(item, index: index)
}
public func insertItem(_ items: [QPagebarItem], index: Int) {
self._collectionSection.insertItem(items, index: index)
}
public func deleteItem(_ item: QPagebarItem) {
self._collectionSection.deleteItem(item)
}
public func deleteItem(_ items: [QPagebarItem]) {
self._collectionSection.deleteItem(items)
}
public func replaceItem(_ item: QPagebarItem, index: Int) {
self._collectionSection.replaceItem(item, index: index)
}
public func reloadItem(_ item: QPagebarItem) {
self._collectionSection.reloadItem(item)
}
public func reloadItem(_ items: [QPagebarItem]) {
self._collectionSection.reloadItem(items)
}
public func setSelectedItem(_ selectedItem: QPagebarItem?, animated: Bool) {
if let item = selectedItem {
if self._collectionController.isSelected(item: item) == false {
self._collectionController.select(item: item, scroll: [ .centeredHorizontally, .centeredVertically ], animated: animated)
}
} else {
self._collectionController.selectedItems = []
}
}
private class CollectionLayout : UICollectionViewFlowLayout {
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard
let collectionView = self.collectionView,
let superAttributes = super.layoutAttributesForElements(in: rect),
let attributes = NSArray(array: superAttributes, copyItems: true) as? [UICollectionViewLayoutAttributes]
else { return nil }
let contentSize = self.collectionViewContentSize
let boundsSize = collectionView.bounds.size
if (contentSize.width < boundsSize.width) || (contentSize.height < boundsSize.height) {
let offset = CGPoint(
x: (boundsSize.width - contentSize.width) / 2,
y: (boundsSize.height - contentSize.height) / 2
)
attributes.forEach({ layoutAttribute in
layoutAttribute.frame = layoutAttribute.frame.offsetBy(dx: offset.x, dy: offset.y)
})
}
attributes.forEach({ layoutAttribute in
layoutAttribute.frame = CGRect(
origin: layoutAttribute.frame.origin,
size: CGSize(
width: layoutAttribute.frame.width,
height: boundsSize.height
)
)
})
return attributes
}
}
private class CollectionController : QCollectionController {
public private(set) weak var pagebar: QPagebar?
public init(_ pagebar: QPagebar, cells: [ItemType.Type]) {
self.pagebar = pagebar
super.init(cells: cells)
}
@objc
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let pagebar = self.pagebar, let delegate = pagebar.delegate else { return }
collectionView.scrollToItem(at: indexPath, at: [ .centeredHorizontally, .centeredVertically ], animated: true)
delegate.pagebar(pagebar, didSelectItem: pagebar.selectedItem!)
}
}
}
public protocol QPagebarDelegate : class {
func pagebar(_ pagebar: QPagebar, didSelectItem: QPagebarItem)
}
| 03f2729966663031501fdb96c03d2a8b | 34.906103 | 137 | 0.640952 | false | false | false | false |
RxSwiftCommunity/RxSwift-Ext | refs/heads/main | Carthage/Checkouts/RxSwiftExt/Playground/RxSwiftExtPlayground.playground/Pages/ignore.xcplaygroundpage/Contents.swift | mit | 3 | /*:
> # IMPORTANT: To use `RxSwiftExtPlayground.playground`, please:
1. Make sure you have [Carthage](https://github.com/Carthage/Carthage) installed
1. Fetch Carthage dependencies from shell: `carthage bootstrap --platform ios`
1. Build scheme `RxSwiftExtPlayground` scheme for a simulator target
1. Choose `View > Show Debug Area`
*/
//: [Previous](@previous)
import RxSwift
import RxSwiftExt
/*:
## ignore
The `ignore` operator filters out any of the elements passed in parameters. An alternate implementation of `ignore` is provided, which takes a `SequenceType` with any number of elements to ignore.
*/
example("ignore a single value") {
let values = ["Hello", "Swift", "world"]
Observable.from(values)
.ignore("Swift")
.toArray()
.subscribe(onNext: { result in
// look values on the right panel ===>
values
result
print("ignore() transformed \(values) to \(result)")
})
}
example("ignore multiple values") {
let values = "Hello Swift world we really like Swift and RxSwift".components(separatedBy: " ")
Observable.from(values)
.ignore("Swift", "and")
.toArray()
.subscribe(onNext: { result in
// look values on the right panel ===>
values
result
print("ignore() transformed \(values) to \(result)")
})
}
example("ignore a collection of values") {
let values = "Hello Swift world we really like Swift and RxSwift".components(separatedBy: " ")
let ignoreSet = Set(["and", "Swift"])
Observable.from(values)
.ignore(ignoreSet)
.toArray()
.subscribe(onNext: { result in
// look values on the right panel ===>
values
result
print("ignore() transformed \(values) to \(result)")
})
}
/*:
## ignoreWhen
The `ignoreWhen` operator works like `filter` but ignores the elements for which the predicate returns `true` instead of keeping them.
*/
example("ignore some elements") {
let values = [1, 5, 40, 12, 60, 3, 9, 18]
Observable.from(values)
.ignoreWhen { value in
return value > 10
}
.toArray()
.subscribe(onNext: { result in
// look values on the right panel ===>
values
result
print("ignoreWhen() transformed \(values) to \(result)")
})
}
/*:
## ignoreErrors
The `ignoreErrors` operator is a synonym for the `retry` operator: it unconditionally ignores any error emitted by the sequence,
creating an sequence that never fails
*/
enum ExampleError : Error {
case SeriousError
case MinorError
}
example("ignore all errors") {
let subject = PublishSubject<Observable<Int>>()
let _ = subject
.asObservable()
.flatMap { $0 }
.ignoreErrors()
.subscribe { print($0) }
subject.onNext(Observable.just(1))
subject.onNext(Observable.just(2))
subject.onNext(Observable.just(3))
subject.onNext(Observable.error(ExampleError.SeriousError))
subject.onNext(Observable.just(4))
subject.onNext(Observable.just(5))
}
example("ignore only minor errors") {
let subject = PublishSubject<Observable<Int>>()
let _ = subject
.asObservable()
.flatMap { $0 }
.ignoreErrors {
if case ExampleError.SeriousError = $0 {
return false
}
return true
}
.subscribe { print($0) }
subject.onNext(Observable.just(1))
subject.onNext(Observable.just(2))
subject.onNext(Observable.just(3))
subject.onNext(Observable.error(ExampleError.SeriousError))
subject.onNext(Observable.just(4))
subject.onNext(Observable.just(5))
}
//: [Next](@next)
| 8f10b2e2778a852bca6f83581faa42e9 | 25.337931 | 197 | 0.615868 | false | false | false | false |
jestinson/weather | refs/heads/master | weather/Cache.swift | mit | 1 | //
// Cache.swift
// weather
//
// Created by Stinson, Justin on 8/9/15.
// Copyright © 2015 Justin Stinson. All rights reserved.
//
import Foundation
/**
Container that holds a collection of generic values referenced by string keys. Data is held in
memory and the size of the collection is bounded. The API is similar to a native Dictionary.
Internally when an item is added an NSDate is stored for record keeping. When the cache reaches
the maximum size the oldest item is removed. When an item is accessed its corresponding date is
bumped to the current time to keep the item from being removed next time the maximum is reached.
This means that items added and never accessed with be removed before items frequently accessed
even if they are the oldest.
This class is implemented using a standard Dictionary which provides best case O(1) and worst
case O(n) access times. Since a cache accesses always require two traversals of the data
structure (one to get the item, and a second to update the item with a new date) the expected
performance is 2 * O(1) to 2 * O(n) or simply O(1) to O(n). Cache insertions become 2 * O(1)
to 2 * O(n^2) or O(1) to O(n^2).
See: http://www.raywenderlich.com/79850/collection-data-structures-swift
*/
struct Cache<ValueType> {
/// The maximum number of items the cache can hold. After this number is reached the
/// oldest item will be removed.
let maxNumItems: Int
/// The number of items in the cache
var count: Int {
get {
return cache.count
}
}
private var cache = [String: (ValueType, NSDate)]()
/// Designated initializer
/// - Parameter: maximumNumberOfItems The largest number of items the cache should allow
/// (values less than 1 are changed to 1)
init(maximumNumberOfItems: Int) {
self.maxNumItems = maximumNumberOfItems > 0 ? maximumNumberOfItems : 1
}
/// Subscript to get/set values in the cache by key
subscript(key: String) -> ValueType? {
mutating get {
guard let value = self.cache[key] else {
// No value for the key
return nil
}
// Replace the existing value with one that has an updated date
self.cache[key] = (value.0, NSDate())
// Return the value
return value.0
}
mutating set {
guard let newValue = newValue else {
// Can't add nil
return
}
// Add the new item and remove one if needed
self.cache[key] = (newValue, NSDate())
self.removeOldestIconFromCacheIfNeeded()
}
}
/// Remove all elements.
mutating func removeAll() {
self.cache.removeAll(keepCapacity: true)
}
/// Removes the oldest icon from the cache
/// - Returns: Boolean indicating if a value was removed from the cache or not
private mutating func removeOldestIconFromCacheIfNeeded() -> Bool {
let cacheSize = self.cache.count
if cacheSize < 1 || cacheSize <= self.maxNumItems {
// Cache is empty or not yet at max size, no removal needed
return false
}
// Find the oldest item and remove it from the cache
var oldestItem = self.cache.first!
for item in self.cache {
if item.1.1.compare(oldestItem.1.1) == .OrderedAscending {
oldestItem = item
}
}
self.cache.removeValueForKey(oldestItem.0)
return true
}
}
| 32a469b84a1f6b00c88dd0452d42d4c8 | 34.411765 | 100 | 0.629568 | false | false | false | false |
pmlbrito/QuickShotUtils | refs/heads/master | QuickShotUtils/Classes/Extensions/Math+QSUAdditions.swift | mit | 1 | //
// Math+QSUAdditions.swift
// Pods
//
// Created by Pedro Brito on 22/06/16.
//
//
import Foundation
public extension CGFloat {
func round(toDecimals: Int = 2) -> CGFloat {
let divisor = pow(10.0, CGFloat(toDecimals))
return ceil(self * divisor) / divisor
}
// mutating func roundToDecimals(decimals: Int = 2) -> CGFloat {
// let divisor = pow(10.0, CGFloat(decimals))
// let retValue = CGFloat((self * divisor) / divisor)
// return ceil(retValue)
// }
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
public extension Double {
/// Rounds the double to decimal places value
func round(toDecimals:Int) -> Double {
let divisor = pow(10.0, Double(toDecimals))
return ceil(self * divisor) / divisor
}
}
| a6c0082d0d2e9fc3e2858e1de66c35fe | 22.371429 | 67 | 0.633252 | false | false | false | false |
UsrNameu1/VIPER-SWIFT | refs/heads/master | VIPER-SWIFTTests/CalendarTests.swift | mit | 8 | //
// CalendarTests.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/6/14.
// Copyright (c) 2014 Conrad Stoll. All rights reserved.
//
import XCTest
class CalendarTests: XCTestCase {
var calendar = NSCalendar()
override func setUp() {
super.setUp()
calendar = NSCalendar.gregorianCalendar()
}
func testEarlyYearMonthDayIsBeforeLaterYearMonthDay() {
let earlyDate = calendar.dateWithYear(2004, month: 2, day: 29)
let laterDate = calendar.dateWithYear(2004, month: 3, day: 1)
let comparison = calendar.isDate(earlyDate, beforeYearMonthDay: laterDate)
XCTAssert(comparison, "\(earlyDate) should be before \(laterDate)")
}
func testYearMonthDayIsNotBeforeSameYearMonthDay() {
let earlyDate = calendar.dateWithYear(2005, month: 6, day: 1)
let laterDate = calendar.dateWithYear(2005, month: 6, day: 1)
let comparison = calendar.isDate(earlyDate, beforeYearMonthDay: laterDate)
XCTAssertFalse(comparison, "\(earlyDate) should not be before \(laterDate)")
}
func testLaterYearMonthDayIsNotBeforeEarlyYearMonthDay() {
let earlyDate = calendar.dateWithYear(2006, month: 4, day: 15)
let laterDate = calendar.dateWithYear(2006, month: 4, day: 16)
let comparison = calendar.isDate(laterDate, beforeYearMonthDay: earlyDate)
XCTAssertFalse(comparison, "\(earlyDate) should not be before \(laterDate)")
}
func testEqualYearMonthDaysCompareAsEqual() {
let earlyDate = calendar.dateWithYear(2005, month: 6, day: 1)
let laterDate = calendar.dateWithYear(2005, month: 6, day: 1)
let comparison = calendar.isDate(earlyDate, equalToYearMonthDay: laterDate)
XCTAssert(comparison, "\(earlyDate) should equal \(laterDate)")
}
func testDifferentYearMonthDaysCompareAsNotEqual() {
let earlyDate = calendar.dateWithYear(2005, month: 6, day: 1)
let laterDate = calendar.dateWithYear(2005, month: 6, day: 2)
let comparison = calendar.isDate(earlyDate, equalToYearMonthDay: laterDate)
XCTAssertFalse(comparison, "\(earlyDate) should not equal \(laterDate)")
}
func testEndOfNextWeekDuringSameYear() {
let date = calendar.dateWithYear(2005, month: 8, day: 2)
let expectedNextWeek = calendar.dateWithYear(2005, month: 8, day: 13)
let nextWeek = calendar.dateForEndOfFollowingWeekWithDate(date)
let comparison = calendar.isDate(nextWeek, equalToYearMonthDay: expectedNextWeek)
XCTAssert(comparison, "Next week should end on \(expectedNextWeek) (not \(nextWeek))")
}
func testEndOfNextWeekDuringFollowingYear() {
let date = calendar.dateWithYear(2005, month: 12, day: 27)
let expectedNextWeek = calendar.dateWithYear(2006, month: 1, day: 7)
let nextWeek = calendar.dateForEndOfFollowingWeekWithDate(date)
let comparison = calendar.isDate(nextWeek, equalToYearMonthDay: expectedNextWeek)
XCTAssert(comparison, "Next week should end on \(expectedNextWeek) (not \(nextWeek))")
}
}
| 01b268333f0078d2c523726a4ed4e0f0 | 43.585714 | 94 | 0.691125 | false | true | false | false |
DikeyKing/WeCenterMobile-iOS | refs/heads/master | WeCenterMobile/View/Search/TopicSearchResultCell.swift | gpl-2.0 | 1 | //
// TopicSearchResultCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/6/14.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class TopicSearchResultCell: UITableViewCell {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var badgeLabel: UILabel!
@IBOutlet weak var topicImageView: UIImageView!
@IBOutlet weak var topicTitleLabel: UILabel!
@IBOutlet weak var topicDescriptionLabel: UILabel!
@IBOutlet weak var topicButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
let theme = SettingsManager.defaultManager.currentTheme
for v in [containerView, badgeLabel] {
v.msr_borderColor = theme.borderColorA
}
containerView.backgroundColor = theme.backgroundColorB
badgeLabel.backgroundColor = theme.backgroundColorA
topicTitleLabel.textColor = theme.titleTextColor
topicDescriptionLabel.textColor = theme.subtitleTextColor
badgeLabel.textColor = theme.footnoteTextColor
topicButton.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted)
}
func update(#dataObject: DataObject) {
let topic = dataObject as! Topic
topicTitleLabel.text = topic.title
topicDescriptionLabel.text = topic.introduction ?? ""
topicImageView.wc_updateWithTopic(topic)
topicButton.msr_userInfo = topic
setNeedsLayout()
layoutIfNeeded()
}
}
| 3700c3360d3f6c0746c25ecdb8394b8d | 33.466667 | 99 | 0.705996 | false | false | false | false |
glessard/swift | refs/heads/snapshot | SwiftCompilerSources/Sources/SIL/SmallProjectionPath.swift | apache-2.0 | 1 | //===--- SmallProjectionPath.swift - a path of projections ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A small and very efficient representation of a projection path.
///
/// A `SmallProjectionPath` can be parsed and printed in SIL syntax and parsed from Swift
/// source code - the SIL syntax is more compact than the Swift syntax.
/// In the following, we use the SIL syntax for the examples.
///
/// The `SmallProjectionPath` represents a path of value or address projections.
/// For example, the projection path which represents
///
/// %t = struct_extract %s: $Str, #Str.tupleField // first field in Str
/// %c = tuple_extract %f : $(Int, Class), 4
/// %r = ref_element_addr %c $Class, #Class.classField // 3rd field in Class
///
/// is `s0.4.c2`, where `s0` is the first path component and `c2` is the last component.
///
/// A `SmallProjectionPath` can be a concrete path (like the example above): it only
/// contains concrete field elements, e.g. `s0.c2.e1`
/// Or it can be a pattern path, where one or more path components are wild cards, e.g.
/// `v**.c*` means: any number of value projections (struct, enum, tuple) followed by
/// a single class field projection.
///
/// Internally, a `SmallProjectionPath` is represented as a single 64-bit word.
/// This is very efficient, but it also means that a path cannot exceed a certain length.
/// If too many projections are pushed onto a path, the path is converted to a `**` wildcard,
/// which means: it represents any number of any kind of projections.
/// Though, it's very unlikely that the limit will be reached in real world scenarios.
///
public struct SmallProjectionPath : CustomStringConvertible, CustomReflectable, Hashable {
/// The physical representation of the path. The path components are stored in
/// reverse order: the first path component is stored in the lowest bits (LSB),
/// the last component is stored in the highest bits (MSB).
/// Each path component consists of zero or more "index-overflow" bytes followed
/// by the "index-kind" main byte (from LSB to MSB).
///
/// index overflow byte: bit-nr: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
/// +---+---+---+---+---+---+---+---+
/// content: | index high bits | 1 |
///
/// main byte (small kind): bit-nr: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
/// +---+---+---+---+---+---+---+---+
/// content: | index low bits| kind | 0 |
///
/// "Large" kind values (>= 0x7) don't have an associated index and the main
/// byte looks like:
///
/// main byte (large kind): bit-nr: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
/// +---+---+---+---+---+---+---+---+
/// content: | kind high bits| 1 | 1 | 1 | 0 |
///
private let bytes: UInt64
// TODO: add better support for tail elements by tracking the
// index of `index_addr` instructions.
public enum FieldKind : Int {
case root = 0x0 // The pseudo component denoting the end of the path.
case structField = 0x1 // A concrete struct field: syntax e.g. `s3`
case tupleField = 0x2 // A concrete tuple element: syntax e.g. `2`
case enumCase = 0x3 // A concrete enum case (with payload): syntax e.g. `e4'
case classField = 0x4 // A concrete class field: syntax e.g. `c1`
case tailElements = 0x5 // A tail allocated element of a class: syntax `ct`
case anyValueFields = 0x6 // Any number of any value fields (struct, tuple, enum): syntax `v**`
// "Large" kinds: starting from here the low 3 bits must be 1.
// This and all following kinds (we'll add in the future) cannot have a field index.
case anyClassField = 0x7 // Any class field, including tail elements: syntax `c*`
case anything = 0xf // Any number of any fields: syntax `**`
public var isValueField: Bool {
switch self {
case .anyValueFields, .structField, .tupleField, .enumCase:
return true
case .root, .anything, .anyClassField, .classField, .tailElements:
return false
}
}
public var isClassField: Bool {
switch self {
case .anyClassField, .classField, .tailElements:
return true
case .root, .anything, .anyValueFields, .structField, .tupleField, .enumCase:
return false
}
}
}
public init() { self.bytes = 0 }
/// Creates a new path with an initial element.
public init(_ kind: FieldKind, index: Int = 0) {
self = Self().push(kind, index: index)
}
private init(bytes: UInt64) { self.bytes = bytes }
public var isEmpty: Bool { bytes == 0 }
public var description: String {
let (kind, idx, sp) = pop()
let subPath = sp
let s: String
switch kind {
case .root: return ""
case .structField: s = "s\(idx)"
case .tupleField: s = "\(idx)"
case .enumCase: s = "e\(idx)"
case .classField: s = "c\(idx)"
case .tailElements: s = "ct"
case .anything: s = "**"
case .anyValueFields: s = "v**"
case .anyClassField: s = "c*"
}
if subPath.isEmpty {
return s
}
return "\(s).\(subPath)"
}
/// Returns the top (= the first) path component and the number of its encoding bits.
private var top: (kind: FieldKind, index: Int, numBits: Int) {
var idx = 0
var b = bytes
var numBits = 0
// Parse any index overflow bytes.
while (b & 1) == 1 {
idx = (idx << 7) | Int((b >> 1) & 0x7f)
b >>= 8
numBits = numBits &+ 8
}
var kindVal = (b >> 1) & 0x7
if kindVal == 0x7 {
// A "large" kind - without any index
kindVal = (b >> 1) & 0x7f
assert(idx == 0)
assert(numBits == 0)
} else {
// A "small" kind with an index
idx = (idx << 4) | Int((b >> 4) & 0xf)
}
let k = FieldKind(rawValue: Int(kindVal))!
if k == .anything {
assert((b >> 8) == 0, "'anything' only allowed in last path component")
numBits = 8
} else {
numBits = numBits &+ 8
}
return (k, idx, numBits)
}
/// Pops \p numBits from the path.
private func pop(numBits: Int) -> SmallProjectionPath {
return Self(bytes: bytes &>> numBits)
}
/// Pops and returns the first path component included the resulting path
/// after popping.
///
/// For example, popping from `s0.c3.e1` returns (`s`, 0, `c3.e1`)
public func pop() -> (kind: FieldKind, index: Int, path: SmallProjectionPath) {
let (k, idx, numBits) = top
return (k, idx, pop(numBits: numBits))
}
/// Pushes a new first component to the path and returns the new path.
///
/// For example, pushing `s0` to `c3.e1` returns `s0.c3.e1`.
public func push(_ kind: FieldKind, index: Int = 0) -> SmallProjectionPath {
assert(kind != .anything || bytes == 0, "'anything' only allowed in last path component")
var idx = index
var b = bytes
if (b >> 56) != 0 {
// Overflow
return Self(.anything)
}
b = (b << 8) | UInt64(((idx & 0xf) << 4) | (kind.rawValue << 1))
idx >>= 4
while idx != 0 {
if (b >> 56) != 0 { return Self(.anything) }
b = (b << 8) | UInt64(((idx & 0x7f) << 1) | 1)
idx >>= 7
}
return Self(bytes: b)
}
/// Pops the first path component if it is exactly of kind `kind` - not considering wildcards.
///
/// Returns the index of the component and the new path or - if not matching - returns nil.
public func pop(kind: FieldKind) -> (index: Int, path: SmallProjectionPath)? {
let (k, idx, newPath) = pop()
if k != kind { return nil }
return (idx, newPath)
}
/// Pops the first path component if it matches `kind` and (optionally) `index`.
///
/// For example:
/// popping `s0` from `s0.c3.e1` returns `c3.e1`
/// popping `c2` from `c*.e1` returns `e1`
/// popping `s0` from `v**.c3.e1` return `v**.c3.e1` (because `v**` means _any_ number of value fields)
/// popping `s0` from `c*.e1` returns nil
///
/// Note that if `kind` is a wildcard, also the first path component must be a wildcard to popped.
/// For example:
/// popping `v**` from `s0.c1` returns nil
/// popping `v**` from `v**.c1` returns `v**.c1` (because `v**` means _any_ number of value fields)
/// popping `c*` from `c0.e3` returns nil
/// popping `c*` from `c*.e3` returns `e3`
public func popIfMatches(_ kind: FieldKind, index: Int? = nil) -> SmallProjectionPath? {
let (k, idx, numBits) = top
switch k {
case .anything:
return self
case .anyValueFields:
if kind.isValueField { return self }
return pop(numBits: numBits).popIfMatches(kind, index: index)
case .anyClassField:
if kind.isClassField {
return pop(numBits: numBits)
}
return nil
case kind:
if let i = index {
if i != idx { return nil }
}
return pop(numBits: numBits)
default:
return nil
}
}
/// Returns true if the path does not have any class projections.
/// For example:
/// returns true for `v**`
/// returns false for `c0`
/// returns false for `**` (because '**' can have any number of class projections)
public var hasNoClassProjection: Bool {
return matches(pattern: Self(.anyValueFields))
}
/// Returns true if the path has at least one class projection.
/// For example:
/// returns false for `v**`
/// returns true for `v**.c0.s1.v**`
/// returns false for `**` (because '**' can have zero class projections)
public var hasClassProjection: Bool {
var p = self
while true {
let (k, _, numBits) = p.top
if k == .root { return false }
if k.isClassField { return true }
p = p.pop(numBits: numBits)
}
}
/// Pops all value field components from the beginning of the path.
/// For example:
/// `s0.e2.3.c4.s1` -> `c4.s1`
/// `v**.c4.s1` -> `c4.s1`
/// `**` -> `**` (because `**` can also be a class field)
public func popAllValueFields() -> SmallProjectionPath {
var p = self
while true {
let (k, _, numBits) = p.top
if !k.isValueField { return p }
p = p.pop(numBits: numBits)
}
}
/// Pops the last class projection and all following value fields from the tail of the path.
/// For example:
/// `s0.e2.3.c4.s1` -> `s0.e2.3`
/// `v**.c1.c4.s1` -> `v**.c1`
/// `c1.**` -> `c1.**` (because it's unknown how many class projections are in `**`)
public func popLastClassAndValuesFromTail() -> SmallProjectionPath {
var p = self
var totalBits = 0
var neededBits = 0
while true {
let (k, _, numBits) = p.top
if k == .root { break }
if k.isClassField {
neededBits = totalBits
totalBits += numBits
} else {
totalBits += numBits
if !k.isValueField {
// k is `anything`
neededBits = totalBits
}
}
p = p.pop(numBits: numBits)
}
if neededBits == 64 { return self }
return SmallProjectionPath(bytes: bytes & ((1 << neededBits) - 1))
}
/// Returns true if this path matches a pattern path.
///
/// Formally speaking:
/// If this path is a concrete path, returns true if it matches the pattern.
/// If this path is a pattern path itself, returns true if all concrete paths which
/// match this path also match the pattern path.
/// For example:
/// `s0.c3.e1` matches `s0.c3.e1`
/// `s0.c3.e1` matches `v**.c*.e1`
/// `v**.c*.e1` does not match `s0.c3.e1`!
/// Note that matching is not reflexive.
public func matches(pattern: SmallProjectionPath) -> Bool {
let (patternKind, patternIdx, subPattern) = pattern.pop()
switch patternKind {
case .root: return isEmpty
case .anything: return true
case .anyValueFields:
return popAllValueFields().matches(pattern: subPattern)
case .anyClassField:
let (kind, _, subPath) = pop()
if !kind.isClassField { return false }
return subPath.matches(pattern: subPattern)
case .structField, .tupleField, .enumCase, .classField, .tailElements:
let (kind, index, subPath) = pop()
if kind != patternKind || index != patternIdx { return false }
return subPath.matches(pattern: subPattern)
}
}
/// Returns the merged path of this path and `rhs`.
///
/// Merging means that all paths which match this path and `rhs` will also match the result.
/// If `rhs` is not equal to this path, the result is computed by replacing
/// mismatching components by wildcards.
/// For example:
/// `s0.c3.e4` merged with `s0.c1.e4` -> `s0.c*.e4`
/// `s0.s1.c3` merged with `e4.c3` -> `v**.c3`
/// `s0.c1.c2` merged with `s0.c3` -> `s0.**`
public func merge(with rhs: SmallProjectionPath) -> SmallProjectionPath {
if self == rhs { return self }
let (lhsKind, lhsIdx, lhsBits) = top
let (rhsKind, rhsIdx, rhsBits) = rhs.top
if lhsKind == rhsKind && lhsIdx == rhsIdx {
assert(lhsBits == rhsBits)
let subPath = pop(numBits: lhsBits).merge(with: rhs.pop(numBits: rhsBits))
if lhsKind == .anyValueFields && subPath.top.kind == .anyValueFields {
return subPath
}
return subPath.push(lhsKind, index: lhsIdx)
}
if lhsKind.isValueField || rhsKind.isValueField {
let subPath = popAllValueFields().merge(with: rhs.popAllValueFields())
assert(!subPath.top.kind.isValueField)
if subPath.top.kind == .anything {
return subPath
}
return subPath.push(.anyValueFields)
}
if lhsKind.isClassField && rhsKind.isClassField {
let subPath = pop(numBits: lhsBits).merge(with: rhs.pop(numBits: rhsBits))
return subPath.push(.anyClassField)
}
return Self(.anything)
}
/// Returns true if this path may overlap with `rhs`.
///
/// "Overlapping" means that both paths may project the same field.
/// For example:
/// `s0.s1` and `s0.s1` overlap (the paths are identical)
/// `s0.s1` and `s0.s2` don't overlap
/// `s0.s1` and `s0` overlap (the second path is a sub-path of the first one)
/// `s0.v**` and `s0.s1` overlap
public func mayOverlap(with rhs: SmallProjectionPath) -> Bool {
if isEmpty || rhs.isEmpty {
return true
}
let (lhsKind, lhsIdx, lhsBits) = top
let (rhsKind, rhsIdx, rhsBits) = rhs.top
if lhsKind == .anything || rhsKind == .anything {
return true
}
if lhsKind == .anyValueFields || rhsKind == .anyValueFields {
return popAllValueFields().mayOverlap(with: rhs.popAllValueFields())
}
if (lhsKind == rhsKind && lhsIdx == rhsIdx) ||
(lhsKind == .anyClassField && rhsKind.isClassField) ||
(lhsKind.isClassField && rhsKind == .anyClassField) {
return pop(numBits: lhsBits).mayOverlap(with: rhs.pop(numBits: rhsBits))
}
return false
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
//===----------------------------------------------------------------------===//
// Parsing
//===----------------------------------------------------------------------===//
extension StringParser {
mutating func parseProjectionPathFromSource(for function: Function, type: Type?) throws -> SmallProjectionPath {
var entries: [(SmallProjectionPath.FieldKind, Int)] = []
var currentTy = type
repeat {
if consume("**") {
entries.append((.anything, 0))
currentTy = nil
} else if consume("class*") {
if let ty = currentTy, !ty.isClass {
try throwError("cannot use 'anyClassField' on a non-class type - add 'anyValueFields' first")
}
entries.append((.anyClassField, 0))
currentTy = nil
} else if consume("value**") {
entries.append((.anyValueFields, 0))
currentTy = nil
} else if let tupleElemIdx = consumeInt() {
guard let ty = currentTy, ty.isTuple else {
try throwError("cannot use a tuple index after 'any' field selection")
}
let tupleElements = ty.tupleElements
if tupleElemIdx >= tupleElements.count {
try throwError("tuple element index too large")
}
entries.append((.tupleField, tupleElemIdx))
currentTy = tupleElements[tupleElemIdx]
} else if let name = consumeIdentifier() {
guard let ty = currentTy else {
try throwError("cannot use field name after 'any' field selection")
}
if !ty.isClass && !ty.isStruct {
try throwError("unknown kind of nominal type")
}
let nominalFields = ty.getNominalFields(in: function)
guard let fieldIdx = nominalFields.getIndexOfField(withName: name) else {
try throwError("field not found")
}
if ty.isClass {
entries.append((.classField, fieldIdx))
} else {
assert(ty.isStruct)
entries.append((.structField, fieldIdx))
}
currentTy = nominalFields[fieldIdx]
} else {
try throwError("expected selection path component")
}
} while consume(".")
if let ty = currentTy, !ty.isClass {
try throwError("the select field is not a class - add 'anyValueFields'")
}
return try createPath(from: entries)
}
mutating func parseProjectionPathFromSIL() throws -> SmallProjectionPath {
var entries: [(SmallProjectionPath.FieldKind, Int)] = []
while true {
if consume("**") {
entries.append((.anything, 0))
} else if consume("c*") {
entries.append((.anyClassField, 0))
} else if consume("v**") {
entries.append((.anyValueFields, 0))
} else if consume("ct") {
entries.append((.tailElements, 0))
} else if consume("c") {
guard let idx = consumeInt(withWhiteSpace: false) else {
try throwError("expected class field index")
}
entries.append((.classField, idx))
} else if consume("e") {
guard let idx = consumeInt(withWhiteSpace: false) else {
try throwError("expected enum case index")
}
entries.append((.enumCase, idx))
} else if consume("s") {
guard let idx = consumeInt(withWhiteSpace: false) else {
try throwError("expected struct field index")
}
entries.append((.structField, idx))
} else if let tupleElemIdx = consumeInt() {
entries.append((.tupleField, tupleElemIdx))
} else if !consume(".") {
return try createPath(from: entries)
}
}
}
private func createPath(from entries: [(SmallProjectionPath.FieldKind, Int)]) throws -> SmallProjectionPath {
var path = SmallProjectionPath()
var first = true
for (kind, idx) in entries.reversed() {
if !first && kind == .anything {
try throwError("'**' only allowed in last path component")
}
path = path.push(kind, index: idx)
// Check for overflow
if !first && path == SmallProjectionPath(.anything) {
try throwError("path is too long")
}
first = false
}
return path
}
}
//===----------------------------------------------------------------------===//
// Unit Tests
//===----------------------------------------------------------------------===//
extension SmallProjectionPath {
public static func runUnitTests() {
basicPushPop()
parsing()
merging()
matching()
overlapping()
predicates()
path2path()
func basicPushPop() {
let p1 = SmallProjectionPath(.structField, index: 3)
.push(.classField, index: 12345678)
let (k2, i2, p2) = p1.pop()
assert(k2 == .classField && i2 == 12345678)
let (k3, i3, p3) = p2.pop()
assert(k3 == .structField && i3 == 3)
assert(p3.isEmpty)
let (k4, i4, _) = p2.push(.enumCase, index: 876).pop()
assert(k4 == .enumCase && i4 == 876)
let p5 = SmallProjectionPath(.anything)
assert(p5.pop().path.isEmpty)
}
func parsing() {
testParse("v**.c*", expect: SmallProjectionPath(.anyClassField)
.push(.anyValueFields))
testParse("s3.c*.v**.s1", expect: SmallProjectionPath(.structField, index: 1)
.push(.anyValueFields)
.push(.anyClassField)
.push(.structField, index: 3))
testParse("2.c*.e6.ct.**", expect: SmallProjectionPath(.anything)
.push(.tailElements)
.push(.enumCase, index: 6)
.push(.anyClassField)
.push(.tupleField, index: 2))
do {
var parser = StringParser("c*.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.s123.s3.**")
_ = try parser.parseProjectionPathFromSIL()
fatalError("too long path not detected")
} catch {
}
do {
var parser = StringParser("**.s0")
_ = try parser.parseProjectionPathFromSIL()
fatalError("wrong '**' not detected")
} catch {
}
}
func testParse(_ pathStr: String, expect: SmallProjectionPath) {
var parser = StringParser(pathStr)
let path = try! parser.parseProjectionPathFromSIL()
assert(path == expect)
let str = path.description
assert(str == pathStr)
}
func merging() {
testMerge("c1.c0", "c0", expect: "c*.**")
testMerge("c2.c1", "c2", expect: "c2.**")
testMerge("s3.c0", "v**.c0", expect: "v**.c0")
testMerge("c0", "s2.c1", expect: "v**.c*")
testMerge("s1.s1.c2", "s1.c2", expect: "s1.v**.c2")
testMerge("s1.s0", "s2.s0", expect: "v**")
testMerge("ct", "c2", expect: "c*")
testMerge("ct.s0.e0.v**.c0", "ct.s0.e0.v**.c0", expect: "ct.s0.e0.v**.c0")
testMerge("ct.s0.s0.c0", "ct.s0.e0.s0.c0", expect: "ct.s0.v**.c0")
}
func testMerge(_ lhsStr: String, _ rhsStr: String,
expect expectStr: String) {
var lhsParser = StringParser(lhsStr)
let lhs = try! lhsParser.parseProjectionPathFromSIL()
var rhsParser = StringParser(rhsStr)
let rhs = try! rhsParser.parseProjectionPathFromSIL()
var expectParser = StringParser(expectStr)
let expect = try! expectParser.parseProjectionPathFromSIL()
let result = lhs.merge(with: rhs)
assert(result == expect)
let result2 = rhs.merge(with: lhs)
assert(result2 == expect)
}
func matching() {
testMatch("ct", "c*", expect: true)
testMatch("c1", "c*", expect: true)
testMatch("s2", "v**", expect: true)
testMatch("1", "v**", expect: true)
testMatch("e1", "v**", expect: true)
testMatch("c*", "c1", expect: false)
testMatch("c*", "ct", expect: false)
testMatch("v**", "s0", expect: false)
testMatch("s0.s1", "s0.s1", expect: true)
testMatch("s0.s2", "s0.s1", expect: false)
testMatch("s0", "s0.v**", expect: true)
testMatch("s0.s1", "s0.v**", expect: true)
testMatch("s0.1.e2", "s0.v**", expect: true)
testMatch("s0.v**.e2", "v**", expect: true)
testMatch("s0.v**", "s0.s1", expect: false)
testMatch("s0.s1.c*", "s0.v**", expect: false)
testMatch("s0.v**", "s0.**", expect: true)
testMatch("s1.v**", "s0.**", expect: false)
testMatch("s0.**", "s0.v**", expect: false)
}
func testMatch(_ lhsStr: String, _ rhsStr: String, expect: Bool) {
var lhsParser = StringParser(lhsStr)
let lhs = try! lhsParser.parseProjectionPathFromSIL()
var rhsParser = StringParser(rhsStr)
let rhs = try! rhsParser.parseProjectionPathFromSIL()
let result = lhs.matches(pattern: rhs)
assert(result == expect)
}
func overlapping() {
testOverlap("s0.s1.s2", "s0.s1.s2", expect: true)
testOverlap("s0.s1.s2", "s0.s2.s2", expect: false)
testOverlap("s0.s1.s2", "s0.e1.s2", expect: false)
testOverlap("s0.s1.s2", "s0.s1", expect: true)
testOverlap("s0.s1.s2", "s1.s2", expect: false)
testOverlap("s0.c*.s2", "s0.ct.s2", expect: true)
testOverlap("s0.c*.s2", "s0.c1.s2", expect: true)
testOverlap("s0.c*.s2", "s0.c1.c2.s2", expect: false)
testOverlap("s0.c*.s2", "s0.s2", expect: false)
testOverlap("s0.v**.s2", "s0.s3", expect: true)
testOverlap("s0.v**.s2.c2", "s0.s3.c1", expect: false)
testOverlap("s0.v**.s2", "s1.s3", expect: false)
testOverlap("s0.v**.s2", "s0.v**.s3", expect: true)
testOverlap("s0.**", "s0.s3.c1", expect: true)
testOverlap("**", "s0.s3.c1", expect: true)
}
func testOverlap(_ lhsStr: String, _ rhsStr: String, expect: Bool) {
var lhsParser = StringParser(lhsStr)
let lhs = try! lhsParser.parseProjectionPathFromSIL()
var rhsParser = StringParser(rhsStr)
let rhs = try! rhsParser.parseProjectionPathFromSIL()
let result = lhs.mayOverlap(with: rhs)
assert(result == expect)
let reversedResult = rhs.mayOverlap(with: lhs)
assert(reversedResult == expect)
}
func predicates() {
testPredicate("v**", \.hasNoClassProjection, expect: true)
testPredicate("c0", \.hasNoClassProjection, expect: false)
testPredicate("1", \.hasNoClassProjection, expect: true)
testPredicate("**", \.hasNoClassProjection, expect: false)
testPredicate("v**", \.hasClassProjection, expect: false)
testPredicate("v**.c0.s1.v**", \.hasClassProjection, expect: true)
testPredicate("c0.**", \.hasClassProjection, expect: true)
testPredicate("c0.c1", \.hasClassProjection, expect: true)
testPredicate("ct", \.hasClassProjection, expect: true)
testPredicate("s0", \.hasClassProjection, expect: false)
}
func testPredicate(_ pathStr: String, _ property: (SmallProjectionPath) -> Bool, expect: Bool) {
var parser = StringParser(pathStr)
let path = try! parser.parseProjectionPathFromSIL()
let result = property(path)
assert(result == expect)
}
func path2path() {
testPath2Path("s0.e2.3.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1")
testPath2Path("v**.c4.s1", { $0.popAllValueFields() }, expect: "c4.s1")
testPath2Path("**", { $0.popAllValueFields() }, expect: "**")
testPath2Path("s0.e2.3.c4.s1.e2.v**.**", { $0.popLastClassAndValuesFromTail() }, expect: "s0.e2.3.c4.s1.e2.v**.**")
testPath2Path("s0.c2.3.c4.s1", { $0.popLastClassAndValuesFromTail() }, expect: "s0.c2.3")
testPath2Path("v**.c*.s1", { $0.popLastClassAndValuesFromTail() }, expect: "v**")
testPath2Path("s1.ct.v**", { $0.popLastClassAndValuesFromTail() }, expect: "s1")
testPath2Path("c0.c1.c2", { $0.popLastClassAndValuesFromTail() }, expect: "c0.c1")
testPath2Path("**", { $0.popLastClassAndValuesFromTail() }, expect: "**")
testPath2Path("v**.c3", { $0.popIfMatches(.anyValueFields) }, expect: "v**.c3")
testPath2Path("**", { $0.popIfMatches(.anyValueFields) }, expect: "**")
testPath2Path("s0.c3", { $0.popIfMatches(.anyValueFields) }, expect: nil)
testPath2Path("c0.s3", { $0.popIfMatches(.anyClassField) }, expect: nil)
testPath2Path("**", { $0.popIfMatches(.anyClassField) }, expect: "**")
testPath2Path("c*.e3", { $0.popIfMatches(.anyClassField) }, expect: "e3")
}
func testPath2Path(_ pathStr: String, _ transform: (SmallProjectionPath) -> SmallProjectionPath?, expect: String?) {
var parser = StringParser(pathStr)
let path = try! parser.parseProjectionPathFromSIL()
let result = transform(path)
if let expect = expect {
var expectParser = StringParser(expect)
let expectPath = try! expectParser.parseProjectionPathFromSIL()
assert(result == expectPath)
} else {
assert(result == nil)
}
}
}
}
| 0efb687dc056ff1fcb7bf9b7a56f989a | 38.377717 | 146 | 0.575495 | false | true | false | false |
mibaldi/ChildBeaconApp | refs/heads/publish | ChildBeaconProject/Models/Beacon.swift | apache-2.0 | 1 | //
// KidBeacon
// Creado por Mikel Balduciel Diaz, Eduardo González de la Huebra Sánchez y David Jiménez Guinaldo en 2016
// para el Club Universitario de Innovación de la Universidad Pontificia de Salamanca.
// Copyright © 2016. Todos los derecho reservados.
//
import Foundation
import CoreLocation
class Beacon : NSObject{
var beaconId = Int64()
var beaconGroupId = Int64()
var name = String ()
var minor = String()
var major = String()
var distance = Float()
var beaconGroupUUID = String()
dynamic var lastSeenBeacon: CLBeacon?
override
var hashValue: Int {
get {
return beaconId.hashValue << 15 + name.hashValue
}
}
static func addBeacon(name: String,minor: String,major: String,group: Int64,groupUUID:String) throws -> Void{
let beacon = Beacon()
beacon.name = name
beacon.beaconGroupId = group
beacon.minor = minor
beacon.major = major
beacon.beaconGroupUUID = groupUUID
do{
try BeaconDataHelper.insert(beacon)
} catch{
throw DataAccessError.Insert_Error
}
}
static func updateBeacon(id : Int64, name: String,minor: String,major: String) throws -> Void{
let beacon = Beacon()
beacon.beaconId = id
beacon.name = name
beacon.minor = minor
beacon.major = major
do{
try BeaconDataHelper.updateBeacon(beacon)
} catch{
throw DataAccessError.Insert_Error
}
}
static func deleteBeacon(id : Int64) throws -> Void{
let beacon = Beacon()
beacon.beaconId = id
do{
try BeaconDataHelper.delete(beacon)
} catch{
throw DataAccessError.Delete_Error
}
}
}
func ==(item: Beacon, beacon: CLBeacon) -> Bool {
return ((beacon.proximityUUID.UUIDString == item.beaconGroupUUID)
&& (Int(beacon.major) == Int(item.major))
&& (Int(beacon.minor) == Int(item.minor)))
}
func ==(lhs: Beacon, rhs: Beacon) -> Bool {
return (lhs.beaconId == rhs.beaconId)
&& (lhs.name == rhs.name)
&& (Int(lhs.minor) == Int(rhs.minor))
&& (Int(lhs.major) == Int(rhs.major))
}
| 66e9779d91de615f66b9b7510762bdb6 | 28.75 | 113 | 0.598408 | false | false | false | false |
Roommate-App/roomy | refs/heads/master | News/Pods/IBAnimatable/Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallGridPulse.swift | mit | 2 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallGridPulse: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let timingFunction: TimingFunctionType = .default
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations: [CFTimeInterval] = [0.72, 1.02, 1.28, 1.42, 1.45, 1.18, 0.87, 1.45, 1.06]
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [-0.06, 0.25, -0.17, 0.48, 0.31, 0.03, 0.46, 0.78, 0.45]
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallGridPulse {
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctionsType = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.5, 1]
return scaleAnimation
}
var opacityAnimation: CAKeyframeAnimation {
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 0.5, 1]
opacityAnimation.timingFunctionsType = [timingFunction, timingFunction]
opacityAnimation.values = [1, 0.7, 1]
return opacityAnimation
}
}
| c07500a46f875042358d4ba16ab9e6a0 | 33.763889 | 127 | 0.669996 | false | false | false | false |
JGiola/swift-package-manager | refs/heads/master | Tests/FunctionalTests/ToolsVersionTests.swift | apache-2.0 | 2 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import Utility
import TestSupport
import Commands
import PackageModel
import SourceControl
import Workspace
class ToolsVersionTests: XCTestCase {
func testToolsVersion() throws {
mktmpdir { path in
let fs = localFileSystem
// Create a repo for the dependency to test against.
let depPath = path.appending(component: "Dep")
try fs.createDirectory(depPath)
initGitRepo(depPath)
let repo = GitRepository(path: depPath)
try fs.writeFileContents(depPath.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Dep",
products: [
.library(name: "Dep", targets: ["Dep"]),
],
targets: [
.target(name: "Dep", path: "./")
]
)
"""
}
try fs.writeFileContents(depPath.appending(component: "foo.swift")) {
$0 <<< """
public func foo() { print("[email protected]") }
"""
}
// v1.
try repo.stageEverything()
try repo.commit(message: "Initial")
try repo.tag(name: "1.0.0")
// v1.0.1
_ = try SwiftPMProduct.SwiftPackage.execute(
["tools-version", "--set", "10000.1"], packagePath: depPath)
try fs.writeFileContents(depPath.appending(component: "foo.swift")) {
$0 <<< """
public func foo() { print("[email protected]") }
"""
}
try repo.stageEverything()
try repo.commit(message: "1.0.1")
try repo.tag(name: "1.0.1")
// Create the primary repository.
let primaryPath = path.appending(component: "Primary")
try fs.writeFileContents(primaryPath.appending(component: "Package.swift")) {
$0 <<< """
import PackageDescription
let package = Package(
name: "Primary",
dependencies: [.package(url: "../Dep", from: "1.0.0")],
targets: [.target(name: "Primary", dependencies: ["Dep"], path: ".")]
)
"""
}
// Create a file.
try fs.writeFileContents(primaryPath.appending(component: "main.swift")) {
$0 <<< """
import Dep
Dep.foo()
"""
}
_ = try SwiftPMProduct.SwiftPackage.execute(
["tools-version", "--set", "4.0"], packagePath: primaryPath).spm_chomp()
// Build the primary package.
_ = try SwiftPMProduct.SwiftBuild.execute([], packagePath: primaryPath)
let exe = primaryPath.appending(components: ".build", Destination.host.target, "debug", "Primary").asString
// v1 should get selected because v1.0.1 depends on a (way) higher set of tools.
XCTAssertEqual(try Process.checkNonZeroExit(args: exe).spm_chomp(), "[email protected]")
// Set the tools version to something high.
_ = try SwiftPMProduct.SwiftPackage.execute(
["tools-version", "--set", "10000.1"], packagePath: primaryPath).spm_chomp()
do {
_ = try SwiftPMProduct.SwiftBuild.execute([], packagePath: primaryPath)
XCTFail()
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssert(stderr.contains("is using Swift tools version 10000.1.0 but the installed version is 5.0.0"), stderr)
}
// Write the manifest with incompatible sources.
try fs.writeFileContents(primaryPath.appending(component: "Package.swift")) {
$0 <<< """
import PackageDescription
let package = Package(
name: "Primary",
dependencies: [.package(url: "../Dep", from: "1.0.0")],
targets: [.target(name: "Primary", dependencies: ["Dep"], path: ".")],
swiftLanguageVersions: [1000])
"""
}
_ = try SwiftPMProduct.SwiftPackage.execute(
["tools-version", "--set", "4.0"], packagePath: primaryPath).spm_chomp()
do {
_ = try SwiftPMProduct.SwiftBuild.execute([], packagePath: primaryPath)
XCTFail()
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTAssertTrue(stderr.contains("package 'Primary' requires minimum Swift language version 1000 which is not supported by the current tools version (5.0.0)"), stderr)
}
try fs.writeFileContents(primaryPath.appending(component: "Package.swift")) {
$0 <<< """
import PackageDescription
let package = Package(
name: "Primary",
dependencies: [.package(url: "../Dep", from: "1.0.0")],
targets: [.target(name: "Primary", dependencies: ["Dep"], path: ".")],
swiftLanguageVersions: [\(ToolsVersion.currentToolsVersion.major), 1000])
"""
}
_ = try SwiftPMProduct.SwiftPackage.execute(
["tools-version", "--set", "4.0"], packagePath: primaryPath).spm_chomp()
_ = try SwiftPMProduct.SwiftBuild.execute([], packagePath: primaryPath)
}
}
}
| affa46314e1b00462fe394108e4b47b3 | 41.875862 | 180 | 0.510375 | false | false | false | false |
qualaroo/QualarooSDKiOS | refs/heads/master | QualarooTests/Model/QuestionModelSpec.swift | mit | 1 | //
// QuestionModelSpec.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class QuestionModelSpec: QuickSpec {
override func spec() {
super.spec()
describe("questions initializations") {
context("equatable") {
it("is equal to another question with same proporties") {
let first = QuestionFactory(with: JsonLibrary.question(id: 1, type: "text", title: "title"))
let second = QuestionFactory(with: JsonLibrary.question(id: 1, type: "text", title: "title"))
let firstQuestion = try! first.build()
let secondQuestion = try! second.build()
expect(firstQuestion).to(equal(secondQuestion))
}
it("is not equal to another question with different type") {
let first = JsonLibrary.question(id: 1, type: "radio", answerList: [JsonLibrary.answer()])
let second = JsonLibrary.question(id: 1, type: "checkbox", answerList: [JsonLibrary.answer()])
let firstQuestion = try! QuestionFactory(with: first).build()
let secondQuestion = try! QuestionFactory(with: second).build()
expect(firstQuestion).notTo(equal(secondQuestion))
}
it("is not equal to another question with different Id") {
let first = QuestionFactory(with: JsonLibrary.question(id: 1, type: "text", title: "title"))
let second = QuestionFactory(with: JsonLibrary.question(id: 2, type: "text", title: "title"))
let firstQuestion = try! first.build()
let secondQuestion = try! second.build()
expect(firstQuestion).notTo(equal(secondQuestion))
}
}
context("radio question") {
it("is created from good dictionary") {
let first = JsonLibrary.answer(id: 999768,
title: "Very disappointed",
nextMap: ["id": 345691,
"node_type": "question"])
let second = JsonLibrary.answer(id: 999769,
title: "Somewhat disappointed",
nextMap: ["id": 345691,
"node_type": "question"])
let third = JsonLibrary.answer(id: 999770,
title: "Not disappointed",
nextMap: ["id": 345691,
"node_type": "question"])
let answersDict = [first, second, third]
let dict = JsonLibrary.question(id: 352640,
type: "radio",
title: "Title",
description: "Description",
answerList: answersDict,
disableRandom: true)
let answerList = [try! AnswerFactory(with: first).build(),
try! AnswerFactory(with: second).build(),
try! AnswerFactory(with: third).build()]
let question = try! QuestionFactory(with: dict).build()
expect(question.answerList).to(haveCount(3))
expect(question.answerList).to(equal(answerList))
expect(question.title).to(equal("Title"))
expect(question.type).to(equal(Question.Category.radio))
expect(question.description).to(equal("Description"))
expect(question.nextNodeId).to(beNil())
}
it("is not created from dictionary without title") {
var badQuestion = JsonLibrary.question(id: 345691, type: "radio")
badQuestion["title"] = NSNull()
let factory = QuestionFactory(with: badQuestion)
expect { try factory.build() }.to(throwError())
}
it("is not created from dictionary without id") {
var badQuestion = JsonLibrary.question(type: "radio")
badQuestion["id"] = NSNull()
let factory = QuestionFactory(with: badQuestion)
expect { try factory.build() }.to(throwError())
}
it("is not created from dictionary with string id type") {
var badQuestion = JsonLibrary.question(type: "radio")
badQuestion["id"] = "text"
let factory = QuestionFactory(with: badQuestion)
expect { try factory.build() }.to(throwError())
}
it("is not created if there is no answers") {
var badQuestion = JsonLibrary.question(type: "radio")
badQuestion["answer_list"] = [[:]]
let factory = QuestionFactory(with: badQuestion)
expect { try factory.build() }.to(throwError())
}
}
context("description placement") {
it("should place description before title") {
var dict = JsonLibrary.question(description: "description")
dict["description_placement"] = "before"
let question = try! QuestionFactory(with: dict).build()
let placement = question.descriptionPlacement
expect(placement).to(equal(Question.DescriptionPlacement.before))
}
it("should place description after title") {
var dict = JsonLibrary.question(description: "description")
dict["description_placement"] = "after"
let question = try! QuestionFactory(with: dict).build()
let placement = question.descriptionPlacement
expect(placement).to(equal(Question.DescriptionPlacement.after))
}
it("should place description after title if not specified") {
var dict = JsonLibrary.question(description: "description")
dict["description_placement"] = NSNull()
let question = try! QuestionFactory(with: dict).build()
let placement = question.descriptionPlacement
expect(placement).to(equal(Question.DescriptionPlacement.after))
}
}
context("anchor last answers") {
it("should randomize question order") {
let answerList = [JsonLibrary.answer(id: 1),
JsonLibrary.answer(id: 2),
JsonLibrary.answer(id: 3),
JsonLibrary.answer(id: 4)]
let dict = JsonLibrary.question(type: "radio",
answerList: answerList,
disableRandom: false,
anchorLast: false)
let question = try! QuestionFactory(with: dict,
listRandomizer: ListRandomizerMock()).build()
expect(question.answerList).to(haveCount(4))
let answersOrder = question.answerList.map({ $0.answerId })
expect(answersOrder).notTo(equal([1, 2, 3, 4]))
}
it("should anchor last one answer if only anchorLast present") {
let answerList = [JsonLibrary.answer(id: 1),
JsonLibrary.answer(id: 2),
JsonLibrary.answer(id: 3),
JsonLibrary.answer(id: 4)]
let dict = JsonLibrary.question(type: "radio",
answerList: answerList,
disableRandom: false,
anchorLast: true)
let question = try! QuestionFactory(with: dict,
listRandomizer: ListRandomizerMock()).build()
let lastAnswerId = question.answerList.last!.answerId
expect(lastAnswerId).to(equal(4))
let answersOrder = question.answerList.map({ $0.answerId })
expect(answersOrder).notTo(equal([1, 2, 3, 4]))
}
it("should anchor last three answers") {
let answerList = [JsonLibrary.answer(id: 1),
JsonLibrary.answer(id: 2),
JsonLibrary.answer(id: 3),
JsonLibrary.answer(id: 4),
JsonLibrary.answer(id: 5)]
var dict = JsonLibrary.question(type: "radio",
answerList: answerList,
disableRandom: false,
anchorLast: true)
dict["anchor_last_count"] = 3
let question = try! QuestionFactory(with: dict,
listRandomizer: ListRandomizerMock()).build()
let answersOrder = question.answerList.map({ $0.answerId })
expect(answersOrder).notTo(equal([1, 2, 3, 4, 5]))
let lastThreeOrder = Array(answersOrder.suffix(3))
expect(lastThreeOrder).to(equal([3, 4, 5]))
}
it("should always be required if radio, nps and dropdown type") {
let answers = Array(repeating: JsonLibrary.answer(), count: 11)
var dict = JsonLibrary.question(type: "radio",
answerList: answers)
dict["is_required"] = NSNull()
var question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beTrue())
dict["type"] = "nps"
dict["nps_min_label"] = ""
dict["nps_max_label"] = ""
question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beTrue())
dict["type"] = "dropdown"
question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beTrue())
}
it("shouldn't preset required for text type") {
var dict = JsonLibrary.question(type: "text")
var question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beFalse())
dict["is_required"] = true
question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beTrue())
}
it("shouldn't preset required for checkbox type") {
var dict = JsonLibrary.question(type: "checkbox", answerList: [JsonLibrary.answer()])
var question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beFalse())
dict["is_required"] = true
question = try! QuestionFactory(with: dict).build()
expect(question.isRequired).to(beTrue())
}
}
context("checkbox question") {
it("has min and max answer count") {
let answers = Array(repeating: JsonLibrary.answer(), count: 5)
var goodQuestion = JsonLibrary.question(id: 1, type: "checkbox", answerList: answers)
goodQuestion["min_answers_count"] = 2
goodQuestion["max_answers_count"] = 3
let question = try! QuestionFactory(with: goodQuestion).build()
expect(question.minAnswersCount).to(equal(2))
expect(question.maxAnswersCount).to(equal(3))
}
it("have backward compatibility with min and max answer count") {
let answers = Array(repeating: JsonLibrary.answer(), count: 5)
let goodQuestion = JsonLibrary.question(id: 1, type: "checkbox", answerList: answers)
let question = try! QuestionFactory(with: goodQuestion).build()
expect(question.minAnswersCount).to(equal(0))
expect(question.maxAnswersCount).to(equal(5))
}
it("interfeere min answer count from isRequired param") {
let answers = Array(repeating: JsonLibrary.answer(), count: 5)
var goodQuestion = JsonLibrary.question(id: 1, type: "checkbox", answerList: answers)
goodQuestion["is_required"] = true
let question = try! QuestionFactory(with: goodQuestion).build()
expect(question.minAnswersCount).to(equal(1))
}
}
context("nps question") {
it("is created from good dictionary") {
let answers = Array(repeating: JsonLibrary.answer(), count: 11)
var goodQuestion = JsonLibrary.question(id: 345691,
type: "nps",
title: "Title",
description: "Description",
answerList: answers)
goodQuestion["nps_min_label"] = "Poor"
goodQuestion["nps_max_label"] = "Awesome"
goodQuestion["next_map"] = ["id": 123123]
let question = try! QuestionFactory(with: goodQuestion).build()
expect(question.answerList).to(haveCount(11))
expect(question.title).to(equal("Title"))
expect(question.type).to(equal(Question.Category.nps))
expect(question.description).to(equal("Description"))
expect(question.nextNodeId).to(equal(123123))
expect(question.npsMinText!).to(equal("Poor"))
expect(question.npsMaxText!).to(equal("Awesome"))
}
it("throws error if there is no min or max nps description") {
let answers = Array(repeating: JsonLibrary.answer(), count: 11)
var badQuestion = JsonLibrary.question(type: "nps",
answerList: answers)
badQuestion["nps_min_label"] = NSNull()
badQuestion["nps_max_label"] = "Awesome"
badQuestion["next_map"] = ["id": 123123]
let noMinNps = QuestionFactory(with: badQuestion)
expect { try noMinNps.build() }.to(throwError())
badQuestion["nps_min_label"] = "Poor"
badQuestion["nps_max_label"] = NSNull()
let noMaxNps = QuestionFactory(with: badQuestion)
expect { try noMaxNps.build() }.to(throwError())
}
it("throws error if the number of answers isn't 11") {
let answers = Array(repeating: JsonLibrary.answer(), count: 9)
var badQuestion = JsonLibrary.question(type: "nps",
answerList: answers)
badQuestion["nps_min_label"] = "Poor"
badQuestion["nps_max_label"] = "Awesome"
badQuestion["next_map"] = ["id": 123123]
let factory = QuestionFactory(with: badQuestion)
expect { try factory.build() }.to(throwError())
}
}
context("wrong questions") {
it("throws error with unknown type") {
let badQuestion = JsonLibrary.question(type: "unknown")
let factory = QuestionFactory(with: badQuestion)
expect { try factory.build() }.to(throwError())
}
}
}
}
}
| 06663c6f6db7f8c455be9d046237cb27 | 50.65625 | 104 | 0.552665 | false | false | false | false |
zmian/xcore.swift | refs/heads/main | Sources/Xcore/SwiftUI/Components/Pond/Variants/Pond+UserDefaults.swift | mit | 1 | //
// Xcore
// Copyright © 2021 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
public struct UserDefaultsPond: Pond {
private let userDefaults: UserDefaults
public init(_ userDefaults: UserDefaults = .standard) {
self.userDefaults = userDefaults
}
public func get<T>(_ type: T.Type, _ key: Key) -> T? {
switch T.self {
case is Data.Type, is Optional<Data>.Type:
return userDefaults.object(forKey: key.id) as? T
default:
if Mirror.isCollection(T.self) {
return userDefaults.object(forKey: key.id) as? T
} else {
return StringConverter(userDefaults.string(forKey: key.id))?.get(type)
}
}
}
public func set<T>(_ key: Key, value: T?) {
if value == nil {
remove(key)
} else if let value = value as? Data {
userDefaults.set(value, forKey: key.id)
} else if let value = StringConverter(value)?.get(String.self) {
userDefaults.set(value, forKey: key.id)
} else if let value = value, Mirror.isCollection(value) {
userDefaults.set(value, forKey: key.id)
} else {
#if DEBUG
fatalError("Unable to save value for \(key.id): \(String(describing: value))")
#endif
}
}
public func remove(_ key: Key) {
userDefaults.removeObject(forKey: key.id)
}
public func contains(_ key: Key) -> Bool {
userDefaults.object(forKey: key.id) != nil
}
}
// MARK: - Dot Syntax Support
extension Pond where Self == UserDefaultsPond {
/// Returns standard `UserDefaults` variant of `Pond`.
public static var userDefaults: Self {
.init()
}
/// Returns `UserDefaults` variant of `Pond`.
public static func userDefaults(_ userDefaults: UserDefaults) -> Self {
.init(userDefaults)
}
}
| f6c5864c5f8e999306b3c22d41e66fc7 | 28.742424 | 90 | 0.57514 | false | false | false | false |
22377832/ccyswift | refs/heads/master | FetchResultsController/FetchResultsController/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// FetchResultsController
//
// Created by sks on 17/2/24.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "FetchResultsController")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 61d5655e60bb2f75b16474d4af3f631d | 48.505376 | 285 | 0.687011 | false | false | false | false |
gustavoavena/MOPT | refs/heads/master | MOPT/UserServices.swift | mit | 1 | //
// UserServices.swift
// MOPT
//
// Created by Gustavo Avena on 31/03/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import UIKit
import CloudKit
import FBSDKLoginKit
class UserServices: NSObject {
//fetching user's facebook information
func fetchFacebookUserInfo(completionHandler:@escaping ([String:Any]?, Error?) -> Void) {
//getting id, name and email informations from user's facebook
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"]).start {
(connection, result, error) in
guard error == nil && result != nil else {
print("error fetching user's facebook information")
return
}
let userInfo = (result as? [String:Any])
completionHandler(userInfo, error)
}
}
// public func getUserRecordFromEmail(email: String, completionHandler: @escaping (CKRecord?, Error?) -> Void) {
// let predicate = NSPredicate(format: "email == %@", email)
// let query = CKQuery(recordType: "User", predicate: predicate)
//
// self.ckHandler.publicDB.perform(query, inZoneWith: nil) {
// (results, error) in
//
// guard error == nil && results != nil else {
// print("error getting user record by email.")
// return
// }
//
// let records = results!
//
// if records.count > 0 {
// completionHandler(records[0], nil)
// } else {
// completionHandler(nil, QueryError.UserByEmail)
// }
//
// }
//
//
// }
func getCurrentUserRecordID(completionHandler: @escaping (CKRecordID?, Error?) -> Void) {
fetchFacebookUserInfo {
(userInfo, error) in
guard error == nil && userInfo != nil else {
print("error getting current user CK Record ID")
return
}
let userID = CKRecordID(recordName: userInfo?["id"] as! String)
completionHandler(userID, error)
}
}
func downloadImage(imageURL: URL, userID: ObjectID) {
print("Download of \(imageURL) started")
var urlStr = imageURL.absoluteString
urlStr = urlStr.replacingOccurrences(of: "http", with: "https")
let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileName = documentsDirectory.appendingPathComponent(String(format: "%@ProfilePicture.jpg", userID))
let request = URLRequest(url: URL(string: urlStr)!)
URLSession.shared.dataTask(with: request) {
(data, response, error) in
guard let data = data, error == nil else {
print("Error downloading user profile picture -> \(String(describing: error?.localizedDescription))")
// completionHandler(nil, error)
return
}
DispatchQueue.main.async {
do {
try data.write(to: fileName)
print("User \(userID)'s profile picture saved successfully")
}
catch {
print("Error when trying to save profile picture")
return
}
// completionHandler(UIImage(data: data), nil)
}
print("Download of \(imageURL) finished")
}.resume()
}
}
| 6348d2d6725247da1e477485a274c10d | 29.59322 | 137 | 0.546814 | false | false | false | false |
tutsplus/ODR-Introduction-Starter | refs/heads/master | ODR Introduction/ShapeTableViewController.swift | bsd-2-clause | 3 | //
// ShapeTableViewController.swift
// ODR Introduction
//
// Created by Davis Allie on 26/09/2015.
// Copyright © 2015 tutsplus. All rights reserved.
//
import UIKit
class ShapeTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Shapes"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UITableViewCell, let tag = cell.textLabel?.text where validTags.contains(tag) {
if let detail = segue.destinationViewController as? DetailViewController {
detail.navigationItem.title = tag
detail.tagToLoad = tag
}
}
}
}
| e70958742c96869732c738a34d6bdbc0 | 30.549451 | 157 | 0.668757 | false | false | false | false |
mikaoj/BSImagePicker | refs/heads/master | Sources/Scene/Assets/CameraCollectionViewCell.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
/**
*/
final class CameraCollectionViewCell: UICollectionViewCell {
static let identifier = "cameraCellIdentifier"
let imageView: UIImageView = UIImageView(frame: .zero)
let cameraBackground: UIView = UIView(frame: .zero)
var takePhotoIcon: UIImage? {
didSet {
imageView.image = takePhotoIcon
// Apply tint to image
imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
}
}
var session: AVCaptureSession?
var captureLayer: AVCaptureVideoPreviewLayer?
let sessionQueue = DispatchQueue(label: "AVCaptureVideoPreviewLayer", attributes: [])
override init(frame: CGRect) {
super.init(frame: frame)
cameraBackground.frame = contentView.bounds
cameraBackground.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.addSubview(cameraBackground)
imageView.frame = contentView.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.contentMode = .center
contentView.addSubview(imageView)
// TODO: Check settings if live view is enabled
setupCaptureLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
captureLayer?.frame = bounds
}
func startLiveBackground() {
sessionQueue.async { () -> Void in
self.session?.startRunning()
}
}
func stopLiveBackground() {
sessionQueue.async { () -> Void in
self.session?.stopRunning()
}
}
private func setupCaptureLayer() {
// Don't trigger camera access for the background
guard AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized else {
return
}
do {
// Prepare avcapture session
session = AVCaptureSession()
session?.sessionPreset = AVCaptureSession.Preset.medium
// Hook upp device
let device = AVCaptureDevice.default(for: AVMediaType.video)
let input = try AVCaptureDeviceInput(device: device!)
session?.addInput(input)
// Setup capture layer
guard session != nil else {
return
}
let captureLayer = AVCaptureVideoPreviewLayer(session: session!)
captureLayer.frame = bounds
captureLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
cameraBackground.layer.addSublayer(captureLayer)
self.captureLayer = captureLayer
} catch {
session = nil
}
}
}
| 56e1f179b0633f2b6ee08195396f9eaf | 33.112069 | 95 | 0.662118 | false | false | false | false |
SAP/IssieBoard | refs/heads/master | ConfigurableKeyboard/StandardKeyboard.swift | apache-2.0 | 1 | //
// KeyboardView.swift
// EducKeyboard
//
// Created by Bezalel, Orit on 2/27/15.
// Copyright (c) 2015 sap. All rights reserved.
//
import UIKit
import Foundation
func standardKeyboard() -> Keyboard {
let customCharSetOne : String = "פםןףךלץתצ"
let customCharSetTwo : String = "וטאחיעמנה"
let customCharSetThree : String = "רקכגדשבסז,."
var visibleKeys : String = Settings.sharedInstance.visibleKeys
if(visibleKeys.isEmptyOrWhiteSpace)
{
visibleKeys = Settings.sharedInstance.allCharsInKeyboard
}
let standardKeyboard = Keyboard()
for key in [ ",", ".", "ק", "ר", "א", "ט", "ו", "ן", "ם", "פ"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(0)
standardKeyboard.addKey(keyModel, row: 0, page: 0)
}
var backspace = Key(.Backspace)
backspace.setPage(0)
standardKeyboard.addKey(backspace, row: 0, page: 0)
for key in ["ש", "ד", "ג", "כ", "ע", "י", "ח", "ל", "ך", "ף"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(0)
standardKeyboard.addKey(keyModel, row: 1, page: 0)
}
for key in [ "ז", "ס", "ב", "ה", "נ", "מ", "צ", "ת", "ץ"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(0)
standardKeyboard.addKey(keyModel, row: 2, page: 0)
}
var returnKey = Key(.Return)
returnKey.setKeyOutput("\n")
returnKey.setPage(0)
standardKeyboard.addKey(returnKey, row: 1, page: 0)
var keyModeChangeNumbers = Key(.ModeChange)
keyModeChangeNumbers.setKeyTitle(".?123")
keyModeChangeNumbers.toMode = 1
keyModeChangeNumbers.setPage(0)
standardKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
var keyboardChange = Key(.KeyboardChange)
keyboardChange.setPage(0)
standardKeyboard.addKey(keyboardChange, row: 3, page: 0)
var space = Key(.Space)
space.setKeyTitle("רווח")
space.setKeyOutput(" ")
space.setPage(0)
standardKeyboard.addKey(space, row: 3, page: 0)
standardKeyboard.addKey(Key(keyModeChangeNumbers), row: 3, page: 0)
var dismissKeyboard = Key(.DismissKeyboard)
dismissKeyboard.setPage(0)
standardKeyboard.addKey(dismissKeyboard, row: 3, page: 0)
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(1)
standardKeyboard.addKey(keyModel, row: 0, page: 1)
}
backspace = Key(backspace)
backspace.setPage(1)
standardKeyboard.addKey(backspace, row: 0, page: 1)
for key in ["-", "/", ":", ";", "(", ")","₪", "&", "@"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(1)
standardKeyboard.addKey(keyModel, row: 1, page: 1)
}
returnKey = Key(returnKey)
returnKey.setPage(1)
standardKeyboard.addKey(returnKey, row: 1, page: 1)
let keyModeChangeSpecialCharacters = Key(.ModeChange)
keyModeChangeSpecialCharacters.setKeyTitle("#+=")
keyModeChangeSpecialCharacters.toMode = 2
keyModeChangeSpecialCharacters.setPage(1)
standardKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1)
let undoKey = Key(.Undo)
undoKey.setKeyTitle("בטל")
undoKey.setPage(1)
standardKeyboard.addKey(undoKey, row: 2, page: 1)
for key in [".", ",", "?", "!", "'", "\""] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(1)
standardKeyboard.addKey(keyModel, row: 2, page: 1)
}
standardKeyboard.addKey(Key(keyModeChangeSpecialCharacters), row: 2, page: 1)
var keyModeChangeLetters = Key(.ModeChange)
keyModeChangeLetters.setKeyTitle("אבג")
keyModeChangeLetters.toMode = 0
keyModeChangeLetters.setPage(1)
standardKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
keyboardChange = Key(keyboardChange)
keyboardChange.setPage(1)
standardKeyboard.addKey(keyboardChange, row: 3, page: 1)
space = Key(space)
space.setPage(1)
standardKeyboard.addKey(space, row: 3, page: 1)
standardKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 1)
//orit: add output
dismissKeyboard = Key(dismissKeyboard)
dismissKeyboard.setPage(1)
standardKeyboard.addKey(dismissKeyboard, row: 3, page: 1)
for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(2)
standardKeyboard.addKey(keyModel, row: 0, page: 2)
}
backspace = Key(backspace)
backspace.setPage(2)
standardKeyboard.addKey(backspace, row: 0, page: 2)
for key in ["_", "\\", "|", "~", "<", ">", "$", "€", "£"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(2)
standardKeyboard.addKey(keyModel, row: 1, page: 2)
}
returnKey = Key(returnKey)
returnKey.setPage(2)
standardKeyboard.addKey(returnKey, row: 1, page: 2)
keyModeChangeNumbers = Key(keyModeChangeNumbers)
keyModeChangeNumbers.setPage(2)
standardKeyboard.addKey(keyModeChangeNumbers, row: 2, page: 2)
let restoreKey = Key(.Restore)
restoreKey.setKeyTitle("שחזר")
restoreKey.setPage(2)
standardKeyboard.addKey(restoreKey, row: 2, page: 2)
for key in [".", ",", "?", "!", "'", "•"] {
var keyModel : Key
if (visibleKeys.rangeOfString(key) == nil) {
keyModel = Key (.HiddenKey)
}
else if (customCharSetOne.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetOne)
}
else if (customCharSetTwo.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetTwo)
}
else if (customCharSetThree.rangeOfString(key) != nil) {
keyModel = Key(.CustomCharSetThree)
}
else {
keyModel = Key(.Character)
}
keyModel.setKeyTitle(key)
keyModel.setKeyOutput(key)
keyModel.setPage(2)
standardKeyboard.addKey(keyModel, row: 2, page: 2)
}
standardKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
keyModeChangeLetters = Key(keyModeChangeLetters)
keyModeChangeLetters.setPage(2)
standardKeyboard.addKey(keyModeChangeLetters,row: 3, page: 2)
keyboardChange = Key(keyboardChange)
keyboardChange.setPage(2)
standardKeyboard.addKey(keyboardChange, row: 3, page: 2)
space = Key(space)
space.setPage(2)
standardKeyboard.addKey(space, row: 3, page: 2)
standardKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
dismissKeyboard = Key(dismissKeyboard)
dismissKeyboard.setPage(2)
standardKeyboard.addKey(Key(dismissKeyboard), row: 3, page: 2)
return standardKeyboard
}
| a1d055b1f7a24e4357b4a63e7539e2b3 | 30.55163 | 81 | 0.582465 | false | false | false | false |
bubnov/SBTableViewAdapter | refs/heads/master | TableViewAdapter/TableViewAdapter.swift | mit | 2 | //
// TableViewAdapter.swift
// Collections
//
// Created by Bubnov Slavik on 02/03/2017.
// Copyright © 2017 Bubnov Slavik. All rights reserved.
//
import UIKit
public class TableViewAdapter: NSObject, UITableViewDataSource, UITableViewDelegate, CollectionViewAdapterType, ReloadableAdapterType {
//MARK: - Public
public var sections: [CollectionSectionType] = []
public var mappers: [AbstractMapper] = []
public var selectionHandler: ((CollectionItemType) -> Void)?
public var accessoryButtonHandler: ((CollectionItemType) -> Void)?
public var logger: ((String) -> Void)?
public func assign(to view: UIView) {
guard let view = view as? UITableView else { fatalError("UITableView is expected") }
tableView = view
view.delegate = self
view.dataSource = self
view.estimatedSectionHeaderHeight = 10
view.estimatedSectionFooterHeight = 10
view.estimatedRowHeight = 44
view.sectionHeaderHeight = UITableViewAutomaticDimension
view.sectionFooterHeight = UITableViewAutomaticDimension
view.rowHeight = UITableViewAutomaticDimension
view.reloadData()
view.reloadSections(
NSIndexSet(indexesIn: NSMakeRange(0, view.dataSource!.numberOfSections!(in: view))) as IndexSet,
with: .automatic
)
tableViewPositionManager = TableViewPositionManager(
tableView: view,
idResolver: { [weak self] indexPath in
return self?._item(atIndexPath: indexPath)?.uid
},
indexPathResolver: { [weak self] id -> IndexPath? in
for section in (self?.sections ?? []).enumerated() {
for item in (section.element.items ?? []).enumerated() {
if item.element.uid == id {
return IndexPath(row: item.offset, section: section.offset)
}
}
}
return nil
}
)
tableViewPositionManager.logger = logger
}
//MARK: - ReloadableAdapterType
internal func reloadAll() {
tableViewPositionManager.keepPosition {
tableView?.reloadData()
}
}
internal func reloadItem(at index: Int, section: Int, animation: UITableViewRowAnimation? = nil) {
guard let tableView = tableView, section < tableView.numberOfSections, index < tableView.numberOfRows(inSection: section) else { return }
tableViewPositionManager.keepPosition {
if _UIAndDataAreDesynchronized() {
tableView.reloadData()
}
else {
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: index, section: section)], with: animation ?? .automatic)
tableView.endUpdates()
}
}
}
internal func reloadSection(at index: Int, animation: UITableViewRowAnimation? = nil) {
guard let tableView = tableView, index < tableView.numberOfSections else { return }
tableViewPositionManager.keepPosition {
if _UIAndDataAreDesynchronized() {
tableView.reloadData()
}
else {
tableView.beginUpdates()
tableView.reloadSections(IndexSet(integer: index), with: animation ?? .automatic)
tableView.endUpdates()
}
}
}
//MARK: - Private
private weak var tableView: UITableView?
private var registeredIds: [String] = []
private var tableViewPositionManager: TableViewPositionManagerType!
private enum ViewType {
case Item, Header, Footer
}
private func _UIAndDataAreDesynchronized() -> Bool {
guard let tableView = tableView else { return true }
for sectionInfo in sections.enumerated() {
if let items = sectionInfo.element.items, items.count != tableView.numberOfRows(inSection: sectionInfo.offset) {
return true
}
}
return false
}
private func _section(atIndex index: Int) -> CollectionSectionType? {
guard (0..<sections.count).contains(index) else { return nil }
let section = sections[index]
if let internalSection = section as? InternalCollectionSectionType {
internalSection._index = index
internalSection._adapter = self
}
return section
}
private func _section(atIndexPath indexPath: IndexPath) -> CollectionSectionType? {
return _section(atIndex: indexPath.section)
}
private func _header(atIndex index: Int) -> CollectionItemType? {
return _item(atIndexPath: IndexPath(item: 0, section: index), viewType: .Header)
}
private func _footer(atIndex index: Int) -> CollectionItemType? {
return _item(atIndexPath: IndexPath(item: 0, section: index), viewType: .Footer)
}
private func _item(atIndexPath indexPath: IndexPath, viewType: ViewType? = .Item) -> CollectionItemType? {
guard let section = _section(atIndexPath: indexPath) else { return nil }
var item: CollectionItemType?
switch viewType! {
case .Item:
if indexPath.item < section.items?.count ?? 0 {
item = section.items?[indexPath.item]
} else if section.dynamicItemMapper != nil {
item = Item(value: indexPath.row, mapper: section.dynamicItemMapper)
}
case .Header:
item = section.header
case .Footer:
item = section.footer
}
guard item != nil else { return nil }
if let internalItem = item as? InternalCollectionItemType {
internalItem._index = indexPath.item
internalItem._section = section as? ReloadableSectionType
}
if item!.mapper == nil {
_ = _resolveMapperForItem(item!, section: section, viewType: viewType)
}
/// Register views
let mapper = (item!.mapper)!
let id = item!.id
if !registeredIds.contains(id) {
registeredIds.append(id)
/// Resolve optional nib
var nib: UINib? = nil
let className = "\(mapper.targetClass)"
if Bundle.main.path(forResource: className, ofType: "nib") != nil {
nib = UINib(nibName: className, bundle: nil)
}
/// Register class/nib
switch viewType! {
case .Item:
if nib != nil {
tableView?.register(nib, forCellReuseIdentifier: id)
} else {
tableView?.register(mapper.targetClass, forCellReuseIdentifier: id)
}
case .Header, .Footer:
if nib != nil {
tableView?.register(nib, forHeaderFooterViewReuseIdentifier: id)
} else {
tableView?.register(mapper.targetClass, forHeaderFooterViewReuseIdentifier: id)
}
}
}
return item
}
private func _resolveMapperForItem(_ item: CollectionItemType, section: CollectionSectionType, viewType: ViewType? = .Item) -> AbstractMapper? {
if let mapper = item.mapper {
return mapper
}
var resolvedMapper: AbstractMapper?
for (_, mapper) in section.mappers.enumerated() {
if mapper.id == item.id {
resolvedMapper = mapper
break
}
}
if resolvedMapper == nil {
for (_, mapper) in mappers.enumerated() {
if mapper.id == item.id {
resolvedMapper = mapper
break
}
}
}
if resolvedMapper == nil {
switch viewType! {
case .Item:
resolvedMapper = Mapper<AnyObject, UITableViewCell> { value, cell in
cell.textLabel?.text = (value != nil) ? "\(value!)" : nil
}
case .Header:
resolvedMapper = Mapper<AnyObject, TableViewHeaderFooterView> { value, view in
view.label.text = (value != nil) ? "\(value!)" : nil
view.setNeedsUpdateConstraints()
view.invalidateIntrinsicContentSize()
}
case .Footer:
resolvedMapper = Mapper<AnyObject, TableViewHeaderFooterView> { value, view in
view.label.text = (value != nil) ? "\(value!)" : nil
}
}
}
item.mapper = resolvedMapper
return resolvedMapper
}
// MARK: - UITableViewDataSource
public func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = _section(atIndex: section), !section.isHidden else { return 0 }
return section.dynamicItemCount ?? section.items?.count ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let item = _item(atIndexPath: indexPath as IndexPath) {
if let cell = tableView.dequeueReusableCell(withIdentifier: item.id) {
item.mapper?.apply(item.value, to: cell)
return cell
}
}
return UITableViewCell()
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let header = _header(atIndex: section), _section(atIndex: section)?.isHidden != true {
if let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: header.id) {
if var headerViewType = headerView as? TableViewHeaderFooterViewType {
headerViewType.isFooter = false
headerViewType.isFirst = (section == 0)
headerViewType.tableViewStyle = tableView.style
headerView.setNeedsUpdateConstraints()
}
header.mapper?.apply(header.value, to: headerView)
return headerView
}
}
return UITableViewHeaderFooterView()
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let footer = _footer(atIndex: section), _section(atIndex: section)?.isHidden != true {
if let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: footer.id) {
if var footerViewType = footerView as? TableViewHeaderFooterViewType {
footerViewType.isFooter = true
footerViewType.isFirst = (section == 0)
footerViewType.tableViewStyle = tableView.style
footerView.setNeedsUpdateConstraints()
}
footer.mapper?.apply(footer.value, to: footerView)
return footerView
}
}
return UITableViewHeaderFooterView()
}
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
var titles: [String] = []
for section in sections {
if let indexTitle = section.indexTitle {
titles.append(indexTitle)
}
}
return titles
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return _item(atIndexPath: indexPath as IndexPath)?.editable ?? true
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard let item = _item(atIndexPath: indexPath as IndexPath) else { return }
item.commitEditingStyle?(editingStyle, item)
}
// MARK: - UITableViewDelegate
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
guard let item = _item(atIndexPath: indexPath as IndexPath) else { return }
if let handler = item.selectionHandler {
handler(item)
return
}
if let section = _section(atIndex: indexPath.section),
let handler = section.selectionHandler {
handler(item)
return
}
selectionHandler?(item)
}
public func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
guard let item = _item(atIndexPath: indexPath as IndexPath) else { return }
if let handler = item.accessoryButtonHandler {
handler(item)
return
}
if let section = _section(atIndex: indexPath.section),
let handler = section.accessoryButtonHandler {
handler(item)
return
}
accessoryButtonHandler?(item)
}
public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
return tableView.estimatedSectionHeaderHeight
}
public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
return tableView.estimatedSectionFooterHeight
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
guard _header(atIndex: section) != nil else {
guard tableView.style == .grouped else { return 0 }
guard _section(atIndex: section - 1)?.footer != nil else { return 35 }
return 16
}
return tableView.sectionHeaderHeight
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
guard _footer(atIndex: section) != nil else {
guard tableView.style == .grouped else { return 0 }
guard let nextSection = _section(atIndex: section + 1) else { return 16 }
guard nextSection.header != nil else { return 0 }
return 16
}
return tableView.sectionFooterHeight
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return _item(atIndexPath: indexPath as IndexPath)?.editingStyle ?? .none
}
public func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return _item(atIndexPath: indexPath as IndexPath)?.titleForDeleteConfirmationButton
}
public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return _item(atIndexPath: indexPath as IndexPath)?.editActions
}
}
| 49673312f986f9b48442a16d255ad249 | 37.788557 | 148 | 0.588982 | false | false | false | false |
davidjeong/doge-reader | refs/heads/master | DogeReader/DogeReader/DRModel.swift | mit | 1 | //
// DRSubreddit.swift
// DogeReader
//
// Created by Juhwan Jeong on 4/8/16.
// Copyright © 2016 Juhwan Jeong. All rights reserved.
//
// Has all models required for Doge Reader.
import Cocoa
class DRModelManager {
static let sharedInstance = DRModelManager();
var account: DRAccount;
private init() {
account = DRAccount(username: "");
}
}
class DRAccount: NSObject {
var username : String
var mySubreddits: [DRSubreddit] = []
init(username: String) {
self.username = username;
}
func addToMySubreddits(subreddit: DRSubreddit) {
self.mySubreddits.append(subreddit);
}
}
class DRSubreddit: NSObject {
let subreddit : String
let url : String
init (subreddit:String, url: String) {
self.subreddit = subreddit;
self.url = url;
}
}
| c5a264f9f7ecdd5f5d4767b6849c6783 | 18.906977 | 55 | 0.626168 | false | false | false | false |
luispadron/UIEmptyState | refs/heads/master | src/UIEmptyState/UIViewController+UIEmptyState.swift | mit | 1 | //
// UIViewController+UIEmptyState
// UIEmptyState
//
// Created by Luis Padron on 1/31/17.
// Copyright © 2017 Luis Padron. All rights reserved.
//
import UIKit
/// Extension on UIViewController which adds method and computed properties in order to allow empty view creation
extension UIViewController {
/// Private struct of keys to be used with objective-c associated objects
private struct Keys {
static var emptyStateView = "com.luispadron.emptyStateView"
static var emptyStateDataSource = "com.luispadron.emptyStateDataSource"
static var emptyStateDelegate = "com.luispadron.emptyStateDelegate"
}
/**
The data source for the Empty View
Default conformance for UIViewController is provided,
however feel free to implement these methods to customize your view.
*/
public var emptyStateDataSource: UIEmptyStateDataSource? {
get { return objc_getAssociatedObject(self, &Keys.emptyStateDataSource) as? UIEmptyStateDataSource }
set { objc_setAssociatedObject(self, &Keys.emptyStateDataSource, newValue, .OBJC_ASSOCIATION_ASSIGN) }
}
/**
The delegate for UIEmptyStateView
**Important:** this delegate and its functions are only used when using UIEmptyStateView.
If you will provide a custom view in the UIEmptyStateDataSource you must handle how this delegate operates
*/
public var emptyStateDelegate: UIEmptyStateDelegate? {
get { return objc_getAssociatedObject(self, &Keys.emptyStateDelegate) as? UIEmptyStateDelegate }
set { objc_setAssociatedObject(self, &Keys.emptyStateDelegate, newValue, .OBJC_ASSOCIATION_ASSIGN) }
}
/**
The empty state view associated to the ViewController
**Note:**
This view corresponds and is created from
the UIEmptyDataSource method: `func viewForEmptyState() -> UIView`
To set this view, use `UIEmptyStateDataSource.emptyStateView`.
By default this view is of type `UIEmptyStateView`
*/
private var emptyView: UIView? {
get { return objc_getAssociatedObject(self, &Keys.emptyStateView) as? UIView }
set {
objc_setAssociatedObject(self, &Keys.emptyStateView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// Set the views delegate
if let view = emptyView as? UIEmptyStateView { view.delegate = emptyStateDelegate }
}
}
/**
The method responsible for show and hiding the `UIEmptyStateDataSource.viewForEmptyState` view
**Important:**
This should be called whenever changes are made to the tableView data source or after reloading the tableview
Do NOT override this method/implement it unless you need custom behavior and know what you are doing.
*/
public func reloadEmptyStateForTableView(_ tableView: UITableView) {
guard let source = emptyStateDataSource, source.emptyStateViewShouldShow(for: tableView) else {
// Call the will hide delegate
if let view = emptyView {
self.emptyStateDelegate?.emptyStateViewWillHide(view: view)
}
// If shouldnt show view remove from superview, enable scrolling again
emptyView?.isHidden = true
tableView.isScrollEnabled = true
// Also return edges for extended layout to the default values, if adjusted
if emptyStateDataSource?.emptyStateViewAdjustsToFitBars ?? false {
self.edgesForExtendedLayout = .all
}
return
}
// Check whether scrolling for tableview is allowed or not
tableView.isScrollEnabled = source.emptyStateViewCanScroll
finishReload(for: source, in: tableView)
}
/**
The method responsible for show and hiding the `UIEmptyStateDataSource.viewForEmptyState` view
**Important:**
This should be called whenever changes are made to the collection view data source or after reloading the collection view.
Do NOT override this method/implement it unless you need custom behavior and know what you are doing.
*/
public func reloadEmptyStateForCollectionView(_ collectionView: UICollectionView) {
guard let source = emptyStateDataSource,
source.emptyStateViewShouldShow(for: collectionView) else {
// Call the will hide delegate
if let view = emptyView {
self.emptyStateDelegate?.emptyStateViewWillHide(view: view)
}
// If shouldnt show view remove from superview, enable scrolling again
emptyView?.isHidden = true
collectionView.isScrollEnabled = true
// Also return edges for extended layout to the default values, if adjusted
if emptyStateDataSource?.emptyStateViewAdjustsToFitBars ?? false {
self.edgesForExtendedLayout = .all
}
return
}
// Check to see if scrolling is enabled
collectionView.isScrollEnabled = source.emptyStateViewCanScroll
finishReload(for: source, in: collectionView)
}
/// Finishes the reload, i.e assigns the empty view, and adjusts any other UI
private func finishReload(for source: UIEmptyStateDataSource, in superView: UIView) {
let emptyView = showView(for: source, in: superView)
// Only add constraints if they haven't already been added
if emptyView.constraints.count <= 2 { // 2, because theres already 2 constraints added to it's subviews
self.createViewConstraints(for: emptyView, in: superView, source: source)
}
// Return & call the did show view delegate
self.emptyStateDelegate?.emptyStateViewDidShow(view: emptyView)
}
//// Private helper which creates view contraints for the UIEmptyStateView.
private func createViewConstraints(for view: UIView, in superView: UIView, source: UIEmptyStateDataSource) {
var centerYOffset: CGFloat?
// Takes into account any extra offset that the table's header view might need, this way
// we get a true center alignment with the table view.
if let tableHeader = (superView as? UITableView)?.tableHeaderView {
centerYOffset = tableHeader.frame.height / 2.0
}
var centerY = view.centerYAnchor.constraint(equalTo: superView.centerYAnchor)
var centerX = view.centerXAnchor.constraint(equalTo: superView.centerXAnchor, constant: centerYOffset ?? 0)
centerX.isActive = true
centerY.isActive = true
// If iOS 11.0 is not available, then adjust the extended layout accordingly using older API
// and then return
guard #available(iOS 11.0, *) else {
// Adjust to fit bars if allowed
if source.emptyStateViewAdjustsToFitBars {
self.edgesForExtendedLayout = []
} else {
self.edgesForExtendedLayout = .all
}
return
}
// iOS 11.0+ is available, thus use new safeAreaLayoutGuide, but only if adjustesToFitBars is true.
// The reason for this is safeAreaLayoutGuide will take into account any bar that may be used
// If for some reason user doesn't want to adjust to bars, then keep the old center constraints
if source.emptyStateViewAdjustsToFitBars {
// Adjust constraint to fit new big title bars, etc
centerX.isActive = false
centerX = view.centerXAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.centerXAnchor)
centerX.isActive = true
centerY.isActive = false
centerY = view.centerYAnchor.constraint(equalTo: superView.safeAreaLayoutGuide.centerYAnchor,
constant: centerYOffset ?? 0)
centerY.isActive = true
}
}
/// Private helper method which will create the empty state view if not created, or show it if hidden
private func showView(for source: UIEmptyStateDataSource, in view: UIView) -> UIView {
if let createdView = emptyView {
// Call the will show delegate
self.emptyStateDelegate?.emptyStateViewWillShow(view: createdView)
// View has been created, update it and then reshow
createdView.isHidden = false
guard let view = createdView as? UIEmptyStateView else { return createdView }
view.backgroundColor = source.emptyStateBackgroundColor
view.title = source.emptyStateTitle
view.image = source.emptyStateImage
view.imageSize = source.emptyStateImageSize
view.imageViewTintColor = source.emptyStateImageViewTintColor
view.buttonTitle = source.emptyStateButtonTitle
view.buttonImage = source.emptyStateButtonImage
view.buttonSize = source.emptyStateButtonSize
view.detailMessage = source.emptyStateDetailMessage
view.spacing = source.emptyStateViewSpacing
view.centerYOffset = source.emptyStateViewCenterYOffset
view.backgroundColor = source.emptyStateBackgroundColor
// Animate now
if source.emptyStateViewCanAnimate && source.emptyStateViewAnimatesEverytime {
DispatchQueue.main.async {
source.emptyStateViewAnimation(
for: view,
animationDuration: source.emptyStateViewAnimationDuration,
completion: { finished in
self.emptyStateDelegate?.emptyStateViewAnimationCompleted(for: view, didFinish: finished)
}
)
}
}
return view
} else {
// We can create the view now
let newView = source.emptyStateView
// Call the will show delegate
self.emptyStateDelegate?.emptyStateViewWillShow(view: newView)
// Add to emptyStateView property
emptyView = newView
// Add as a subView, bring it infront of the tableView
view.addSubview(newView)
view.bringSubviewToFront(newView)
// Animate now
if source.emptyStateViewCanAnimate {
DispatchQueue.main.async {
source.emptyStateViewAnimation(
for: newView,
animationDuration: source.emptyStateViewAnimationDuration,
completion: { finished in
self.emptyStateDelegate?.emptyStateViewAnimationCompleted(for: newView, didFinish: finished)
}
)
}
}
return newView
}
}
}
/// A convenience extension for UITableViewController which defaults the tableView
extension UITableViewController {
/// Reloads the empty state, defaults the tableView to `self.tableView`
public func reloadEmptyState() {
self.reloadEmptyStateForTableView(self.tableView)
}
}
/// A convenience extension for UICollectionViewController which defaults the collectionView
extension UICollectionViewController {
/// Reloads the empty state, defaults the collectionView to `self.collectionView`
public func reloadEmptyState() {
guard let collectionView = self.collectionView else {
print("UIEmptyState ==== WARNING: Tried to reload collectionView's empty state but the collectionView for\n\(self) was nil.")
return
}
self.reloadEmptyStateForCollectionView(collectionView)
}
}
| c38fc5e9ff0d903827fc2c3e29144572 | 43.051852 | 137 | 0.646797 | false | false | false | false |
kylecrawshaw/ImagrAdmin | refs/heads/master | ImagrAdmin/WorkflowSupport/WorkflowComponents/PackageComponent/PackageComponentViewController.swift | apache-2.0 | 1 | //
// PackageComponentViewController.swift
// ImagrManager
//
// Created by Kyle Crawshaw on 7/15/16.
// Copyright © 2016 Kyle Crawshaw. All rights reserved.
//
import Cocoa
class PackageComponentViewController: NSViewController {
@IBOutlet weak var packageURLField: NSTextField!
@IBOutlet weak var firstBootCheckbox: NSButton!
var component: PackageComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? PackageComponent
packageURLField.stringValue = component!.URL
if component!.firstBoot == false {
firstBootCheckbox.state = 0
} else {
firstBootCheckbox.state = 1
}
}
override func viewDidDisappear() {
component!.URL = packageURLField.stringValue
if firstBootCheckbox.state == 0 {
component!.firstBoot = false
} else {
component!.firstBoot = true
}
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
| 7419541cac328d872fa5807e20febcac | 26.068182 | 104 | 0.642317 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/BlogServiceAuthorTests.swift | gpl-2.0 | 1 | import CoreData
import XCTest
@testable import WordPress
class BlogServiceAuthorTests: XCTestCase {
var contextManager: TestContextManager!
var blogService: BlogService!
var context: NSManagedObjectContext {
return contextManager.mainContext
}
override func setUp() {
super.setUp()
contextManager = TestContextManager()
blogService = BlogService(managedObjectContext: contextManager.mainContext)
}
override func tearDown() {
super.tearDown()
ContextManager.overrideSharedInstance(nil)
contextManager.mainContext.reset()
contextManager = nil
blogService = nil
}
func testUpdatingBlogAuthors() {
let blog = blogService.createBlog()
let notFoundAuthor = blog.getAuthorWith(id: 1)
XCTAssertNil(notFoundAuthor)
let remoteUser = RemoteUser()
remoteUser.userID = 1
blogService.updateBlogAuthors(for: blog, with: [remoteUser])
let author = blog.getAuthorWith(id: 1)
XCTAssertNotNil(author)
}
/// Authors should be marked as not deleted from the blog on initial insertion, or reinsertion after being deleted.
func testMarkingAuthorAsNotDeleted() throws {
let blog = blogService.createBlog()
let remoteUser = RemoteUser()
remoteUser.userID = 1
blogService.updateBlogAuthors(for: blog, with: [remoteUser])
let author = try XCTUnwrap(blog.getAuthorWith(id: 1))
XCTAssertFalse(author.deletedFromBlog)
// the author was removed, set as deleted
blogService.updateBlogAuthors(for: blog, with: [])
let removedAuthor = try XCTUnwrap(blog.getAuthorWith(id: 1))
XCTAssertTrue(removedAuthor.deletedFromBlog)
// the author was added back, set as not deleted
blogService.updateBlogAuthors(for: blog, with: [remoteUser])
let addedBackAuthor = try XCTUnwrap(blog.getAuthorWith(id: 1))
XCTAssertFalse(addedBackAuthor.deletedFromBlog)
}
/// Authors that are no longer included in the remote user array from the API are marked as deleted.
func testMarkingAuthorAsDeleted() throws {
let blog = blogService.createBlog()
let remoteUser1 = RemoteUser()
remoteUser1.userID = 1
let remoteUser2 = RemoteUser()
remoteUser2.userID = 2
blogService.updateBlogAuthors(for: blog, with: [remoteUser1, remoteUser2])
XCTAssertNotNil(blog.getAuthorWith(id: 1))
XCTAssertNotNil(blog.getAuthorWith(id: 2))
/// User 2 was deleted so the API only returned User 1
blogService.updateBlogAuthors(for: blog, with: [remoteUser1])
XCTAssertNotNil(blog.getAuthorWith(id: 1))
let author2 = try XCTUnwrap(blog.getAuthorWith(id: 2))
XCTAssertTrue(author2.deletedFromBlog)
}
func testQueryingBlogAuthorById() throws {
let blog = blogService.createBlog()
let remoteUser = RemoteUser()
remoteUser.userID = 1
remoteUser.displayName = "Test Author"
blogService.updateBlogAuthors(for: blog, with: [remoteUser])
let foundAuthor = try XCTUnwrap(blog.getAuthorWith(id: 1))
XCTAssertEqual(foundAuthor.userID, 1)
XCTAssertEqual(foundAuthor.displayName, "Test Author")
let notFoundAuthor = blog.getAuthorWith(id: 2)
XCTAssertNil(notFoundAuthor)
}
}
| 667b2f15143fe360e9f02d04229793c4 | 30.601852 | 119 | 0.678875 | false | true | false | false |
chronotruck/CTKFlagPhoneNumber | refs/heads/master | Sources/FPNCountryPicker/FPNNibLoadingView.swift | apache-2.0 | 1 | import UIKit
class NibLoadingView: UIView {
@IBOutlet weak var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
fileprivate func nibSetup() {
backgroundColor = UIColor.clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
fileprivate func loadViewFromNib() -> UIView {
let bundle = Bundle.FlagPhoneNumber()
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}
| f3d586d450baedcfe2f5a17ded73459c | 21.057143 | 79 | 0.727979 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Source/Synchronization/Strategies/TeamMembersDownloadRequestStrategy.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
/// Downloads all team members during the slow sync.
public final class TeamMembersDownloadRequestStrategy: AbstractRequestStrategy, ZMSingleRequestTranscoder {
let syncStatus: SyncStatus
var sync: ZMSingleRequestSync!
public init(withManagedObjectContext managedObjectContext: NSManagedObjectContext,
applicationStatus: ApplicationStatus,
syncStatus: SyncStatus) {
self.syncStatus = syncStatus
super.init(withManagedObjectContext: managedObjectContext,
applicationStatus: applicationStatus)
configuration = [.allowsRequestsDuringSlowSync]
sync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: managedObjectContext)
}
override public func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? {
guard syncStatus.currentSyncPhase == .fetchingTeamMembers else { return nil }
sync.readyForNextRequestIfNotBusy()
return sync.nextRequest(for: apiVersion)
}
// MARK: - ZMSingleRequestTranscoder
public func request(for sync: ZMSingleRequestSync, apiVersion: APIVersion) -> ZMTransportRequest? {
guard let teamID = ZMUser.selfUser(in: managedObjectContext).teamIdentifier else {
completeSyncPhase() // Skip sync phase if user doesn't belong to a team
return nil
}
return ZMTransportRequest(getFromPath: "/teams/\(teamID.transportString())/members", apiVersion: apiVersion.rawValue)
}
public func didReceive(_ response: ZMTransportResponse, forSingleRequest sync: ZMSingleRequestSync) {
guard
response.result == .success,
let team = ZMUser.selfUser(in: managedObjectContext).team,
let rawData = response.rawData,
let payload = MembershipListPayload(rawData)
else {
return
}
if !payload.hasMore {
payload.members.forEach { (membershipPayload) in
membershipPayload.createOrUpdateMember(team: team, in: managedObjectContext)
}
}
completeSyncPhase()
}
func completeSyncPhase() {
syncStatus.finishCurrentSyncPhase(phase: .fetchingTeamMembers)
}
}
| d7d733b09e3b4401f55ebb5d67c3c560 | 35.097561 | 125 | 0.701689 | false | false | false | false |
WSDOT/wsdot-ios-app | refs/heads/master | wsdot/BloggerStore.swift | gpl-3.0 | 1 | //
// BloggerStore.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import Foundation
import Alamofire
import SwiftyJSON
class BloggerStore {
typealias FetchBlogPostsCompletion = (_ data: [BlogItem]?, _ error: Error?) -> ()
static func getBlogPosts(_ completion: @escaping FetchBlogPostsCompletion) {
AF.request("https://wsdotblog.blogspot.com/feeds/posts/default?alt=json&max-results=10").validate().responseJSON { response in
switch response.result {
case .success:
if let value = response.data {
let json = JSON(value)
let posts = parsePostsJSON(json)
completion(posts, nil)
}
case .failure(let error):
print(error)
completion(nil, error)
}
}
}
fileprivate static func parsePostsJSON(_ json: JSON) ->[BlogItem]{
var posts = [BlogItem]()
for (_,postJson):(String, JSON) in json["feed"]["entry"] {
let post = BlogItem()
post.title = postJson["title"]["$t"].stringValue
post.content = postJson["content"]["$t"].stringValue
.replacingOccurrences(of: "</p><p>", with: ": ", options: .regularExpression, range: nil)
.replacingOccurrences(of: "</h2><h3>", with: " ", options: .regularExpression, range: nil)
.replacingOccurrences(of: "<i>(.*)</i><br /><br />", with: "", options: .regularExpression, range: nil)
.replacingOccurrences(of: "<em>(.*)</em><br /><br />", with: "", options: .regularExpression, range: nil)
.replacingOccurrences(of: "<table(.*?)>.*?</table>", with: "", options: .regularExpression, range: nil)
.replacingOccurrences(of: " ", with:" ")
.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
post.link = postJson["link"][4]["href"].stringValue
post.published = TimeUtils.postPubDateToNSDate(postJson["published"]["$t"].stringValue, formatStr: "yyyy-MM-dd'T'HH:mm:ss.SSSz", isUTC: true)
post.imageUrl = postJson["media$thumbnail"]["url"].stringValue
posts.append(post)
}
return posts
}
}
| e5610c84400d19b2dbb93bd8c01e6750 | 41.569444 | 153 | 0.594127 | false | false | false | false |
mLewisLogic/codepath-application | refs/heads/master | tipster/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// tipster
//
// Created by Michael Lewis on 1/17/15.
// Copyright (c) 2015 Machel. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
let tipPercentageArray = [0.18, 0.20, 0.22]
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Appropriate default values
tipLabel.text = formattedAmount(0.0)
totalLabel.text = formattedAmount(0.0)
}
// Make sure that we reload the defaults when the modal closes
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadTipControl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEditingChanged(sender: AnyObject) {
var tipPercentage = tipPercentageArray[tipControl.selectedSegmentIndex]
// Extract the user-entered bill amount
var billAmount = (billField.text as NSString).doubleValue
// Calculate the tip and total amounts
var tipAmount = billAmount * tipPercentage
var totalAmount = billAmount + tipAmount
// Update the UI elements for tip and total amounts
tipLabel.text = formattedAmount(tipAmount)
totalLabel.text = formattedAmount(totalAmount)
}
// Tapping outside of the keyboard will hide it.
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
private
// Build a properly formatted string for a given amount,
// in local currency and formatting.
func formattedAmount(amount: Double) -> String? {
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
return formatter.stringFromNumber(amount)
}
// Load the current user default and set the index of the control
func reloadTipControl() {
tipControl.selectedSegmentIndex = getTipIndex(loadDefaultTipValue())
}
// Load the user's saved default tip value
func loadDefaultTipValue() -> Double {
var defaults = NSUserDefaults.standardUserDefaults()
return defaults.doubleForKey("tip_percentage")
}
// Get the control index for a given tip value
// If the tip value is not found, default to 1, the default tip value
func getTipIndex(tipValue: Double) -> Int {
var tipIndex = find(tipPercentageArray, tipValue)
// In case we have a non-standard tip, use the default value's index
if (tipIndex == nil) {
tipIndex = 1
}
return tipIndex!
}
}
| d33f9333011b2a6c822145ab14e87c84 | 29.578947 | 80 | 0.670912 | false | false | false | false |
TouchInstinct/LeadKit | refs/heads/master | Sources/Classes/Controllers/BaseScrollContentController.swift | apache-2.0 | 1 | //
// Copyright (c) 2018 Touch Instinct
//
// 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 RxSwift
import RxCocoa
public typealias ScrollViewHolderView = UIView & ScrollViewHolder
/// Base controller configurable with view model and ScrollViewHolder custom view.
open class BaseScrollContentController<ViewModel, View: ScrollViewHolderView>: BaseCustomViewController<ViewModel, View> {
private var bottomInsetDisposable: Disposable?
private let defaultInsetsRelay = BehaviorRelay<UIEdgeInsets>(value: .zero)
/// Bind given driver to bottom inset of scroll view. Takes into account default bottom insets.
///
/// - Parameter bottomInsetDriver: Driver that emits CGFloat bottom inset changes.
public func bindBottomInsetBinding(from bottomInsetDriver: Driver<CGFloat>) {
bottomInsetDisposable = bottomInsetDriver
.withLatestFrom(defaultInsetsRelay.asDriver()) {
$0 + $1.bottom
}
.drive(customView.scrollView.rx.bottomInsetBinder)
}
/// Unbind scroll view from previous binding.
public func unbindBottomInsetBinding() {
bottomInsetDisposable?.dispose()
}
/// Contained UIScrollView instance.
public var scrollView: UIScrollView {
customView.scrollView
}
/// Default insets used for contained scroll view.
public var defaultInsets: UIEdgeInsets {
get {
defaultInsetsRelay.value
}
set {
defaultInsetsRelay.accept(newValue)
customView.scrollView.contentInset = newValue
customView.scrollView.scrollIndicatorInsets = newValue
}
}
}
public extension BaseScrollContentController {
/// On iOS, tvOS 11+ sets contentInsetAdjustmentBehavior to .never.
/// On earlier versions sets automaticallyAdjustsScrollViewInsets to false.
func disableAdjustsScrollViewInsets() {
if #available(iOS 11.0, tvOS 11.0, *) {
customView.scrollView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
}
}
| 0a3d1e759bba16f57af8809d0577f57a | 38.974684 | 122 | 0.717543 | false | false | false | false |
innawaylabs/tippsie | refs/heads/master | Tippsie/SettingsViewController.swift | apache-2.0 | 1 | //
// SettingsViewController.swift
// Tippsie
//
// Created by Ravi Mandala on 8/20/17.
// Copyright © 2017 Ravi Mandala. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
let defaultTipPercentageKey = "default_tip_segment"
let roundingPolicyKey = "rounding_policy_index"
@IBOutlet weak var defaultTipPercentage: UISegmentedControl!
@IBOutlet weak var roundingSegControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
let defaults = UserDefaults.standard
if (defaults.object(forKey: defaultTipPercentageKey) != nil) {
let segIndex = defaults.integer(forKey: defaultTipPercentageKey)
defaultTipPercentage.selectedSegmentIndex = segIndex
}
if (defaults.object(forKey: roundingPolicyKey) != nil) {
let roundingPolicyIndex = defaults.integer(forKey: roundingPolicyKey)
roundingSegControl.selectedSegmentIndex = roundingPolicyIndex
}
}
@IBAction func persistDefaultTipPercentage(_ sender: Any) {
let defaults = UserDefaults.standard
defaults.set(defaultTipPercentage.selectedSegmentIndex, forKey: defaultTipPercentageKey)
defaults.set(roundingSegControl.selectedSegmentIndex, forKey: roundingPolicyKey)
defaults.synchronize()
}
}
| 922da3218846c5a73a3946067e90380f | 32.877551 | 96 | 0.693373 | false | false | false | false |
Daltron/BigBoard | refs/heads/master | Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift | mit | 5 | //
// DateTransform.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-13.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// 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
open class DateTransform: TransformType {
public typealias Object = Date
public typealias JSON = Double
public init() {}
public func transformFromJSON(_ value: Any?) -> Date? {
if let timeInt = value as? Double {
return Date(timeIntervalSince1970: TimeInterval(timeInt))
}
if let timeStr = value as? String {
return Date(timeIntervalSince1970: TimeInterval(atof(timeStr)))
}
return nil
}
public func transformToJSON(_ value: Date?) -> Double? {
if let date = value {
return Double(date.timeIntervalSince1970)
}
return nil
}
}
| aa3d8c99536be07ef0558d41d14ae245 | 32.436364 | 81 | 0.730832 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | refs/heads/master | iOS/Venue/Controllers/PeopleListViewController.swift | epl-1.0 | 1 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
// MARK: - PeopleListDelegate Declaration
@objc protocol PeopleListDelegate {
func didSelectRow(tableView: UITableView, indexPath: NSIndexPath)
optional func additionalSetupForCell(cell: PeopleTableViewCell)
}
/// ViewController for displaying list of users with search bar
class PeopleListViewController: UIViewController {
var viewModel = PeopleListViewModel()
weak var delegate: PeopleListDelegate?
@IBOutlet weak var searchTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
searchTextField.rac_textSignal().subscribeNext({[unowned self](text: AnyObject!) -> Void in
self.viewModel.filterPeople(text as! String)
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - UITableView & UIScrollView Methods
extension PeopleListViewController: UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return viewModel.displayedUserSections.count
}
/**
Create header for the last name inital
*/
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerFrame = CGRectMake(0, 0, tableView.frame.width, 28)
let headerView = UIView(frame: headerFrame)
headerView.backgroundColor = UIColor.venueBabyBlue()
let labelFrame = CGRectMake(20, 0, headerView.frame.width - 20, headerView.frame.height)
let headerLabel = UILabel(frame: labelFrame)
headerLabel.textColor = UIColor.venueDarkGray()
headerLabel.font = UIFont.systemFontOfSize(12.0)
headerLabel.text = String(viewModel.displayedUserSections[section].key)
headerView.addSubview(headerLabel)
return headerView
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.displayedUserSections[section].users.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("peopleCell") as? PeopleTableViewCell {
viewModel.setUpPersonCell(cell, indexPath: indexPath)
if let delegate = self.delegate {
delegate.additionalSetupForCell?(cell)
}
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let delegate = self.delegate {
delegate.didSelectRow(tableView, indexPath: indexPath)
}
view.endEditing(true)
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
view.endEditing(true)
}
}
| c8069876e13788d3521d4982ca1d0d3f | 33.410526 | 109 | 0.678189 | false | false | false | false |
pfvernon2/swiftlets | refs/heads/master | iOSX/iOS/UIImage+Scaling.swift | apache-2.0 | 1 | //
// UIImage+Scaling.swift
// swiftlets
//
// Created by Frank Vernon on 1/19/16.
// Copyright © 2016 Frank Vernon. All rights reserved.
//
import UIKit
extension UIImage {
///Scale image to the size supplied. If screen resolution is desired, pass scale == 0.0
func scale(toSize size:CGSize, flip:Bool = false, scale:CGFloat = .unity) -> UIImage? {
let newRect:CGRect = CGRect(x:0, y:0, width:size.width, height:size.height).integral
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer {
UIGraphicsEndImageContext()
}
guard let context:CGContext = UIGraphicsGetCurrentContext() else {
return nil
}
// Set the quality level to use when rescaling
context.interpolationQuality = CGInterpolationQuality.high
//flip if requested
if flip {
let flipVertical:CGAffineTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)
context.concatenate(flipVertical)
}
// Draw into the context; this scales the image
draw(in: newRect)
// Get the resized image from the context and a UIImage
guard let newImageRef:CGImage = context.makeImage() else {
return nil
}
let newImage:UIImage = UIImage(cgImage: newImageRef)
return newImage;
}
func scaleProportional(toSize size:CGSize, scale:CGFloat = 1.0) -> UIImage? {
var proportialSize = size
if self.size.width > self.size.height {
proportialSize = CGSize(width: (self.size.width/self.size.height) * proportialSize.height, height: proportialSize.height)
}
else {
proportialSize = CGSize(width: proportialSize.width, height: (self.size.height/self.size.width) * proportialSize.width)
}
return self.scale(toSize: proportialSize)
}
func circular() -> UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .scaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width.halved
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
//https://gist.github.com/ffried/0cbd6366bb9cf6fc0208
public func imageRotated(byDegrees degrees: CGFloat, flip: Bool) -> UIImage? {
func degreesToRadians(_ degrees:CGFloat) -> CGFloat {
degrees / 180.0 * CGFloat(Double.pi)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint.zero, size: size))
rotatedViewBox.transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
defer {
UIGraphicsEndImageContext()
}
guard let bitmap:CGContext = UIGraphicsGetCurrentContext() else {
return nil
}
// Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap.translateBy(x: rotatedSize.width.halved, y: rotatedSize.height.halved)
// Rotate the image context
bitmap.rotate(by: degreesToRadians(degrees))
// Now, draw the rotated/scaled image into the context
bitmap.scaleBy(x: flip ? -1.0 : 1.0, y: -1.0)
draw(in: CGRect(x: -size.width.halved, y: -size.height.halved, width: size.width, height: size.height))
let newImage:UIImage? = UIGraphicsGetImageFromCurrentImageContext()
return newImage
}
}
public extension UIImage {
convenience init?(systemName: String, scale: UIImage.SymbolScale) {
let config = UIImage.SymbolConfiguration(scale: scale)
self.init(systemName: systemName, withConfiguration: config)
}
}
| 1baf89ddceaa2a63f1de8b18da2dd6fe | 36.661157 | 133 | 0.630239 | false | false | false | false |
C4Framework/C4iOS | refs/heads/master | C4/UI/Polygon.swift | mit | 4 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import Foundation
import CoreGraphics
/// Polygon is a concrete subclass of Shape that has a special initialzer that creates a non-uniform shape made up of 3 or more points.
open class Polygon: Shape {
/// Returns the array of points that make up the polygon.
///
/// Assigning an array of Point values to this object will cause the receiver to update itself.
///
/// ````
/// let p = Polygon()
/// let a = Point()
/// let b = Point(100,100)
/// let c = Point(200,0)
/// p.points = [a,b,c]
/// p.center = canvas.center
/// canvas.add(p)
/// ````
public var points: [Point] {
didSet {
updatePath()
}
}
/// Initializes a default Polygon.
public override init() {
self.points = []
super.init()
fillColor = clear
}
/// Initializes a new Polygon using the specified array of points.
///
/// Protects against trying to create a polygon with only 1 point (i.e. requires 2 or more points).
///
/// ````
/// let a = Point()
/// let b = Point(100,100)
/// let c = Point(200,0)
/// let p = Polygon([a,b,c])
/// p.center = canvas.center
/// canvas.add(p)
/// ````
/// - parameter points: An array of Point structs.
public init(_ points: [Point]) {
assert(points.count >= 2, "To create a Polygon you need to specify an array of at least 2 points")
self.points = points
super.init()
fillColor = clear
let path = Path()
path.moveToPoint(points.first!)
for point in points.dropFirst() {
path.addLineToPoint(point)
}
self.path = path
adjustToFitPath()
}
/// Initializes a new Polygon from data in a given unarchiver.
/// - parameter coder: An unarchiver object.
required public init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updatePath() {
if points.count > 1 {
let p = Path()
p.moveToPoint(points.first!)
for point in points.dropFirst() {
p.addLineToPoint(point)
}
path = p
adjustToFitPath()
}
}
/// Closes the shape.
///
/// This method appends a line between the shape's last point and its first point.
public func close() {
let p = path
p?.closeSubpath()
self.path = p
adjustToFitPath()
}
}
| dadf96f5eb71227dcdf40a75409178db | 31.7 | 136 | 0.618849 | false | false | false | false |
rick020/MijnOV | refs/heads/final | MijnOV/Utilities.swift | mit | 1 | //
// Utilities.swift
// ObjectAndClasses
//
// Created by Rick Bruins on 23/01/2017.
// Copyright © 2017 Mprog. All rights reserved.
//
import Foundation
import MapKit
import CoreData
// MARK: Helper Extensions
extension MKMapView {
func zoomToUserLocation() {
guard let coordinate = userLocation.location?.coordinate else { return }
let region = MKCoordinateRegionMakeWithDistance(coordinate, 200, 200)
setRegion(region, animated: true)
}
}
extension UIViewController {
func alert(title: String, message : String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension UIColor {
convenience init(rgb: UInt) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
extension UIViewController {
func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
}
| 8f2f637a5e27b55545a0b16ef49cf2ce | 26.564516 | 131 | 0.667642 | false | false | false | false |
slavapestov/swift | refs/heads/master | stdlib/public/core/Reflection.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Customizes the result of `_reflect(x)`, where `x` is a conforming
/// type.
public protocol _Reflectable {
// The runtime has inappropriate knowledge of this protocol and how its
// witness tables are laid out. Changing this protocol requires a
// corresponding change to Reflection.cpp.
/// Returns a mirror that reflects `self`.
@warn_unused_result
func _getMirror() -> _MirrorType
}
/// A unique identifier for a class instance or metatype. This can be used by
/// reflection clients to recognize cycles in the object graph.
///
/// In Swift, only class instances and metatypes have unique identities. There
/// is no notion of identity for structs, enums, functions, or tuples.
public struct ObjectIdentifier : Hashable, Comparable {
let value: Builtin.RawPointer
/// Convert to a `UInt` that captures the full value of `self`.
///
/// Axiom: `a.uintValue == b.uintValue` iff `a == b`.
public var uintValue: UInt {
return UInt(Builtin.ptrtoint_Word(value))
}
// FIXME: Better hashing algorithm
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(value))
}
/// Construct an instance that uniquely identifies the class instance `x`.
public init(_ x: AnyObject) {
self.value = Builtin.bridgeToRawPointer(x)
}
/// Construct an instance that uniquely identifies the metatype `x`.
public init(_ x: Any.Type) {
self.value = unsafeBitCast(x, Builtin.RawPointer.self)
}
}
@warn_unused_result
public func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {
return lhs.uintValue < rhs.uintValue
}
@warn_unused_result
public func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(x.value, y.value))
}
/// How children of this value should be presented in the IDE.
public enum _MirrorDisposition {
/// As a struct.
case Struct
/// As a class.
case Class
/// As an enum.
case Enum
/// As a tuple.
case Tuple
/// As a miscellaneous aggregate with a fixed set of children.
case Aggregate
/// As a container that is accessed by index.
case IndexContainer
/// As a container that is accessed by key.
case KeyContainer
/// As a container that represents membership of its values.
case MembershipContainer
/// As a miscellaneous container with a variable number of children.
case Container
/// An Optional which can have either zero or one children.
case Optional
/// An Objective-C object imported in Swift.
case ObjCObject
}
/// The type returned by `_reflect(x)`; supplies an API for runtime
/// reflection on `x`.
public protocol _MirrorType {
/// The instance being reflected.
var value: Any { get }
/// Identical to `value.dynamicType`.
var valueType: Any.Type { get }
/// A unique identifier for `value` if it is a class instance; `nil`
/// otherwise.
var objectIdentifier: ObjectIdentifier? { get }
/// The count of `value`'s logical children.
var count: Int { get }
/// Get a name and mirror for the `i`th logical child.
subscript(i: Int) -> (String, _MirrorType) { get }
/// A string description of `value`.
var summary: String { get }
/// A rich representation of `value` for an IDE, or `nil` if none is supplied.
var quickLookObject: PlaygroundQuickLook? { get }
/// How `value` should be presented in an IDE.
var disposition: _MirrorDisposition { get }
}
/// An entry point that can be called from C++ code to get the summary string
/// for an arbitrary object. The memory pointed to by "out" is initialized with
/// the summary string.
@warn_unused_result
@_silgen_name("swift_getSummary")
public // COMPILER_INTRINSIC
func _getSummary<T>(out: UnsafeMutablePointer<String>, x: T) {
out.initialize(String(reflecting: x))
}
/// Produce a mirror for any value. If the value's type conforms to
/// `_Reflectable`, invoke its `_getMirror()` method; otherwise, fall back
/// to an implementation in the runtime that structurally reflects values
/// of any type.
@warn_unused_result
@_silgen_name("swift_reflectAny")
public func _reflect<T>(x: T) -> _MirrorType
/// Dump an object's contents using its mirror to the specified output stream.
public func dump<T, TargetStream : OutputStreamType>(
x: T, inout _ targetStream: TargetStream,
name: String? = nil, indent: Int = 0,
maxDepth: Int = .max, maxItems: Int = .max
) -> T {
var maxItemCounter = maxItems
var visitedItems = [ObjectIdentifier : Int]()
targetStream._lock()
defer { targetStream._unlock() }
_dumpObject_unlocked(
x, name, indent, maxDepth, &maxItemCounter, &visitedItems,
&targetStream)
return x
}
/// Dump an object's contents using its mirror to standard output.
public func dump<T>(x: T, name: String? = nil, indent: Int = 0,
maxDepth: Int = .max, maxItems: Int = .max) -> T {
var stdoutStream = _Stdout()
return dump(
x, &stdoutStream, name: name, indent: indent, maxDepth: maxDepth,
maxItems: maxItems)
}
/// Dump an object's contents. User code should use dump().
internal func _dumpObject_unlocked<TargetStream : OutputStreamType>(
object: Any, _ name: String?, _ indent: Int, _ maxDepth: Int,
inout _ maxItemCounter: Int,
inout _ visitedItems: [ObjectIdentifier : Int],
inout _ targetStream: TargetStream
) {
guard maxItemCounter > 0 else { return }
maxItemCounter -= 1
for _ in 0..<indent { targetStream.write(" ") }
let mirror = Mirror(reflecting: object)
let count = mirror.children.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
targetStream.write(bullet)
targetStream.write(" ")
if let nam = name {
targetStream.write(nam)
targetStream.write(": ")
}
// This takes the place of the old mirror API's 'summary' property
_dumpPrint_unlocked(object, mirror, &targetStream)
let id: ObjectIdentifier?
if let classInstance = object as? AnyObject where object.dynamicType is AnyObject.Type {
// Object is a class (but not an ObjC-bridged struct)
id = ObjectIdentifier(classInstance)
} else if let metatypeInstance = object as? Any.Type {
// Object is a metatype
id = ObjectIdentifier(metatypeInstance)
} else {
id = nil
}
if let theId = id {
if let previous = visitedItems[theId] {
targetStream.write(" #")
_print_unlocked(previous, &targetStream)
targetStream.write("\n")
return
}
let identifier = visitedItems.count
visitedItems[theId] = identifier
targetStream.write(" #")
_print_unlocked(identifier, &targetStream)
}
targetStream.write("\n")
guard maxDepth > 0 else { return }
if let superclassMirror = mirror.superclassMirror() {
_dumpSuperclass_unlocked(superclassMirror, indent + 2, maxDepth - 1, &maxItemCounter, &visitedItems, &targetStream)
}
var currentIndex = mirror.children.startIndex
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
_print_unlocked(" ", &targetStream)
}
let remainder = count - i
targetStream.write("(")
_print_unlocked(remainder, &targetStream)
if i > 0 { targetStream.write(" more") }
if remainder == 1 {
targetStream.write(" child)\n")
} else {
targetStream.write(" children)\n")
}
return
}
let (name, child) = mirror.children[currentIndex]
currentIndex = currentIndex.successor()
_dumpObject_unlocked(child, name, indent + 2, maxDepth - 1,
&maxItemCounter, &visitedItems, &targetStream)
}
}
/// Dump information about an object's superclass, given a mirror reflecting
/// that superclass.
internal func _dumpSuperclass_unlocked<TargetStream : OutputStreamType>(
mirror: Mirror, _ indent: Int, _ maxDepth: Int,
inout _ maxItemCounter: Int,
inout _ visitedItems: [ObjectIdentifier : Int],
inout _ targetStream: TargetStream
) {
guard maxItemCounter > 0 else { return }
maxItemCounter -= 1
for _ in 0..<indent { targetStream.write(" ") }
let count = mirror.children.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
targetStream.write(bullet)
targetStream.write(" super: ")
_debugPrint_unlocked(mirror.subjectType, &targetStream)
targetStream.write("\n")
guard maxDepth > 0 else { return }
if let superclassMirror = mirror.superclassMirror() {
_dumpSuperclass_unlocked(superclassMirror, indent + 2, maxDepth - 1,
&maxItemCounter, &visitedItems, &targetStream)
}
var currentIndex = mirror.children.startIndex
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
targetStream.write(" ")
}
let remainder = count - i
targetStream.write("(")
_print_unlocked(remainder, &targetStream)
if i > 0 { targetStream.write(" more") }
if remainder == 1 {
targetStream.write(" child)\n")
} else {
targetStream.write(" children)\n")
}
return
}
let (name, child) = mirror.children[currentIndex]
currentIndex = currentIndex.successor()
_dumpObject_unlocked(child, name, indent + 2, maxDepth - 1,
&maxItemCounter, &visitedItems, &targetStream)
}
}
// -- Implementation details for the runtime's _MirrorType implementation
@_silgen_name("swift_MagicMirrorData_summary")
func _swift_MagicMirrorData_summaryImpl(
metadata: Any.Type, _ result: UnsafeMutablePointer<String>
)
public struct _MagicMirrorData {
let owner: Builtin.NativeObject
let ptr: Builtin.RawPointer
let metadata: Any.Type
var value: Any {
@_silgen_name("swift_MagicMirrorData_value")get
}
var valueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_valueType")get
}
public var objcValue: Any {
@_silgen_name("swift_MagicMirrorData_objcValue")get
}
public var objcValueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_objcValueType")get
}
var summary: String {
let (_, result) = _withUninitializedString {
_swift_MagicMirrorData_summaryImpl(self.metadata, $0)
}
return result
}
public func _loadValue<T>() -> T {
return Builtin.load(ptr) as T
}
}
struct _OpaqueMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _MirrorType) {
_preconditionFailure("no children")
}
var summary: String { return data.summary }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Aggregate }
}
internal struct _TupleMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_TupleMirror_count")get
}
subscript(i: Int) -> (String, _MirrorType) {
@_silgen_name("swift_TupleMirror_subscript")get
}
var summary: String { return "(\(count) elements)" }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Tuple }
}
struct _StructMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_StructMirror_count")get
}
subscript(i: Int) -> (String, _MirrorType) {
@_silgen_name("swift_StructMirror_subscript")get
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Struct }
}
struct _EnumMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_EnumMirror_count")get
}
var caseName: UnsafePointer<CChar> {
@_silgen_name("swift_EnumMirror_caseName")get
}
subscript(i: Int) -> (String, _MirrorType) {
@_silgen_name("swift_EnumMirror_subscript")get
}
var summary: String {
let maybeCaseName = String.fromCString(self.caseName)
let typeName = _typeName(valueType)
if let caseName = maybeCaseName {
return typeName + "." + caseName
}
return typeName
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Enum }
}
@warn_unused_result
@_silgen_name("swift_ClassMirror_count")
func _getClassCount(_: _MagicMirrorData) -> Int
@warn_unused_result
@_silgen_name("swift_ClassMirror_subscript")
func _getClassChild(_: Int, _: _MagicMirrorData) -> (String, _MirrorType)
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_ClassMirror_quickLookObject")
public func _getClassPlaygroundQuickLook(
data: _MagicMirrorData
) -> PlaygroundQuickLook?
#endif
struct _ClassMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _MirrorType) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? {
#if _runtime(_ObjC)
return _getClassPlaygroundQuickLook(data)
#else
return nil
#endif
}
var disposition: _MirrorDisposition { return .Class }
}
struct _ClassSuperMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
// Suppress the value identifier for super mirrors.
var objectIdentifier: ObjectIdentifier? {
return nil
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _MirrorType) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(data.metadata)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Class }
}
struct _MetatypeMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return 0
}
subscript(i: Int) -> (String, _MirrorType) {
_preconditionFailure("no children")
}
var summary: String {
return _typeName(data._loadValue() as Any.Type)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
// Special disposition for types?
var disposition: _MirrorDisposition { return .Aggregate }
}
@available(*, unavailable, message="call the 'Mirror(reflecting:)' initializer")
public func reflect<T>(x: T) -> _MirrorType {
fatalError("unavailable function can't be called")
}
| 366da0b395f3570e9fdfdb05eb0d0edd | 29.703276 | 119 | 0.676624 | false | false | false | false |
StephenVinouze/ios-charts | refs/heads/master | ChartsRealm/Classes/Data/RealmRadarDataSet.swift | apache-2.0 | 2 | //
// RealmRadarDataSet.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
import Charts
import Realm
import Realm.Dynamic
public class RealmRadarDataSet: RealmLineRadarDataSet, IRadarChartDataSet
{
public override func initialize()
{
self.valueFont = NSUIFont.systemFontOfSize(13.0)
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// flag indicating whether highlight circle should be drawn or not
/// **default**: false
public var drawHighlightCircleEnabled: Bool = false
/// - returns: true if highlight circle should be drawn, false if not
public var isDrawHighlightCircleEnabled: Bool { return drawHighlightCircleEnabled }
public var highlightCircleFillColor: NSUIColor? = NSUIColor.whiteColor()
/// The stroke color for highlight circle.
/// If `nil`, the color of the dataset is taken.
public var highlightCircleStrokeColor: NSUIColor?
public var highlightCircleStrokeAlpha: CGFloat = 0.3
public var highlightCircleInnerRadius: CGFloat = 3.0
public var highlightCircleOuterRadius: CGFloat = 4.0
public var highlightCircleStrokeWidth: CGFloat = 2.0
} | 34212977fb0fc499b13ab6f38f2b0160 | 26.846154 | 87 | 0.70698 | false | false | false | false |
xinan/big-brother | refs/heads/master | bigbrother-iphone/BigBrother/SwiftIO/SocketEventHandler.swift | mit | 1 | //
// EventHandler.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias AnyHandler = (event:String, items:AnyObject?)
public typealias AckEmitter = (AnyObject...) -> Void
private func emitAckCallback(socket:SocketIOClient, num:Int, type:Int) -> AckEmitter {
func emitter(items:AnyObject...) {
socket.emitAck(num, withData: items, withAckType: type)
}
return emitter
}
class SocketEventHandler {
let event:String!
let callback:NormalCallback?
init(event:String, callback:NormalCallback) {
self.event = event
self.callback = callback
}
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!, type!) : nil)
return
}
}
} | 82e5743ea88b8315b512dd55d64ecabd | 38.581818 | 101 | 0.701746 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | refs/heads/master | AviasalesSDKTemplate/Source/HotelsSource/PeekAndPop/BookingPeekVC.swift | mit | 1 | class BookingPeekVC: PeekTableVC {
var room: HDKRoom?
override func viewDidLoad() {
super.viewDidLoad()
tableView?.register(AccommodationCell.self, forCellReuseIdentifier: AccommodationCell.hl_reuseIdentifier())
tableView?.hl_registerNib(withName: PeekFullInfoCell.hl_reuseIdentifier())
}
override func createItems() -> [PeekItem] {
var result = [FullInfoItem(variant), PricePeekItem(variant, room: room)]
result.append(contentsOf: accomodationItems())
return result
}
func accomodationItems() -> [PeekItem] {
view.layoutIfNeeded()
guard let width = tableView?.bounds.width else { return [] }
let accItems = HLHotelDetailsCommonCellFactory.accommodationItems(variant, startDate: variant.searchInfo.checkInDate, endDate: variant.searchInfo.checkOutDate, containerWidth: width)
var result: [AccomodationPeekItem] = []
for i in 0..<accItems.count {
let infoItem = accItems[i]
let accItem = AccomodationPeekItem(variant)
accItem.infoItem = infoItem
result.append(accItem)
}
return result
}
// MARK: - Preview actions
@available(iOS 9.0, *)
override var previewActionItems: [UIPreviewActionItem] {
if let room = room {
return [createBookPreviewActionItem(room)]
}
return []
}
@available(iOS 9.0, *)
fileprivate func createBookPreviewActionItem(_ room: HDKRoom) -> UIPreviewActionItem {
let bookStringWithPrice = NSMutableAttributedString(string: NSLS("HL_HOTEL_PEEK_BOOK_BUTTON_TITLE"))
let appFont = UIFont.boldSystemFont(ofSize: 17.0)
let price = StringUtils.attributedPriceString(withPrice: room.price, currency: self.variant.searchInfo.currency, font: appFont)
bookStringWithPrice.append(price)
let bookTitleWithPrice = bookStringWithPrice.string
let bookTitleWithoutPrice = NSLS("HL_HOTEL_DETAIL_BOOK_BUTTON_TITLE")
let bookTitle = bookTitleWithPrice.count <= 35 ? bookTitleWithPrice : bookTitleWithoutPrice
let bookAction = UIPreviewAction(title: bookTitle, style: .default) { [weak self] (action, viewController) -> Void in
guard let `self` = self else { return }
let bookBrowserPresenter = BookBrowserViewPresenter(variant: self.variant, room: room)
let browserViewController = BrowserViewController(presenter: bookBrowserPresenter)
let navigationController = JRNavigationController(rootViewController: browserViewController)
self.viewControllerToShowBrowser?.present(navigationController, animated: true, completion: nil)
}
return bookAction
}
}
| 67a0336505e00827bfa2b5c636b72379 | 39.455882 | 190 | 0.686296 | false | false | false | false |
wireapp/wire-ios-data-model | refs/heads/develop | Source/Model/Conversation/ZMConversation+AccessMode.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
/// Defines how users can join a conversation.
public struct ConversationAccessMode: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// Allowed user can be added by an existing conv member.
public static let invite = ConversationAccessMode(rawValue: 1 << 0)
/// Allowed user can join the conversation using the code.
public static let code = ConversationAccessMode(rawValue: 1 << 1)
/// Allowed user can join knowing only the conversation ID.
public static let link = ConversationAccessMode(rawValue: 1 << 2)
/// Internal value that indicates the conversation that cannot be joined (1-1).
public static let `private` = ConversationAccessMode(rawValue: 1 << 3)
public static let legacy = invite
public static let teamOnly = ConversationAccessMode()
public static let allowGuests: ConversationAccessMode = [.invite, .code]
}
extension ConversationAccessMode: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.rawValue)
}
}
public extension ConversationAccessMode {
internal static let stringValues: [ConversationAccessMode: String] = [.invite: "invite",
.code: "code",
.link: "link",
.`private`: "private"]
var stringValue: [String] {
return ConversationAccessMode.stringValues.compactMap { self.contains($0) ? $1 : nil }
}
init(values: [String]) {
var result = ConversationAccessMode()
ConversationAccessMode.stringValues.forEach {
if values.contains($1) {
result.formUnion($0)
}
}
self = result
}
}
public extension ConversationAccessMode {
static func value(forAllowGuests allowGuests: Bool) -> ConversationAccessMode {
return allowGuests ? .allowGuests : .teamOnly
}
}
/// Defines who can join the conversation.
public enum ConversationAccessRole: String {
/// Only the team member can join.
case team = "team"
/// Only users who have verified their phone number / email can join.
case activated = "activated"
/// Any user can join.
case nonActivated = "non_activated"
// 1:1 conversation
case `private` = "private"
public static func fromAccessRoleV2(_ accessRoles: Set<ConversationAccessRoleV2>) -> ConversationAccessRole {
if accessRoles.contains(.guest) {
return .nonActivated
} else if accessRoles.contains(.nonTeamMember) || accessRoles.contains(.service) {
return .activated
} else if accessRoles.contains(.teamMember) {
return .team
} else {
return .private
}
}
}
/// The issue:
///
/// The access_role specifies who can be in the conversation. When “guests and services” is allowed,
/// then the value is non_activated (indicating the anyone can be in the conversation).
/// When “guests and services” is not allowed, then the value is team, indicating that only team member can be in the conversation.
/// These values do not distinguish between human guests and non-human services.
/// For this reason, the access_role property will be deprecated and a new access role property should be used.
///
/// The fix:
///
/// The new access role property access_role_v2 will contain a set of values,
/// each of which is used to distinguish a type of user, that describes who can be a participant of the conversation.
///
public enum ConversationAccessRoleV2: String {
/// Users with Wire accounts belonging to the same team owning the conversation.
case teamMember = "team_member"
/// Users with Wire accounts belonging to another team or no team.
case nonTeamMember = "non_team_member"
/// Users without Wire accounts, or wireless users (i.e users who join with a guest link and temporary account).
case guest = "guest"
/// A service pseudo-user, aka a non-human bot.
case service = "service"
public static func fromLegacyAccessRole(_ accessRole: ConversationAccessRole) -> Set<Self> {
switch accessRole {
case .team:
return [.teamMember]
case .activated:
return [.teamMember, .nonTeamMember, guest]
case .nonActivated:
return [.teamMember, .nonTeamMember, guest, .service]
case .private:
return []
}
}
}
public extension ConversationAccessRole {
static func value(forAllowGuests allowGuests: Bool) -> ConversationAccessRole {
return allowGuests ? ConversationAccessRole.nonActivated : ConversationAccessRole.team
}
}
extension ZMConversation: SwiftConversationLike {
@NSManaged dynamic internal var accessModeStrings: [String]?
@NSManaged dynamic internal var accessRoleString: String?
@NSManaged dynamic internal var accessRoleStringsV2: [String]?
public var sortedActiveParticipantsUserTypes: [UserType] {
return sortedActiveParticipants
}
public var teamType: TeamType? {
return team
}
public internal(set) var accessRoles: Set<ConversationAccessRoleV2> {
get {
guard let strings = accessRoleStringsV2 else {
return [.teamMember,
.nonTeamMember,
.guest,
.service]
}
return Set(strings.compactMap(ConversationAccessRoleV2.init))
}
set {
accessRoleStringsV2 = newValue.map(\.rawValue)
}
}
/// If set to false, only team member can join the conversation.
/// True means that a regular guest OR wireless guests could join
/// Controls the values of `accessMode` and `accessRoleV2`.
@objc public var allowGuests: Bool {
get {
return accessMode != .teamOnly && accessRoles.contains(.guest) && accessRoles.contains(.nonTeamMember)
}
set {
accessMode = ConversationAccessMode.value(forAllowGuests: newValue)
if newValue {
accessRoles.insert(.guest)
accessRoles.insert(.nonTeamMember)
} else {
accessRoles.remove(.guest)
accessRoles.remove(.nonTeamMember)
}
}
}
/// If set to false, only team member or guest can join the conversation.
/// True means that a service could join
/// Controls the value of `accessRoleV2`.
@objc public var allowServices: Bool {
get {
return accessRoles.contains(.service)
}
set {
if newValue {
accessRoles.insert(.service)
} else {
accessRoles.remove(.service)
}
}
}
// The conversation access mode is stored as an array of string in CoreData, cf. `acccessModeStrings`.
/// Defines how users can join a conversation.
public var accessMode: ConversationAccessMode? {
get {
guard let strings = self.accessModeStrings else {
return nil
}
return ConversationAccessMode(values: strings)
}
set {
guard let value = newValue else {
accessModeStrings = nil
return
}
accessModeStrings = value.stringValue
}
}
/// Defines who can join the conversation.
public var accessRole: ConversationAccessRole? {
get {
guard let strings = self.accessRoleString else {
return nil
}
return ConversationAccessRole(rawValue: strings)
}
set {
guard let value = newValue else {
accessRoleString = nil
return
}
accessRoleString = value.rawValue
}
}
}
| 5346cf5d484c5289a5d2b4b985d80663 | 34.384615 | 131 | 0.626316 | false | false | false | false |
machelix/ROKO.Stickers.Swift-Demo | refs/heads/master | ROKO.Stickers.iOS-Swift-Demo-APP/ViewController.swift | gpl-2.0 | 1 | //
// ViewController.swift
// ROKOStickersSwiftDemo
//
// Created by Maslov Sergey on 08.09.15.
// Copyright (c) 2015 ROKOLabs. All rights reserved.
//
import UIKit
let kROKOStickersShareContentTypeKey = "_ROKO.ImageWithStickers"
class ViewController: UIViewController, RLPhotoComposerDelegate {
var stickersScheme: ROKOStickersScheme?
var dataSource: ROKOPortalStickersDataSource = ROKOPortalStickersDataSource.init(manager: nil)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController!.navigationBarHidden = true
}
func loadStickersForController(controller : RLComposerWorkflowController!) {
weak var composer = controller.composer
dataSource.reloadStickersWithCompletionBlock { (_:AnyObject!, _:NSError!) -> Void in
composer?.reloadData()
}
}
// MARK: Button Interaction
@IBAction func choosePhotoButtonPressed(sender: AnyObject) {
if let workflowController = RLComposerWorkflowController.buildComposerWorkflowWithType(RLComposerWorkflowType.PhotoPicker, useROKOCMS: false) {
let photoComposer = workflowController.composer
photoComposer!.delegate = self
photoComposer!.dataSource = dataSource
self.loadStickersForController(workflowController);
self.presentViewController(workflowController, animated: true, completion: nil)
}
}
@IBAction func takePhotoButtonPressed(sender: AnyObject) {
if let workflowController = RLComposerWorkflowController.buildComposerWorkflowWithType(RLComposerWorkflowType.Camera, useROKOCMS: false) {
workflowController.composer.dataSource = dataSource
workflowController.composer.delegate = self
loadStickersForController(workflowController)
self.presentViewController(workflowController, animated: true, completion: nil)
}
}
// MARK: RLCameraViewController Delegate
func composer(composer: RLPhotoComposerController!, didFinishWithPhoto photo: UIImage!){
return
}
func composerDidCancel(composer: RLPhotoComposerController!) {
return
}
func composer(composer: RLPhotoComposerController!, willAppearAnimated animated: Bool) {
if (stickersScheme != nil) {
composer.scheme = stickersScheme!
}
}
func shareController(controller: RLPhotoComposerController!, willAppearAnimated animated: Bool) {
return
}
func composer(composer: RLPhotoComposerController!, didPressShareButtonForImage image: UIImage!){
if let controller = RSActivityViewController.buildController(){
controller.image = image
controller.displayMessage = "I made this for you on the ROKO Stickers app!"
controller.contentId = composer.photoId.UUIDString
controller.contentType = kROKOStickersShareContentTypeKey
composer.navigationController!.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
composer.navigationController!.presentViewController(controller, animated: true, completion: nil)
}
}
func composer(composer: RLPhotoComposerController!, didAddSticker stickerInfo: RLStickerInfo!) {
return
}
func composer(composer: RLPhotoComposerController!, didSwitchToStickerPackAtIndex packIndex: Int) {
return
}
func composer(composer: RLPhotoComposerController!, didRemoveSticker stickerInfo: RLStickerInfo!) {
return
}
}
| 8c61bbd476af385a0204dfeaa606a4cd | 36.212121 | 151 | 0.70874 | false | false | false | false |
alblue/swift-corelibs-foundation | refs/heads/master | Foundation/NSRange.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_SWIFT
import CoreFoundation
public struct _NSRange {
public var location: Int
public var length: Int
public init() {
location = 0
length = 0
}
public init(location: Int, length: Int) {
self.location = location
self.length = length
}
}
public typealias NSRange = _NSRange
public typealias NSRangePointer = UnsafeMutablePointer<NSRange>
public func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange {
return NSRange(location: loc, length: len)
}
public func NSMaxRange(_ range: NSRange) -> Int {
return range.location + range.length
}
public func NSLocationInRange(_ loc: Int, _ range: NSRange) -> Bool {
return !(loc < range.location) && (loc - range.location) < range.length
}
public func NSEqualRanges(_ range1: NSRange, _ range2: NSRange) -> Bool {
return range1.location == range2.location && range1.length == range2.length
}
public func NSUnionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange {
let max1 = range1.location + range1.length
let max2 = range2.location + range2.length
let maxend: Int
if max1 > max2 {
maxend = max1
} else {
maxend = max2
}
let minloc: Int
if range1.location < range2.location {
minloc = range1.location
} else {
minloc = range2.location
}
return NSRange(location: minloc, length: maxend - minloc)
}
public func NSIntersectionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange {
let max1 = range1.location + range1.length
let max2 = range2.location + range2.length
let minend: Int
if max1 < max2 {
minend = max1
} else {
minend = max2
}
if range2.location <= range1.location && range1.location < max2 {
return NSRange(location: range1.location, length: minend - range1.location)
} else if range1.location <= range2.location && range2.location < max1 {
return NSRange(location: range2.location, length: minend - range2.location)
}
return NSRange(location: 0, length: 0)
}
public func NSStringFromRange(_ range: NSRange) -> String {
return "{\(range.location), \(range.length)}"
}
public func NSRangeFromString(_ aString: String) -> NSRange {
let emptyRange = NSRange(location: 0, length: 0)
if aString.isEmpty {
// fail early if the string is empty
return emptyRange
}
let scanner = Scanner(string: aString)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharactersFromSet(digitSet)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return emptyRange
}
guard let location = scanner.scanInt() else {
return emptyRange
}
let partialRange = NSRange(location: location, length: 0)
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return partialRange
}
let _ = scanner.scanUpToCharactersFromSet(digitSet)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return partialRange
}
guard let length = scanner.scanInt() else {
return partialRange
}
return NSRange(location: location, length: length)
}
#else
@_exported import Foundation // Clang module
#endif
extension NSRange : Hashable {
public var hashValue: Int {
#if arch(i386) || arch(arm)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 16)))
#elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64le)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 32)))
#endif
}
public static func==(_ lhs: NSRange, _ rhs: NSRange) -> Bool {
return lhs.location == rhs.location && lhs.length == rhs.length
}
}
extension NSRange : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return "{\(location), \(length)}" }
public var debugDescription: String {
guard location != NSNotFound else {
return "{NSNotFound, \(length)}"
}
return "{\(location), \(length)}"
}
}
extension NSRange {
public init?(_ string: String) {
var savedLocation = 0
if string.isEmpty {
// fail early if the string is empty
return nil
}
let scanner = Scanner(string: string)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return nil
}
var location = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&location) else {
return nil
}
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return nil
}
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
location = integral
}
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return nil
}
var length = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&length) else {
return nil
}
if !scanner.isAtEnd {
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
length = integral
}
}
self.location = location
self.length = length
}
}
extension NSRange {
public var lowerBound: Int { return location }
public var upperBound: Int { return location + length }
public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) }
public mutating func formUnion(_ other: NSRange) {
self = union(other)
}
public func union(_ other: NSRange) -> NSRange {
let max1 = location + length
let max2 = other.location + other.length
let maxend = (max1 < max2) ? max2 : max1
let minloc = location < other.location ? location : other.location
return NSRange(location: minloc, length: maxend - minloc)
}
public func intersection(_ other: NSRange) -> NSRange? {
let max1 = location + length
let max2 = other.location + other.length
let minend = (max1 < max2) ? max1 : max2
if other.location <= location && location < max2 {
return NSRange(location: location, length: minend - location)
} else if location <= other.location && other.location < max1 {
return NSRange(location: other.location, length: minend - other.location);
}
return nil
}
}
//===----------------------------------------------------------------------===//
// Ranges
//===----------------------------------------------------------------------===//
extension NSRange {
public init<R: RangeExpression>(_ region: R)
where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger {
let r = region.relative(to: 0..<R.Bound.max)
location = numericCast(r.lowerBound)
length = numericCast(r.count)
}
public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S)
where R.Bound == S.Index, S.Index == String.Index {
let r = region.relative(to: target)
self = NSRange(
location: r.lowerBound.encodedOffset - target.startIndex.encodedOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset
)
}
@available(swift, deprecated: 4, renamed: "Range.init(_:)")
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}
extension Range where Bound: BinaryInteger {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound)))
}
}
// This additional overload will mean Range.init(_:) defaults to Range<Int> when
// no additional type context is provided:
extension Range where Bound == Int {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (range.lowerBound, range.upperBound))
}
}
extension Range where Bound == String.Index {
public init?(_ range: NSRange, in string: String) {
let u = string.utf16
guard range.location != NSNotFound,
let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
let lowerBound = String.Index(start, within: string),
let upperBound = String.Index(end, within: string)
else { return nil }
self = lowerBound..<upperBound
}
}
extension NSRange : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["location": location, "length": length])
}
}
extension NSRange : CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "NSRange.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .range(Int64(location), Int64(length))
}
}
extension NSRange : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let location = try container.decode(Int.self)
let length = try container.decode(Int.self)
self.init(location: location, length: length)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.location)
try container.encode(self.length)
}
}
#if DEPLOYMENT_RUNTIME_SWIFT
extension NSRange {
internal init(_ range: CFRange) {
location = range.location == kCFNotFound ? NSNotFound : range.location
length = range.length
}
}
extension CFRange {
internal init(_ range: NSRange) {
let _location = range.location == NSNotFound ? kCFNotFound : range.location
self.init(location: _location, length: range.length)
}
}
extension NSRange {
public init(_ x: Range<Int>) {
location = x.lowerBound
length = x.count
}
}
extension NSRange: NSSpecialValueCoding {
init(bytes: UnsafeRawPointer) {
self.location = bytes.load(as: Int.self)
self.length = bytes.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self)
}
init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if let location = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.location") {
self.location = location.intValue
} else {
self.location = 0
}
if let length = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.length") {
self.length = length.intValue
} else {
self.length = 0
}
}
func encodeWithCoder(_ aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(NSNumber(value: self.location), forKey: "NS.rangeval.location")
aCoder.encode(NSNumber(value: self.length), forKey: "NS.rangeval.length")
}
static func objCType() -> String {
#if arch(i386) || arch(arm)
return "{_NSRange=II}"
#elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
return "{_NSRange=QQ}"
#else
NSUnimplemented()
#endif
}
func getValue(_ value: UnsafeMutableRawPointer) {
value.initializeMemory(as: NSRange.self, repeating: self, count: 1)
}
func isEqual(_ aValue: Any) -> Bool {
if let other = aValue as? NSRange {
return other.location == self.location && other.length == self.length
} else {
return false
}
}
var hash: Int { return hashValue }
}
extension NSValue {
public convenience init(range: NSRange) {
self.init()
self._concreteValue = NSSpecialValue(range)
}
public var rangeValue: NSRange {
let specialValue = self._concreteValue as! NSSpecialValue
return specialValue._value as! NSRange
}
}
#endif
| 84afe44c5182dda03ba8caeb4026bd83 | 31.742925 | 117 | 0.609378 | false | false | false | false |
moonknightskye/Luna | refs/heads/master | Luna/Utility.swift | gpl-3.0 | 1 | //
// Utility.swift
// Salesforce Hybrid
//
// Created by Mart Civil on 2016/12/27.
// Copyright © 2016年 salesforce.com. All rights reserved.
//
import UIKit
import WebKit
import CoreData
import LocalAuthentication
class Utility: NSObject {
static let shared = Utility()
func showStatusBar() {
UIApplication.shared.isStatusBarHidden = false
}
func hideStatusBar() {
UIApplication.shared.isStatusBarHidden = true
}
func statusBarHeight() -> CGFloat {
let statusBarSize = UIApplication.shared.statusBarFrame.size
return Swift.min(statusBarSize.width, statusBarSize.height)
}
func getContext () -> NSManagedObjectContext {
return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
}
func dictionaryToJSON( dictonary:NSDictionary )-> String{
var allInfoJSONString: String?
do {
let allInfoJSON = try JSONSerialization.data(withJSONObject: dictonary, options: JSONSerialization.WritingOptions(rawValue: 0))
allInfoJSONString = (NSString(data: allInfoJSON, encoding: String.Encoding.utf8.rawValue)! as String).replacingOccurrences(of: "\'", with: "%27")
} catch let error as NSError {
print(error)
}
return allInfoJSONString!
}
func StringToDictionary( txt: String )-> NSDictionary? {
if let data = txt.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] as NSDictionary?
} catch {}
}
return nil
}
func executeOnFullPermission( execute:@escaping ((Bool)->()) ) {
UserNotification.instance.requestAuthorization { (isNotifPermitted) in
if( isNotifPermitted ) {
DispatchQueue.main.async {
Location.instance.checkPermissionAction = { isLocPermitted in
if isLocPermitted {
execute(true)
} else {
execute(false)
}
}
if( !Location.instance.isAccessPermitted ) {
Location.instance.requestAuthorization(status: .authorizedAlways)
} else {
Location.instance.checkPermissionAction?(true)
}
}
} else {
execute(false)
}
}
}
func splitDataToChunks( file:Data, onSplit:((Data)->()), onSuccess:((Bool)->()) ) {
let length = file.count
let chunkSize = (1024 * 1024) * 3
var offset = 0
var count = 0
repeat {
// get the length of the chunk
let thisChunkSize = ((length - offset) > chunkSize) ? chunkSize : (length - offset);
// get the chunk
onSplit( file.subdata(in: offset..<offset + thisChunkSize ) )
count+=1
print("processing chunk # \(count)")
// update the offset
offset += thisChunkSize;
} while (offset < length);
onSuccess( true )
}
func StringToData( txt: String ) -> Data {
return txt.data(using: .utf8, allowLossyConversion: false)!
}
func DataToString( data: Data ) -> String {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
}
func DataToBase64( data: Data ) -> String {
return data.base64EncodedString()
// return data.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
}
func DictionaryToData( dict: NSDictionary ) -> Data {
return NSKeyedArchiver.archivedData(withRootObject: dict)
}
func DataToDictionary( data:Data ) -> NSDictionary {
return NSKeyedUnarchiver.unarchiveObject(with: data) as? [String : Any] as NSDictionary!
}
func degrees(radians:Double) -> Double {
return ( 180 / Double.pi ) * radians
}
func printDictionary( dictonary:NSDictionary ) {
for (key, _) in dictonary {
print( key )
print( dictonary[ key ]! )
}
}
func getDimentionScaleValue( originalDimention:CGRect, resizedDimention:CGRect ) -> CGFloat {
let width = 1 - ((originalDimention.width - resizedDimention.width) / originalDimention.width)
let height = 1 - ((originalDimention.height - resizedDimention.height) / originalDimention.height)
return CGFloat(max(width, height))
}
func getScaledDimention( dimention:CGRect, scale:CGFloat ) -> CGRect {
return CGRect(x: dimention.origin.x, y: dimention.origin.y, width: dimention.width * scale, height: dimention.height * scale)
}
func getAspectRatioCoordinates( origin:CGPoint, originalDimention:CGRect, resizedDimention:CGRect ) -> CGPoint {
let x = ((1-origin.y) * originalDimention.width) - ((originalDimention.width - resizedDimention.width) / 2)
let y = (origin.x * originalDimention.height) - ((originalDimention.height - resizedDimention.height) / 2)
return CGPoint(x: x, y: y)
}
}
| f4892578b1b166b51ceead44e12e7d86 | 35.172414 | 157 | 0.603241 | false | false | false | false |
dcutting/Syft | refs/heads/master | Sources/Sample/Song.swift | mit | 1 | import Syft
enum SongExpressionError: Error {
case unknown
}
protocol SongExpression {
func evaluate() -> String
}
struct SongNumber: SongExpression {
let value: Int
func evaluate() -> String {
return "\(value)"
}
}
//func song() -> Pipeline<SongExpression> {
//// let input = "[].length() = 0\n[_|y].length() = 1.+(y.length())"
// let input = ""
// return Pipeline(defaultInput: input, parser: makeParser(), transformer: makeTransformer()) { ast in
// let result = ast.evaluate()
// return "\(result)"
// }
//}
| 375635a52e69ff474f1f337a3fe69ffb | 20.185185 | 105 | 0.590909 | false | false | false | false |
EasySwift/EasySwift | refs/heads/master | Carthage/Checkouts/YXJKxMenu/YXJKxMenuTest/YXJKxMenuTest/ViewController.swift | apache-2.0 | 2 | //
// ViewController.swift
// YXJKxMenuTest
//
// Created by yuanxiaojun on 16/8/9.
// Copyright © 2016年 袁晓钧. All rights reserved.
//
import UIKit
import YXJKxMenu
class ViewController: UIViewController {
var ScreenWidth: CGFloat {
return UIScreen.main.bounds.size.width
}
var ScreenHeight: CGFloat {
return UIScreen.main.bounds.size.height
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showMenu(_ sender: UIButton) {
var menuArray: [YXJKxMenuItem] = []
for i in 0..<4 {
let menuItem = YXJKxMenuItem("选项\(i)", image: UIImage(named: "\(i)"), target: self, action: #selector(ViewController.choiceTypeResult(_:)))
menuArray.append(menuItem!)
}
YXJKxMenu.setTitleFont(UIFont.systemFont(ofSize: 14))
let option = OptionalConfiguration(
arrowSize: 10,
marginXSpacing: 10,
marginYSpacing: 10,
intervalSpacing: 10,
menuCornerRadius: 3,
maskToBackground: true,
shadowOfMenu: false,
hasSeperatorLine: true,
seperatorLineHasInsets: false,
textColor: Color(R: 82 / 255.0, G: 82 / 255.0, B: 82 / 255.0),
menuBackgroundColor: Color(R: 1, G: 1, B: 1),
setWidth: (ScreenWidth - 15 * 2) / 2)
let rect = CGRect(x: sender.frame.origin.x, y: 0, width: sender.frame.size.width, height: 64)
// 特别说明,这里的fromRect之所以没有直接使用sender.frame是因为该button的高度并没有占满整个navigationBar的高度,所以直接填写的titleBar加上navigationBar的高度(64)
YXJKxMenu.show(in: self.view, from: rect, menuItems: menuArray, withOptions: option)
}
@IBAction func showMenu1(_ sender: UIButton) {
var menuArray: [YXJKxMenuItem] = []
for i in 0..<5 {
let menuItem = YXJKxMenuItem("选项\(i)", image: nil, target: self, action: #selector(ViewController.choiceTypeResult(_:)))
menuArray.append(menuItem!)
}
YXJKxMenu.setTitleFont(UIFont.systemFont(ofSize: 14))
let option = OptionalConfiguration(
arrowSize: 10,
marginXSpacing: 10,
marginYSpacing: 10,
intervalSpacing: 30,
menuCornerRadius: 3,
maskToBackground: true,
shadowOfMenu: false,
hasSeperatorLine: true,
seperatorLineHasInsets: false,
textColor: Color(R: 82 / 255.0, G: 82 / 255.0, B: 82 / 255.0),
menuBackgroundColor: Color(R: 1, G: 1, B: 1),
setWidth: 0)
// 特别说明,这里直接使用sender.frame是因为该框架能正确计算出YXJKxMenu将展示的位置
YXJKxMenu.show(in: self.view, from: sender.frame, menuItems: menuArray, withOptions: option)
}
// MAKR:实现YXJKxMenu协议
func choiceTypeResult(_ item: YXJKxMenuItem) {
print(item.title)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 45c94cc2dcdf6f7a50d237396d66e4f6 | 30.709677 | 151 | 0.60902 | false | false | false | false |
szweier/SZMentionsSwift | refs/heads/master | SZMentionsSwiftTests/MentionsDisplayTests.swift | mit | 1 | @testable import SZMentionsSwift
import XCTest
private final class MentionsDisplay: XCTestCase {
var hidingMentionsList: Bool!
var mentionsString: String!
var triggerString: String!
var mentionsListener: MentionListener!
var textView: UITextView!
func hideMentions() { hidingMentionsList = true }
func showMentions(mention: String, trigger: String) {
hidingMentionsList = false
mentionsString = mention
triggerString = trigger
}
override func setUp() {
super.setUp()
textView = UITextView()
}
override func tearDown() {
super.tearDown()
textView = nil
mentionsListener = nil
triggerString = nil
mentionsString = nil
hidingMentionsList = nil
}
func test_shouldShowTheMentionsListWhenTypingAMentionAndHideWhenASpaceIsAdded_whenSearchSpacesIsFalse() {
mentionsListener = generateMentionsListener(searchSpacesInMentions: false, spaceAfterMention: false)
textView.insertText("@t")
XCTAssertFalse(hidingMentionsList)
XCTAssertEqual(mentionsString, "t")
XCTAssertEqual(triggerString, "@")
textView.insertText(" ")
XCTAssertTrue(hidingMentionsList)
}
func test_shouldShowTheMentionsListWhenTypingAMentionAndRemainVisibleWhenASpaceIsAdded_whenSearchSpacesIsTrue() {
mentionsListener = generateMentionsListener(searchSpacesInMentions: true, spaceAfterMention: false)
textView.insertText("@t")
XCTAssertFalse(hidingMentionsList)
XCTAssertEqual(mentionsString, "t")
XCTAssertEqual(triggerString, "@")
textView.insertText(" ")
XCTAssertFalse(hidingMentionsList)
}
func test_shouldShowTheMentionsListWhenTypingAMentionOnANewLineAndHideWhenASpaceIsAdded_whenSearchSpacesIsFalse() {
mentionsListener = generateMentionsListener(searchSpacesInMentions: false, spaceAfterMention: false)
textView.insertText("\n@t")
XCTAssertFalse(hidingMentionsList)
XCTAssertEqual(mentionsString, "t")
XCTAssertEqual(triggerString, "@")
textView.insertText(" ")
XCTAssertTrue(hidingMentionsList)
}
func test_shouldShowTheMentionsListWhenTypingAMentionOnANewLineAndRemainVisibleWhenASpaceIsAdded_whenSearchSpacesIsTrue() {
mentionsListener = generateMentionsListener(searchSpacesInMentions: true, spaceAfterMention: false)
textView.insertText("\n@t")
XCTAssertFalse(hidingMentionsList)
XCTAssertEqual(mentionsString, "t")
XCTAssertEqual(triggerString, "@")
textView.insertText(" ")
XCTAssertFalse(hidingMentionsList)
}
func test_shouldSetCursorAfterAddedSpaceWhenAddAMention_whenSpacesAfterMentionIsTrue() {
mentionsListener = generateMentionsListener(searchSpacesInMentions: true, spaceAfterMention: true)
textView.text = ""
textView.insertText("@a")
addMention(named: "@awesome", on: mentionsListener)
XCTAssertEqual("@awesome ".count, textView.selectedRange.location)
}
func generateMentionsListener(searchSpacesInMentions: Bool, spaceAfterMention: Bool) -> MentionListener {
return MentionListener(mentionsTextView: textView,
spaceAfterMention: spaceAfterMention,
searchSpaces: searchSpacesInMentions,
hideMentions: hideMentions,
didHandleMentionOnReturn: { true },
showMentionsListWithString: showMentions)
}
}
| e273fecb4780714022256b179bff093f | 34.441176 | 127 | 0.694606 | false | true | false | false |
HTWDD/HTWDresden-iOS | refs/heads/master | HTWDD/Main Categories/General/Models/SemesterInformation.swift | gpl-2.0 | 1 | //
// SemesterInformation.swift
// HTWDD
//
// Created by Benjamin Herzog on 05/03/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
import Marshal
struct SemesterInformation: Codable {
let semester: Semester
var year: Int {
return semester.year
}
let period: EventPeriod
let freeDays: Set<Event>
let lectures: EventPeriod
let exams: EventPeriod
let reregistration: EventPeriod
// static func get(network: Network) -> Observable<[SemesterInformation]> {
// return network.getArrayM(url: SemesterInformation.url)
// }
static func information(date: Date, input: [SemesterInformation]) -> SemesterInformation? {
for e in input {
if e.contains(date: date) {
return e
}
}
return nil
}
func contains(date: Date) -> Bool {
guard let eventDate = EventDate(date: date) else {
return false
}
return self.period.contains(date: eventDate)
}
func lecturesContains(date: Date) -> Bool {
guard let eventDate = EventDate(date: date) else {
return false
}
return self.lectures.contains(date: eventDate)
}
func freeDayContains(date: Date) -> Event? {
guard let eventDate = EventDate(date: date) else {
return nil
}
for d in self.freeDays {
if d.period.contains(date: eventDate) {
return d
}
}
return nil
}
}
extension SemesterInformation: Equatable {
static func ==(lhs: SemesterInformation, rhs: SemesterInformation) -> Bool {
return lhs.semester == rhs.semester
}
}
extension SemesterInformation: Unmarshaling {
static let url = "https://www2.htw-dresden.de/~app/API/semesterplan.json"
init(object: MarshaledObject) throws {
let year: Int = try object <| "year"
let type: String = try object <| "type"
if type == "W" {
self.semester = .winter(year: year)
} else if type == "S" {
self.semester = .summer(year: year)
} else {
throw MarshalError.typeMismatch(expected: Semester.self, actual: "\(year)\(type)")
}
self.period = try object <| "period"
let freeDays: [Event] = try object <| "freeDays"
self.freeDays = Set(freeDays)
self.lectures = try object <| "lecturePeriod"
self.exams = try object <| "examsPeriod"
self.reregistration = try object <| "reregistration"
}
}
| 4d31978186c7aecf508fcef99327595a | 26.553191 | 95 | 0.596525 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.