hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
61473610f24abe1dcdb3631d831e35c8edd2637b | 2,333 | //
// LogsReporterTests.swift
// DiagnosticsTests
//
// Created by Antoine van der Lee on 03/12/2019.
// Copyright © 2019 WeTransfer. All rights reserved.
//
import XCTest
@testable import Diagnostics
final class LogsReporterTests: XCTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
try DiagnosticsLogger.setup()
}
override func tearDownWithError() throws {
try DiagnosticsLogger.standard.deleteLogs()
try super.tearDownWithError()
}
/// It should show logged messages.
func testMessagesLog() throws {
let message = UUID().uuidString
DiagnosticsLogger.log(message: message)
let diagnostics = LogsReporter().report().diagnostics as! String
XCTAssertTrue(diagnostics.contains(message), "Diagnostics is \(diagnostics)")
XCTAssertEqual(diagnostics.debugLogs.count, 1)
let debugLog = try XCTUnwrap(diagnostics.debugLogs.first)
XCTAssertTrue(debugLog.contains("<span class=\"log-prefix\">LogsReporterTests.swift:L27</span>"), "Prefix should be added")
XCTAssertTrue(debugLog.contains("<span class=\"log-message\">\(message)</span>"), "Log message should be added")
}
/// It should show errors.
func testErrorLog() throws {
enum Error: Swift.Error {
case testCase
}
DiagnosticsLogger.log(error: Error.testCase)
let diagnostics = LogsReporter().report().diagnostics as! String
XCTAssertTrue(diagnostics.contains("testCase"))
XCTAssertEqual(diagnostics.errorLogs.count, 1)
let errorLog = try XCTUnwrap(diagnostics.errorLogs.first)
XCTAssertTrue(errorLog.contains("<span class=\"log-message\">ERROR: testCase"))
}
/// It should reverse the order of sessions to have the most recent session on top.
func testReverseSessions() throws {
DiagnosticsLogger.log(message: "first")
DiagnosticsLogger.standard.startNewSession()
DiagnosticsLogger.log(message: "second")
let diagnostics = LogsReporter().report().diagnostics as! String
let firstIndex = try XCTUnwrap(diagnostics.range(of: "first")?.lowerBound)
let secondIndex = try XCTUnwrap(diagnostics.range(of: "second")?.lowerBound)
XCTAssertTrue(firstIndex > secondIndex)
}
}
| 37.629032 | 131 | 0.68667 |
def5edb3599654438fdd94d5aed77a9dd9e51780 | 5,577 | // MIT License
// Copyright (c) 2017 Haik Aslanyan
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class MainVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//MARK: Properties
@IBOutlet var tabBarView: TabBarView!
@IBOutlet weak var collectionView: UICollectionView!
var views = [UIView]()
//MARK: Methods
func customization() {
self.view.backgroundColor = UIColor.rbg(r: 228, g: 34, b: 24)
//CollectionView Setup
self.collectionView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
self.collectionView.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: (self.view.bounds.height))
//TabbarView setup
self.view.addSubview(self.tabBarView)
self.tabBarView.translatesAutoresizingMaskIntoConstraints = false
let _ = NSLayoutConstraint.init(item: self.view, attribute: .top, relatedBy: .equal, toItem: self.tabBarView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
let _ = NSLayoutConstraint.init(item: self.view, attribute: .left, relatedBy: .equal, toItem: self.tabBarView, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
let _ = NSLayoutConstraint.init(item: self.view, attribute: .right, relatedBy: .equal, toItem: self.tabBarView, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
self.tabBarView.heightAnchor.constraint(equalToConstant: 64).isActive = true
//ViewController init
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC")
let trendingVC = self.storyboard?.instantiateViewController(withIdentifier: "TrendingVC")
let subscriptionsVC = self.storyboard?.instantiateViewController(withIdentifier: "SubscriptionsVC")
let accountVC = self.storyboard?.instantiateViewController(withIdentifier: "AccountVC")
let viewControllers = [homeVC, trendingVC, subscriptionsVC, accountVC]
for vc in viewControllers {
self.addChildViewController(vc!)
vc!.didMove(toParentViewController: self)
vc!.view.frame = CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: (self.view.bounds.height - 44))
self.views.append(vc!.view)
}
self.collectionView.reloadData()
//NotificationCenter setup
NotificationCenter.default.addObserver(self, selector: #selector(self.scrollViews(notification:)), name: Notification.Name.init(rawValue: "didSelectMenu"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.hideBar(notification:)), name: NSNotification.Name("hide"), object: nil)
}
func scrollViews(notification: Notification) {
if let info = notification.userInfo {
let userInfo = info as! [String: Int]
self.collectionView.scrollToItem(at: IndexPath.init(row: userInfo["index"]!, section: 0), at: .centeredHorizontally, animated: true)
}
}
func hideBar(notification: NSNotification) {
let state = notification.object as! Bool
self.navigationController?.setNavigationBarHidden(state, animated: true)
}
//MARK: Delegates
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.views.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.contentView.addSubview(self.views[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: self.collectionView.bounds.width, height: (self.collectionView.bounds.height + 22))
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollIndex = scrollView.contentOffset.x / self.view.bounds.width
NotificationCenter.default.post(name: Notification.Name.init(rawValue: "scrollMenu"), object: nil, userInfo: ["length": scrollIndex])
}
//MARK: ViewController lifecyle
override func viewDidLoad() {
super.viewDidLoad()
self.customization()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| 53.114286 | 184 | 0.71508 |
9c2160856977802e23b313afe76509f6dcb16671 | 33,374 | //
// File.swift
//
//
// Created by William Vabrinskas on 1/22/22.
//
import Foundation
import Accelerate
public extension Array where Element == [Double] {
func zeroPad(filterSize: (Int, Int), stride: (Int, Int) = (1,1)) -> Self {
guard let first = self.first else {
return self
}
let height = Double(self.count)
let width = Double(first.count)
let outHeight = ceil(height / Double(stride.0))
let outWidth = ceil(width / Double(stride.1))
let padAlongHeight = Swift.max((outHeight - 1) * Double(stride.0) + Double(filterSize.0) - height, 0)
let padAlongWidth = Swift.max((outWidth - 1) * Double(stride.1) + Double(filterSize.1) - width, 0)
let paddingTop = Int(floor(padAlongHeight / 2))
let paddingBottom = Int(padAlongHeight - Double(paddingTop))
let paddingLeft = Int(floor(padAlongWidth / 2))
let paddingRight = Int(padAlongWidth - Double(paddingLeft))
var result: [Element] = self
let newRow = [Double](repeating: 0, count: first.count)
//top / bottom comes first so we can match row insertion
for _ in 0..<paddingTop {
result.insert(newRow, at: 0)
}
for _ in 0..<paddingBottom {
result.append(newRow)
}
var paddingLeftMapped: [[Double]] = []
result.forEach { v in
var row = v
for _ in 0..<paddingLeft {
row.insert(0, at: 0)
}
paddingLeftMapped.append(row)
}
result = paddingLeftMapped
var paddingRightMapped: [[Double]] = []
result.forEach { v in
var row = v
for _ in 0..<paddingRight {
row.append(0)
}
paddingRightMapped.append(row)
}
result = paddingRightMapped
return result
}
func zeroPad() -> Self {
guard let first = self.first else {
return self
}
let result: [Element] = self
let mapped = result.map { r -> [Double] in
var newR: [Double] = [0]
newR.append(contentsOf: r)
newR.append(0)
return newR
}
let zeros = [Double](repeating: 0, count: first.count + 2)
var r = [zeros]
r.append(contentsOf: mapped)
r.append(zeros)
return r
}
func transConv2d(_ filter: [[Double]],
strides: (rows: Int, columns: Int) = (1,1),
padding: NumSwift.ConvPadding = .valid,
filterSize: (rows: Int, columns: Int),
inputSize: (rows: Int, columns: Int)) -> Element {
let result: Element = NumSwift.transConv2D(signal: self,
filter: filter,
strides: strides,
padding: padding,
filterSize: filterSize,
inputSize: inputSize).flatten()
return result
}
func flip180() -> Self {
self.reversed().map { $0.reverse() }
}
}
public extension Array where Element == [Float] {
func zeroPad(padding: NumSwiftPadding) -> Self {
guard let first = self.first else {
return self
}
let paddingTop = padding.top
let paddingLeft = padding.left
let paddingRight = padding.right
let paddingBottom = padding.bottom
var result: [Element] = self
let newRow = [Float](repeating: 0, count: first.count)
//top / bottom comes first so we can match row insertion
for _ in 0..<paddingTop {
result.insert(newRow, at: 0)
}
for _ in 0..<paddingBottom {
result.append(newRow)
}
var paddingLeftMapped: [[Float]] = []
result.forEach { v in
var row = v
for _ in 0..<paddingLeft {
row.insert(0, at: 0)
}
paddingLeftMapped.append(row)
}
result = paddingLeftMapped
var paddingRightMapped: [[Float]] = []
result.forEach { v in
var row = v
for _ in 0..<paddingRight {
row.append(0)
}
paddingRightMapped.append(row)
}
result = paddingRightMapped
return result
}
func stridePad(strides: (rows: Int, columns: Int), shrink: Int = 0) -> Self {
var result = stridePad(strides: strides)
result = result.shrink(by: shrink)
return result
}
func stridePad(strides: (rows: Int, columns: Int), padding: Int = 0) -> Self {
var result = stridePad(strides: strides)
for _ in 0..<padding {
result = result.zeroPad()
}
return result
}
func zeroPad(filterSize: (Int, Int), stride: (Int, Int) = (1,1)) -> Self {
guard let first = self.first else {
return self
}
let height = Double(self.count)
let width = Double(first.count)
let outHeight = ceil(height / Double(stride.0))
let outWidth = ceil(width / Double(stride.1))
let padAlongHeight = Swift.max((outHeight - 1) * Double(stride.0) + Double(filterSize.0) - height, 0)
let padAlongWidth = Swift.max((outWidth - 1) * Double(stride.1) + Double(filterSize.1) - width, 0)
let paddingTop = Int(floor(padAlongHeight / 2))
let paddingBottom = Int(padAlongHeight - Double(paddingTop))
let paddingLeft = Int(floor(padAlongWidth / 2))
let paddingRight = Int(padAlongWidth - Double(paddingLeft))
let paddingObc = NumSwiftPadding(top: paddingTop,
left: paddingLeft,
right: paddingRight,
bottom: paddingBottom)
return self.zeroPad(padding: paddingObc)
}
func zeroPad() -> Self {
guard let first = self.first else {
return self
}
let result: [Element] = self
let mapped = result.map { r -> [Float] in
var newR: [Float] = [0]
newR.append(contentsOf: r)
newR.append(0)
return newR
}
let zeros = [Float](repeating: 0, count: first.count + 2)
var r = [zeros]
r.append(contentsOf: mapped)
r.append(zeros)
return r
}
func shrink(by size: Int) -> Self {
var results: [[Float]] = self
for _ in 0..<size {
var newResult: [[Float]] = []
results.forEach { p in
var newRow: [Float] = p
newRow.removeFirst()
newRow.removeLast()
newResult.append(newRow)
}
results = newResult
results.removeFirst()
results.removeLast()
}
return results
}
func stridePad(strides: (rows: Int, columns: Int)) -> Self {
guard let firstCount = self.first?.count else {
return self
}
let numToPad = (strides.rows - 1, strides.columns - 1)
let newRows = count + ((strides.rows - 1) * (count - 1))
let newColumns = firstCount + ((strides.columns - 1) * (count - 1))
var result: [[Float]] = NumSwift.zerosLike((rows: newRows, columns: newColumns))
var mutableSelf: [Float] = self.flatten()
if numToPad.0 > 0 || numToPad.1 > 0 {
for r in stride(from: 0, to: newRows, by: strides.rows) {
for c in stride(from: 0, to: newColumns, by: strides.columns) {
result[r][c] = mutableSelf.removeFirst()
}
}
} else {
return self
}
return result
}
func transConv2d(_ filter: [[Float]],
strides: (rows: Int, columns: Int) = (1,1),
padding: NumSwift.ConvPadding = .valid,
filterSize: (rows: Int, columns: Int),
inputSize: (rows: Int, columns: Int)) -> Element {
let result: Element = NumSwift.transConv2D(signal: self,
filter: filter,
strides: strides,
padding: padding,
filterSize: filterSize,
inputSize: inputSize).flatten()
return result
}
func flip180() -> Self {
self.reversed().map { $0.reverse() }
}
}
//use accelerate
public extension Array where Element == Float {
var sum: Element {
vDSP.sum(self)
}
var sumOfSquares: Element {
let stride = vDSP_Stride(1)
let n = vDSP_Length(self.count)
var c: Element = .nan
vDSP_svesq(self,
stride,
&c,
n)
return c
}
var indexOfMin: (UInt, Element) {
vDSP.indexOfMinimum(self)
}
var indexOfMax: (UInt, Element) {
vDSP.indexOfMaximum(self)
}
var max: Element {
vDSP.maximum(self)
}
var min: Element {
vDSP.minimum(self)
}
var mean: Element {
vDSP.mean(self)
}
mutating func fillZeros() {
vDSP.fill(&self, with: .zero)
}
@inlinable mutating func clip(_ to: Element) {
self = self.map { Swift.max(-to, Swift.min(to, $0)) }
}
@inlinable mutating func l1Normalize(limit: Element) {
//normalize gradients
let norm = self.sum
if norm > limit {
self = self / norm
}
}
/// Will normalize the vector using the L2 norm to 1.0 if the sum of squares is greater than the limit
/// - Parameter limit: the sumOfSquares limit that when reached it should normalize
@inlinable mutating func l2Normalize(limit: Element) {
//normalize gradients
let norm = self.sumOfSquares
if norm > limit {
let length = sqrt(norm)
self = self / length
}
}
/// Normalizes input to have 0 mean and 1 unit standard deviation
@discardableResult
@inlinable mutating func normalize() -> (mean: Element, std: Element) {
var mean: Float = 0
var std: Float = 0
var result: [Float] = [Float](repeating: 0, count: self.count)
vDSP_normalize(self,
vDSP_Stride(1),
&result,
vDSP_Stride(1),
&mean,
&std,
vDSP_Length(self.count))
self = result
return (mean, std)
}
func reverse() -> Self {
var result = self
vDSP.reverse(&result)
return result
}
func dot(_ b: [Element]) -> Element {
let n = vDSP_Length(self.count)
var C: Element = .nan
let aStride = vDSP_Stride(1)
let bStride = vDSP_Stride(1)
vDSP_dotpr(self,
aStride,
b,
bStride,
&C,
n)
return C
}
func multiply(B: [Element], columns: Int32, rows: Int32, dimensions: Int32 = 1) -> [Element] {
let M = vDSP_Length(dimensions)
let N = vDSP_Length(columns)
let K = vDSP_Length(rows)
var C: [Element] = [Element].init(repeating: 0, count: Int(N))
let aStride = vDSP_Stride(1)
let bStride = vDSP_Stride(1)
let cStride = vDSP_Stride(1)
vDSP_mmul(self,
aStride,
B,
bStride,
&C,
cStride,
vDSP_Length(M),
vDSP_Length(N),
vDSP_Length(K))
return C
}
func transpose(columns: Int, rows: Int) -> [Element] {
var result: [Element] = [Element].init(repeating: 0, count: columns * rows)
vDSP_mtrans(self,
vDSP_Stride(1),
&result,
vDSP_Stride(1),
vDSP_Length(columns),
vDSP_Length(rows))
return result
}
static func +(lhs: [Element], rhs: Element) -> [Element] {
return vDSP.add(rhs, lhs)
}
static func +(lhs: Element, rhs: [Element]) -> [Element] {
return vDSP.add(lhs, rhs)
}
static func +(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.add(rhs, lhs)
}
static func -(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.subtract(lhs, rhs)
}
static func *(lhs: [Element], rhs: Element) -> [Element] {
return vDSP.multiply(rhs, lhs)
}
static func *(lhs: Element, rhs: [Element]) -> [Element] {
return vDSP.multiply(lhs, rhs)
}
static func *(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.multiply(lhs, rhs)
}
static func /(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.divide(lhs, rhs)
}
static func /(lhs: [Element], rhs: Element) -> [Element] {
return vDSP.divide(lhs, rhs)
}
}
//use accelerate
public extension Array where Element == Double {
var sum: Element {
vDSP.sum(self)
}
var sumOfSquares: Element {
let stride = vDSP_Stride(1)
let n = vDSP_Length(self.count)
var c: Element = .nan
vDSP_svesqD(self,
stride,
&c,
n)
return c
}
var indexOfMin: (UInt, Element) {
vDSP.indexOfMinimum(self)
}
var indexOfMax: (UInt, Element) {
vDSP.indexOfMaximum(self)
}
var mean: Element {
vDSP.mean(self)
}
var max: Element {
vDSP.maximum(self)
}
var min: Element {
vDSP.minimum(self)
}
@inlinable mutating func clip(_ to: Element) {
self = self.map { Swift.max(-to, Swift.min(to, $0)) }
}
@inlinable mutating func l1Normalize(limit: Element) {
//normalize gradients
let norm = self.sum
if norm > limit {
self = self / norm
}
}
/// Will normalize the vector using the L2 norm to 1.0 if the sum of squares is greater than the limit
/// - Parameter limit: the sumOfSquares limit that when reached it should normalize
@inlinable mutating func l2Normalize(limit: Element) {
//normalize gradients
let norm = self.sumOfSquares
if norm > limit {
let length = sqrt(norm)
self = self / length
}
}
/// Normalizes input to have 0 mean and 1 unit standard deviation
@discardableResult
@inlinable mutating func normalize() -> (mean: Element, std: Element) {
var mean: Element = 0
var std: Element = 0
var result: [Element] = [Element](repeating: 0, count: self.count)
vDSP_normalizeD(self,
vDSP_Stride(1),
&result,
vDSP_Stride(1),
&mean,
&std,
vDSP_Length(self.count))
self = result
return (mean, std)
}
func reverse() -> Self {
var result = self
vDSP.reverse(&result)
return result
}
mutating func fillZeros() {
vDSP.fill(&self, with: .zero)
}
func dot(_ b: [Element]) -> Element {
let n = vDSP_Length(self.count)
var C: Element = .nan
let aStride = vDSP_Stride(1)
let bStride = vDSP_Stride(1)
vDSP_dotprD(self,
aStride,
b,
bStride,
&C,
n)
return C
}
func multiply(B: [Element], columns: Int32, rows: Int32, dimensions: Int32 = 1) -> [Element] {
let M = vDSP_Length(dimensions)
let N = vDSP_Length(columns)
let K = vDSP_Length(rows)
var C: [Element] = [Element].init(repeating: 0, count: Int(N))
let aStride = vDSP_Stride(1)
let bStride = vDSP_Stride(1)
let cStride = vDSP_Stride(1)
vDSP_mmulD(self,
aStride,
B,
bStride,
&C,
cStride,
vDSP_Length(M),
vDSP_Length(N),
vDSP_Length(K))
return C
}
func transpose(columns: Int, rows: Int) -> [Element] {
var result: [Element] = [Element].init(repeating: 0, count: columns * rows)
vDSP_mtransD(self,
vDSP_Stride(1),
&result,
vDSP_Stride(1),
vDSP_Length(columns),
vDSP_Length(rows))
return result
}
static func +(lhs: [Element], rhs: Element) -> [Element] {
return vDSP.add(rhs, lhs)
}
static func +(lhs: Element, rhs: [Element]) -> [Element] {
return vDSP.add(lhs, rhs)
}
static func +(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.add(rhs, lhs)
}
static func -(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.subtract(lhs, rhs)
}
static func *(lhs: [Element], rhs: Element) -> [Element] {
return vDSP.multiply(rhs, lhs)
}
static func *(lhs: Element, rhs: [Element]) -> [Element] {
return vDSP.multiply(lhs, rhs)
}
static func *(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.multiply(lhs, rhs)
}
static func /(lhs: [Element], rhs: [Element]) -> [Element] {
return vDSP.divide(lhs, rhs)
}
static func /(lhs: [Element], rhs: Element) -> [Element] {
return vDSP.divide(lhs, rhs)
}
static func /(lhs: Element, rhs: [Element]) -> [Element] {
return vDSP.divide(rhs, lhs)
}
}
public extension Array where Element: Equatable & Numeric & FloatingPoint {
var average: Element {
let sum = self.sumSlow
return sum / Element(self.count)
}
func scale(_ range: ClosedRange<Element> = 0...1) -> [Element] {
let max = self.max() ?? 0
let min = self.min() ?? 0
let b = range.upperBound
let a = range.lowerBound
let new = self.map { x -> Element in
let ba = (b - a)
let numerator = x - min
let denominator = max - min
return ba * (numerator / denominator) + a
}
return new
}
func scale(from range: ClosedRange<Element> = 0...1,
to toRange: ClosedRange<Element> = 0...1) -> [Element] {
let max = range.upperBound
let min = range.lowerBound
let b = toRange.upperBound
let a = toRange.lowerBound
let new = self.map { x -> Element in
let ba = (b - a)
let numerator = x - min
let denominator = max - min
return ba * (numerator / denominator) + a
}
return new
}
static func -(lhs: [Element], rhs: Element) -> [Element] {
return lhs.map({ $0 - rhs })
}
static func -(lhs: Element, rhs: [Element]) -> [Element] {
return rhs.map({ lhs - $0 })
}
}
public extension Array where Element == [[Double]] {
static func *(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] * right[d][r])
}
result.append(new2d)
}
return result
}
static func /(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] / right[d][r])
}
result.append(new2d)
}
return result
}
static func -(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] - right[d][r])
}
result.append(new2d)
}
return result
}
static func +(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] + right[d][r])
}
result.append(new2d)
}
return result
}
}
public extension Array where Element == [[Float]] {
var sumOfSquares: Float {
var result: Float = 0
self.forEach { a in
a.forEach { b in
let stride = vDSP_Stride(1)
let n = vDSP_Length(b.count)
var c: Float = .nan
vDSP_svesq(b,
stride,
&c,
n)
result += c
}
}
return result
}
var mean: Float {
var r: Float = 0
var total = 0
self.forEach { a in
a.forEach { b in
r += b.mean
total += 1
}
}
return r / Float(total)
}
var sum: Float {
var r: Float = 0
self.forEach { a in
a.forEach { b in
r += b.sum
}
}
return r
}
static func *(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d].map { $0 * rhs }
result.append(new2d)
}
return result
}
static func *(lhs: Float, rhs: Self) -> Self {
var result: Self = []
for d in 0..<rhs.count {
let new2d: Element = rhs[d].map { $0 * lhs }
result.append(new2d)
}
return result
}
static func /(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d].map { $0 / rhs }
result.append(new2d)
}
return result
}
static func +(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d].map { $0 + rhs }
result.append(new2d)
}
return result
}
static func +(lhs: Float, rhs: Self) -> Self {
var result: Self = []
for d in 0..<rhs.count {
let new2d: Element = rhs[d].map { $0 + lhs }
result.append(new2d)
}
return result
}
static func -(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d].map { $0 - rhs }
result.append(new2d)
}
return result
}
static func *(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] * right[d][r])
}
result.append(new2d)
}
return result
}
static func /(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] / right[d][r])
}
result.append(new2d)
}
return result
}
static func -(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] - right[d][r])
}
result.append(new2d)
}
return result
}
static func +(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = leftShape[safe: 2] ?? 0
let rows = leftShape[safe: 1] ?? 0
var result: Self = []
for d in 0..<depth {
var new2d: Element = []
for r in 0..<rows {
new2d.append(left[d][r] + right[d][r])
}
result.append(new2d)
}
return result
}
}
public extension Array {
func as3D() -> [[[Element]]] {
let amount = count
let result: [[[Element]]] = [[[Element]]].init(repeating: [[Element]].init(repeating: self,
count: amount),
count: amount)
return result
}
func as2D() -> [[Element]] {
let amount = count
let result: [[Element]] = [[Element]].init(repeating: self, count: amount)
return result
}
subscript(safe safeIndex: Int, default: Element) -> Element {
if safeIndex < 0 {
return `default`
}
return self[safe: safeIndex] ?? `default`
}
subscript(_ multiple: [Int], default: Element) -> Self {
var result: Self = []
result.reserveCapacity(multiple.count)
multiple.forEach { i in
result.append(self[safe: i, `default`])
}
return result
}
subscript(range multiple: Range<Int>, default: Element) -> Self {
var result: Self = []
result.reserveCapacity(multiple.count)
multiple.forEach { i in
result.append(self[safe: i, `default`])
}
return result
}
subscript(range multiple: Range<Int>, dialate: Int, default: Element) -> Self {
var result: Self = []
result.reserveCapacity(multiple.count)
var i: Int = 0
var dialateTotal: Int = 0
let range = [Int](multiple)
while i < multiple.count {
if i > 0 && dialateTotal < dialate {
result.append(self[safe: -1, `default`])
dialateTotal += 1
} else {
result.append(self[safe: range[i], `default`])
i += 1
dialateTotal = 0
}
}
return result
}
subscript(range multiple: Range<Int>, padding: Int, dialate: Int, default: Element) -> Self {
var result: Self = []
//result.reserveCapacity(multiple.count)
var i: Int = 0
var dialateTotal: Int = 0
var paddingTotal: Int = 0
let range = [Int](multiple)
while i < (multiple.count + padding * 4) {
if (i > multiple.count || i == 0) && paddingTotal < padding {
result.append(self[safe: -1, `default`])
paddingTotal += 1
} else if i > 0 && i < multiple.count && dialateTotal < dialate {
result.append(self[safe: -1, `default`])
dialateTotal += 1
} else {
if i < multiple.count {
result.append(self[safe: range[i], `default`])
paddingTotal = 0
dialateTotal = 0
}
i += 1
}
}
return result
}
}
public extension Array where Element == [Float] {
subscript(_ start: (row: Int, column: Int),
end: (row: Int, column: Int),
default: Float) -> Self {
var result: Self = []
let defaultRow = [Float].init(repeating: `default`, count: count)
result.append(contentsOf: self[range: start.row..<end.row, defaultRow])
return result.map { $0[range: start.column..<end.column, `default`] }
}
subscript(flat start: (row: Int, column: Int),
end: (row: Int, column: Int),
default: Float) -> [Float] {
var result: [Float] = []
let defaultRow = [Float].init(repeating: `default`, count: count)
self[range: start.row..<end.row, defaultRow].forEach { row in
let column = row[range: start.column..<end.column, `default`]
result.append(contentsOf: column)
}
return result
}
subscript(_ start: (row: Int, column: Int),
end: (row: Int, column: Int),
dialate: Int,
default: Float) -> Self {
var result: Self = []
let defaultRow = [Float].init(repeating: `default`, count: count)
result.append(contentsOf: self[range: start.row..<end.row, dialate, defaultRow])
return result.map { $0[range: start.column..<end.column, dialate, `default`] }
}
subscript(_ start: (row: Int, column: Int),
end: (row: Int, column: Int),
padding: Int,
dialate: Int,
default: Float) -> Self {
var result: Self = []
let defaultRow = [Float].init(repeating: `default`, count: count)
result.append(contentsOf: self[range: start.row..<end.row, padding, dialate, defaultRow])
return result.map { $0[range: start.column..<end.column, padding, dialate, `default`] }
}
subscript(flat start: (row: Int, column: Int),
end: (row: Int, column: Int),
dialate: Int,
default: Float) -> [Float] {
var result: [Float] = []
let defaultRow = [Float].init(repeating: `default`, count: count)
self[range: start.row..<end.row, dialate, defaultRow].forEach { row in
let column = row[range: start.column..<end.column, dialate, `default`]
result.append(contentsOf: column)
}
return result
}
subscript(flat start: (row: Int, column: Int),
end: (row: Int, column: Int),
padding: Int,
dialate: Int,
default: Float) -> [Float] {
var result: [Float] = []
let defaultRow = [Float].init(repeating: `default`, count: count)
self[range: start.row..<end.row, padding, dialate, defaultRow].forEach { row in
let column = row[range: start.column..<end.column, padding, dialate, `default`]
result.append(contentsOf: column)
}
return result
}
}
public extension Array where Element == [Float] {
var sumOfSquares: Float {
var result: Float = 0
self.forEach { a in
let stride = vDSP_Stride(1)
let n = vDSP_Length(a.count)
var c: Float = .nan
vDSP_svesq(a,
stride,
&c,
n)
result += c
}
return result
}
var mean: Float {
var r: Float = 0
var total = 0
self.forEach { a in
r += a.mean
total += 1
}
return r / Float(total)
}
var sum: Float {
var r: Float = 0
self.forEach { a in
r += a.sum
}
return r
}
static func *(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d] * rhs
result.append(new2d)
}
return result
}
static func *(lhs: Float, rhs: Self) -> Self {
var result: Self = []
for d in 0..<rhs.count {
let new2d: Element = rhs[d] * lhs
result.append(new2d)
}
return result
}
static func /(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d] / rhs
result.append(new2d)
}
return result
}
static func +(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d] + rhs
result.append(new2d)
}
return result
}
static func +(lhs: Float, rhs: Self) -> Self {
var result: Self = []
for d in 0..<rhs.count {
let new2d: Element = rhs[d] + lhs
result.append(new2d)
}
return result
}
static func -(lhs: Self, rhs: Float) -> Self {
let left = lhs
var result: Self = []
for d in 0..<lhs.count {
let new2d: Element = left[d] - rhs
result.append(new2d)
}
return result
}
static func *(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = left.count
var result: Self = []
for d in 0..<depth {
result.append(left[d] * right[d])
}
return result
}
static func /(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = left.count
var result: Self = []
for d in 0..<depth {
result.append(left[d] / right[d])
}
return result
}
static func -(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = left.count
var result: Self = []
for d in 0..<depth {
result.append(left[d] - right[d])
}
return result
}
static func +(lhs: Self, rhs: Self) -> Self {
let left = lhs
let right = rhs
let leftShape = left.shape
let rightShape = right.shape
precondition(leftShape == rightShape)
let depth = left.count
var result: Self = []
for d in 0..<depth {
result.append(left[d] + right[d])
}
return result
}
}
| 23.838571 | 105 | 0.538952 |
4ae7848ae331271050a1522b2d829f0509a9edb5 | 298 | //
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
import UIKit
import KIF
class ___FILEBASENAMEASIDENTIFIER___: KIFTestCase {
func testAreAnyTestsWritten() {
XCTFail("You should write some KIF tests.")
}
}
| 16.555556 | 51 | 0.704698 |
1cd5e75b43c40f225e0d0e20663764983437c1b9 | 2,766 | //
// TransferFundsViewModel.swift
// MVVMBankApp
//
// Created by Edgar Adrián on 30/12/20.
//
import Foundation
class TransferFundsViewModel: ObservableObject {
@Published var accounts = [AccountViewModel]()
@Published var message: String?
var filteredAccounts: [AccountViewModel] {
if self.fromAccount === nil {
return accounts
} else {
return accounts.filter {
guard let fromAccount = self.fromAccount else {
return false
}
return $0.accountId != fromAccount.accountId
}
}
}
var fromAccount: AccountViewModel?
var toAccount: AccountViewModel?
var amount: String = ""
var isAmountValid: Bool {
guard let amount = Double(amount) else {
return false
}
return amount >= 0 ? true : false
}
var fromAccountType: String {
fromAccount != nil ? fromAccount!.accountType : ""
}
var toAccountType: String {
toAccount != nil ? toAccount!.accountType : ""
}
private func isValid() -> Bool {
return isAmountValid
}//isValid
func submitTransfer(completition: @escaping () -> Void) {
if !isValid() {
return
}
guard let fromAccount = fromAccount,
let toAccount = toAccount,
let amount = Double(amount) else {
return
}
let transferFundRequest = TransferFundRequest(accountFromId: fromAccount.accountId.lowercased(), accountToId: toAccount.accountId.lowercased(), amount: amount)
AccountService.shared.transferFunds(transferFundRequest: transferFundRequest) { (result) in
switch result {
case .success(let response):
if response.success {
completition()
} else {
self.message = response.error
}
case .failure(let error):
self.message = error.localizedDescription
}
}
}//submitTransfer
func populateAccounts() {
AccountService.shared.getAllAccounts { (result) in
switch result {
case .success(let accounts):
if let accounts = accounts {
DispatchQueue.main.async {
self.accounts = accounts.map(AccountViewModel.init)
}
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
| 27.117647 | 167 | 0.515546 |
f99aca82206d8c909168d73a61ae26ed6b520570 | 1,230 | //
// InsulinModelProvider.swift
// LoopKit
//
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
public protocol InsulinModelProvider {
func model(for type: InsulinType?) -> InsulinModel
}
public struct PresetInsulinModelProvider: InsulinModelProvider {
var defaultRapidActingModel: InsulinModel?
public init(defaultRapidActingModel: InsulinModel?) {
self.defaultRapidActingModel = defaultRapidActingModel
}
public func model(for type: InsulinType?) -> InsulinModel {
switch type {
case .fiasp:
return ExponentialInsulinModelPreset.fiasp
case .lyumjev:
return ExponentialInsulinModelPreset.lyumjev
case .afrezza:
return ExponentialInsulinModelPreset.afrezza
default:
return defaultRapidActingModel ?? ExponentialInsulinModelPreset.rapidActingAdult
}
}
}
// Provides a fixed model, ignoring insulin type
public struct StaticInsulinModelProvider: InsulinModelProvider {
var model: InsulinModel
public init(_ model: InsulinModel) {
self.model = model
}
public func model(for type: InsulinType?) -> InsulinModel {
return model
}
}
| 26.170213 | 92 | 0.686992 |
ff1852c762d7ebf150e05c72007826a7b4ce74d8 | 11,419 |
/**
* This class provides a simple interface for performing authentication tasks.
*/
public class WMFAuthenticationManager: NSObject {
public enum AuthenticationResult {
case success(_: WMFAccountLoginResult)
case alreadyLoggedIn(_: WMFCurrentlyLoggedInUser)
case failure(_: Error)
}
public typealias AuthenticationResultHandler = (AuthenticationResult) -> Void
public enum AuthenticationError: LocalizedError {
case missingLoginURL
public var errorDescription: String? {
switch self {
default:
return CommonStrings.genericErrorDescription
}
}
public var recoverySuggestion: String? {
switch self {
default:
return CommonStrings.genericErrorRecoverySuggestion
}
}
}
private let session: Session = {
return Session.shared
}()
/**
* The current logged in user. If nil, no user is logged in
*/
@objc dynamic private(set) var loggedInUsername: String? = nil
/**
* Returns YES if a user is logged in, NO otherwise
*/
@objc public var isLoggedIn: Bool {
return (loggedInUsername != nil)
}
@objc public var hasKeychainCredentials: Bool {
guard
let userName = KeychainCredentialsManager.shared.username,
userName.count > 0,
let password = KeychainCredentialsManager.shared.password,
password.count > 0
else {
return false
}
return true
}
fileprivate let loginInfoFetcher = WMFAuthLoginInfoFetcher()
fileprivate let tokenFetcher = WMFAuthTokenFetcher()
fileprivate let accountLogin = WMFAccountLogin()
fileprivate let currentlyLoggedInUserFetcher = WMFCurrentlyLoggedInUserFetcher()
/**
* Get the shared instance of this class
*
* @return The shared Authentication Manager
*/
@objc public static let sharedInstance = WMFAuthenticationManager()
var loginSiteURL: URL? {
var baseURL: URL?
if let host = KeychainCredentialsManager.shared.host {
var components = URLComponents()
components.host = host
components.scheme = "https"
baseURL = components.url
}
if baseURL == nil {
baseURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL()
}
if baseURL == nil {
baseURL = NSURL.wmf_URLWithDefaultSiteAndCurrentLocale()
}
return baseURL
}
public func attemptLogin(completion: @escaping AuthenticationResultHandler) {
self.loginWithSavedCredentials { (loginResult) in
switch loginResult {
case .success(let result):
DDLogDebug("\n\nSuccessfully logged in with saved credentials for user \(result.username).\n\n")
self.session.cloneCentralAuthCookies()
case .alreadyLoggedIn(let result):
DDLogDebug("\n\nUser \(result.name) is already logged in.\n\n")
self.session.cloneCentralAuthCookies()
case .failure(let error):
DDLogDebug("\n\nloginWithSavedCredentials failed with error \(error).\n\n")
}
DispatchQueue.main.async {
completion(loginResult)
}
}
}
/**
* Login with the given username and password
*
* @param username The username to authenticate
* @param password The password for the user
* @param retypePassword The password used for confirming password changes. Optional.
* @param oathToken Two factor password required if user's account has 2FA enabled. Optional.
* @param loginSuccess The handler for success - at this point the user is logged in
* @param failure The handler for any errors
*/
public func login(username: String, password: String, retypePassword: String?, oathToken: String?, captchaID: String?, captchaWord: String?, completion: @escaping AuthenticationResultHandler) {
guard let siteURL = loginSiteURL else {
completion(.failure(AuthenticationError.missingLoginURL))
return
}
self.tokenFetcher.fetchToken(ofType: .login, siteURL: siteURL, success: { (token) in
self.accountLogin.login(username: username, password: password, retypePassword: retypePassword, loginToken: token.token, oathToken: oathToken, captchaID: captchaID, captchaWord: captchaWord, siteURL: siteURL, success: {result in
let normalizedUserName = result.username
self.loggedInUsername = normalizedUserName
KeychainCredentialsManager.shared.username = normalizedUserName
KeychainCredentialsManager.shared.password = password
KeychainCredentialsManager.shared.host = siteURL.host
self.session.cloneCentralAuthCookies()
SessionSingleton.sharedInstance()?.dataStore.clearMemoryCache()
completion(.success(result))
}, failure: { (error) in
completion(.failure(error))
})
}) { (error) in
completion(.failure(error))
}
}
/**
* Logs in a user using saved credentials in the keychain
*
* @param success The handler for success - at this point the user is logged in
* @param completion
*/
public func loginWithSavedCredentials(completion: @escaping AuthenticationResultHandler) {
guard hasKeychainCredentials,
let userName = KeychainCredentialsManager.shared.username,
let password = KeychainCredentialsManager.shared.password
else {
let error = WMFCurrentlyLoggedInUserFetcherError.blankUsernameOrPassword
completion(.failure(error))
return
}
guard let siteURL = loginSiteURL else {
completion(.failure(AuthenticationError.missingLoginURL))
return
}
currentlyLoggedInUserFetcher.fetch(siteURL: siteURL, success: { result in
self.loggedInUsername = result.name
completion(.alreadyLoggedIn(result))
}, failure:{ error in
guard !(error is URLError) else {
self.loggedInUsername = userName
let loginResult = WMFAccountLoginResult(status: WMFAccountLoginResult.Status.offline, username: userName, message: nil)
completion(.success(loginResult))
return
}
self.login(username: userName, password: password, retypePassword: nil, oathToken: nil, captchaID: nil, captchaWord: nil, completion: { (loginResult) in
switch loginResult {
case .success(let result):
completion(.success(result))
case .failure(let error):
guard !(error is URLError) else {
self.loggedInUsername = userName
let loginResult = WMFAccountLoginResult(status: WMFAccountLoginResult.Status.offline, username: userName, message: nil)
completion(.success(loginResult))
return
}
self.loggedInUsername = nil
self.logout(initiatedBy: .app)
completion(.failure(error))
default:
break
}
})
})
}
fileprivate var logoutManager:AFHTTPSessionManager?
fileprivate func resetLocalUserLoginSettings() {
KeychainCredentialsManager.shared.username = nil
KeychainCredentialsManager.shared.password = nil
self.loggedInUsername = nil
session.removeAllCookies()
SessionSingleton.sharedInstance()?.dataStore.clearMemoryCache()
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
// Reset so can show for next logged in user.
UserDefaults.wmf.wmf_setDidShowEnableReadingListSyncPanel(false)
UserDefaults.wmf.wmf_setDidShowSyncEnabledPanel(false)
}
/**
* Logs out any authenticated user and clears out any associated cookies
*/
@objc(logoutInitiatedBy:completion:)
public func logout(initiatedBy logoutInitiator: LogoutInitiator, completion: @escaping () -> Void = {}){
if logoutInitiator == .app || logoutInitiator == .server {
isUserUnawareOfLogout = true
}
let postDidLogOutNotification = {
NotificationCenter.default.post(name: WMFAuthenticationManager.didLogOutNotification, object: nil)
}
logoutManager = AFHTTPSessionManager(baseURL: loginSiteURL)
_ = logoutManager?.wmf_apiPOST(with: ["action": "logout", "format": "json"], success: { (_, response) in
DDLogDebug("Successfully logged out, deleted login tokens and other browser cookies")
// It's best to call "action=logout" API *before* clearing local login settings...
self.resetLocalUserLoginSettings()
completion()
postDidLogOutNotification()
}, failure: { (_, error) in
// ...but if "action=logout" fails we *still* want to clear local login settings, which still effectively logs the user out.
DDLogDebug("Failed to log out, delete login tokens and other browser cookies: \(error)")
self.resetLocalUserLoginSettings()
completion()
postDidLogOutNotification()
})
}
}
// MARK: @objc login
extension WMFAuthenticationManager {
@objc public func attemptLogin(completion: @escaping () -> Void = {}) {
let completion: AuthenticationResultHandler = { result in
completion()
}
attemptLogin(completion: completion)
}
@objc func loginWithSavedCredentials(success: @escaping WMFAccountLoginResultBlock, userAlreadyLoggedInHandler: @escaping WMFCurrentlyLoggedInUserBlock, failure: @escaping WMFErrorHandler) {
let completion: AuthenticationResultHandler = { loginResult in
switch loginResult {
case .success(let result):
success(result)
case .alreadyLoggedIn(let result):
userAlreadyLoggedInHandler(result)
case .failure(let error):
failure(error)
}
}
loginWithSavedCredentials(completion: completion)
}
}
// MARK: @objc logout
extension WMFAuthenticationManager {
@objc public enum LogoutInitiator: Int {
case user
case app
case server
}
@objc public static let didLogOutNotification = Notification.Name("WMFAuthenticationManagerDidLogOut")
@objc public func userDidAcknowledgeUnintentionalLogout() {
isUserUnawareOfLogout = false
}
@objc public var isUserUnawareOfLogout: Bool {
get {
return UserDefaults.wmf.isUserUnawareOfLogout
}
set {
UserDefaults.wmf.isUserUnawareOfLogout = newValue
}
}
}
| 39.24055 | 240 | 0.622997 |
ab5a6aad3c27f48486b053560de9c85ec060aab0 | 1,581 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 ChattoAdditions
public class DemoTextMessageModel: TextMessageModel<MessageModel>, DemoMessageModelProtocol {
public override init(messageModel: MessageModel, text: String) {
super.init(messageModel: messageModel, text: text)
}
public var status: MessageStatus {
get {
return self._messageModel.status
}
set {
self._messageModel.status = newValue
}
}
}
| 37.642857 | 93 | 0.752056 |
564b25e488be99b60b285c7cb0664df1ed876bdf | 14,317 | //
// FooBookView.swift
// FooBook
//
// Created by Shankar B S on 01/03/20.
// Copyright © 2020 Slicode. All rights reserved.
//
import Foundation
import UIKit
//In this calss we are creating the FeedView
//in code insted of xib file
enum ButtonIcon: String {
case ellipsis = "ellipsis"
case camera = "camera"
case thumb = "hand.thumbsup.fill"
case info = "info.circle"
case none = ""
}
enum Anchor {
case top(value: CGFloat)
case left(value: CGFloat)
case bottom(value: CGFloat)
case right(value: CGFloat)
}
class FooBookView: UIView {
var baseStackView: UIStackView! //Base stack view to hold the all the sections
let leftStandardMargin: CGFloat = 20.0 // some standard left margin
//UI components we need to update
//Profile info
var profileImageView: UIImageView?
var nameLabel: UILabel?
var dateLabel: UILabel?
//Text Part
var subTitleLabel: UILabel?
//Image view part
var feedImageView: UIImageView?
//Comments view part
var likeLabel: UILabel?
var commentsLabel: UILabel?
var sharesLabel: UILabel?
override init(frame: CGRect) {
super.init(frame: frame)
//1
setupFeedUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//2
func setupFeedUI() {
//create base stack vertical view
baseStackView = createStackView(of: .vertical, with: .fill, spacing: 0.0)
self.addSubview(baseStackView)
baseStackView.translatesAutoresizingMaskIntoConstraints = false
pin(subView: baseStackView, to: self, topMargin: 0.0, leftMargin: 0.0, bottomMargin: 0.0, rightMargin: 0.0)
//suggested for you
setupSuggestedForYou()
//seperator
createSeperator()
//Profile info view
createProfileInfoView()
//Text section
createTextSection()
//Image view
createFeedImageViewSection()
//Comments
createCommentViewSection()
//Seperator 2
createSeperatorWithGap()
//Actions
createActionsViewSections()
}
//MARK: Data updaters
func updateWith(feed: FeedModel) {
profileImageView?.image = UIImage(named: feed.profileImageName)
dateLabel?.text = feed.dateString
nameLabel?.text = feed.name
subTitleLabel?.text = feed.subTitle
feedImageView?.image = UIImage(named: feed.feedImageName)
likeLabel?.text = feed.likes
commentsLabel?.text = feed.comments
sharesLabel?.text = feed.shares
}
//Suggested For you section
func setupSuggestedForYou() {
//creating views
let view = createEmptyView()
let horizontalStackView = createStackView(of: .horizontal, with: .fill, spacing: 0.0)
let textLabel = createLabel(with: .black, fontSize: 17.0)
let eclipseButton = createButton(with: .clear, fontSize: 17.0, isBold: false, withIcon: .ellipsis)
textLabel.text = "SUGGESTED FOR YOU"
//adding to stack view
horizontalStackView.addArrangedSubview(textLabel)
horizontalStackView.addArrangedSubview(eclipseButton)
view.addSubview(horizontalStackView)
//adding constraints
set(view: eclipseButton, withFixedHeight: 50)
set(view: eclipseButton, withFixedWidth: 50)
pin(subView: horizontalStackView, to: view, topMargin: 0.0, leftMargin: leftStandardMargin, bottomMargin: 0.0, rightMargin: 0.0)
//Finally adding to base stack view.
baseStackView.addArrangedSubview(view)
}
//MARK: Seperator
func createSeperator() {
//create a empty view
let seperatorView = createEmptyView()
seperatorView.backgroundColor = UIColor.gray
baseStackView.addArrangedSubview(seperatorView)
set(view: seperatorView, withFixedHeight: 1.0)
pin(subView: seperatorView, to: baseStackView, withSide: [.left(value: 0.0), .right(value: 0.0)])
}
//MARK: Profile Info view
func createProfileInfoView() {
//this view is added to base stack view
let profileHolderView = createEmptyView()
//this stack view is holder for image and labels stack view
let horizontalStackView = createStackView(of: .horizontal, with: .fill, spacing: 8.0)
//1
//create profile image part
self.profileImageView = UIImageView()
self.profileImageView?.translatesAutoresizingMaskIntoConstraints = false
if let imageView = self.profileImageView {
set(view: imageView, withFixedHeight: 68)
set(view: imageView, withFixedWidth: 60)
horizontalStackView.addArrangedSubview(imageView)
}
//2
//create labels part
let labelsHolderView = createEmptyView()
let verticalStackView = createStackView(of: .vertical, with: .fillEqually, spacing: 0.0)
self.nameLabel = createLabel(with: .black, fontSize: 20.0, isBold: true, allignment: .left)
self.dateLabel = createLabel(with: .black, fontSize: 18, isBold: false, allignment: .left)
self.nameLabel?.text = "name to set"
self.dateLabel?.text = "date to set"
if let aNameLabel = self.nameLabel, let aDateLabel = self.dateLabel {
verticalStackView.addArrangedSubview(aNameLabel)
verticalStackView.addArrangedSubview(aDateLabel)
}
labelsHolderView.addSubview(verticalStackView)
pin(subView: verticalStackView, to: labelsHolderView, topMargin: 10, leftMargin: 10, bottomMargin: -10, rightMargin: 0)
//3
//finally add the labels holder view to horizontal stack view
horizontalStackView.addArrangedSubview(labelsHolderView)
profileHolderView.addSubview(horizontalStackView)
pin(subView: horizontalStackView, to: profileHolderView, topMargin: 10, leftMargin: leftStandardMargin, bottomMargin: 0, rightMargin: 0)
baseStackView.addArrangedSubview(profileHolderView)
}
//MARK: Text section of UI
func createTextSection() {
//1
let textHolderView = createEmptyView()
self.subTitleLabel = createLabel(with: .black, fontSize: 17, isBold: false, allignment: .natural)
self.subTitleLabel?.text = "sub title text goes here"
self.subTitleLabel?.numberOfLines = 0
if let label = self.subTitleLabel {
textHolderView.addSubview(label)
pin(subView: label, to: textHolderView, topMargin: 5, leftMargin: leftStandardMargin, bottomMargin: 0, rightMargin: 0)
}
self.baseStackView.addArrangedSubview(textHolderView)
}
//MARK: Image section part
func createFeedImageViewSection() {
let imageHolderView = createEmptyView()
self.feedImageView = UIImageView()
self.feedImageView?.translatesAutoresizingMaskIntoConstraints = false
if let feedImgView = self.feedImageView {
set(view: feedImgView, withFixedHeight: 300)
imageHolderView.addSubview(feedImgView)
pin(subView: feedImgView, to: imageHolderView, topMargin: 0, leftMargin: leftStandardMargin, bottomMargin: 0, rightMargin: -leftStandardMargin)
}
self.baseStackView.addArrangedSubview(imageHolderView)
}
//MARK: Comments section
func createCommentViewSection() {
let commentsHolderView = createEmptyView()
set(view: commentsHolderView, withFixedHeight: 55)
let horizontalStackView = createStackView(of: .horizontal, with: .fillEqually, spacing: 0)
self.likeLabel = createLabel(with: .black, fontSize: 17.0, isBold: false, allignment: .center)
self.commentsLabel = createLabel(with: .orange, fontSize: 17.0, isBold: false, allignment: .center)
self.sharesLabel = createLabel(with: .gray, fontSize: 17.0, isBold: false, allignment: .center)
self.likeLabel?.text = "Likes count"
self.commentsLabel?.text = "Comments count"
self.sharesLabel?.text = "Shares count"
if let likeLbl = self.likeLabel, let commentsLbl = self.commentsLabel, let sharesLbl = self.sharesLabel {
horizontalStackView.addArrangedSubview(likeLbl)
horizontalStackView.addArrangedSubview(commentsLbl)
horizontalStackView.addArrangedSubview(sharesLbl)
commentsHolderView.addSubview(horizontalStackView)
pin(subView: horizontalStackView, to: commentsHolderView, topMargin: 0, leftMargin: 0, bottomMargin: 0, rightMargin: 0)
}
baseStackView.addArrangedSubview(commentsHolderView)
}
//MARK: Seperator Part two
func createSeperatorWithGap() {
let emptyView = createEmptyView()
emptyView.backgroundColor = .lightGray
baseStackView.addArrangedSubview(emptyView)
set(view: emptyView, withFixedHeight: 1.0)
pin(subView: emptyView, to: baseStackView, withSide: [.left(value: 20.0), .right(value: -20)])
}
//MARK: Actions part
func createActionsViewSections() {
let actionsHolderView = createEmptyView()
set(view: actionsHolderView, withFixedHeight: 55)
let horizontalStackView = createStackView(of: .horizontal, with: .fillEqually, spacing: 0)
let captureButton = createButton(with: .black, fontSize: 17, isBold: true, withIcon: .camera)
let likeButton = createButton(with: .black, fontSize: 17, isBold: true, withIcon: .thumb)
let infoButton = createButton(with: .black, fontSize: 17, isBold: true, withIcon: .info)
captureButton.setTitle("Capture", for: .normal)
likeButton.setTitle("Like Me", for: .normal)
infoButton.setTitle("Info", for: .normal)
let titleInsects = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
captureButton.titleEdgeInsets = titleInsects
likeButton.titleEdgeInsets = titleInsects
infoButton.titleEdgeInsets = titleInsects
horizontalStackView.addArrangedSubview(captureButton)
horizontalStackView.addArrangedSubview(likeButton)
horizontalStackView.addArrangedSubview(infoButton)
actionsHolderView.addSubview(horizontalStackView)
pin(subView: horizontalStackView, to: actionsHolderView, topMargin: 0, leftMargin: 0, bottomMargin: 0, rightMargin: 0)
baseStackView.addArrangedSubview(actionsHolderView)
}
//MARK: Stack view Helpers
func createStackView(of type:NSLayoutConstraint.Axis, with distributon: UIStackView.Distribution, spacing: CGFloat) -> UIStackView {
let stackView = UIStackView()
stackView.distribution = distributon
stackView.axis = type
stackView.spacing = spacing
stackView.alignment = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}
//MARK: Constraints helpers
func pin(subView: UIView, to superView: UIView, topMargin: CGFloat = 0.0, leftMargin: CGFloat = 0.0, bottomMargin: CGFloat = 0.0, rightMargin: CGFloat = 0.0) {
subView.topAnchor.constraint(equalTo: superView.topAnchor , constant: topMargin).isActive = true
subView.leftAnchor.constraint(equalTo: superView.leftAnchor, constant: leftMargin).isActive = true
subView.bottomAnchor.constraint(equalTo: superView.bottomAnchor, constant: bottomMargin).isActive = true
subView.rightAnchor.constraint(equalTo: superView.rightAnchor, constant: rightMargin).isActive = true
}
//MARK: This will add given constraints with values
func pin(subView: UIView, to superView: UIView, withSide anchors:[Anchor]) {
for anchor in anchors {
switch anchor {
case .top(let value):
subView.topAnchor.constraint(equalTo: superView.topAnchor , constant: value).isActive = true
case .left(let value):
subView.leftAnchor.constraint(equalTo: superView.leftAnchor, constant: value).isActive = true
case .bottom(let value):
subView.bottomAnchor.constraint(equalTo: superView.bottomAnchor, constant: value).isActive = true
case .right(let value):
subView.rightAnchor.constraint(equalTo: superView.rightAnchor, constant: value).isActive = true
}
}
}
func set(view: UIView, withFixedWidth width: CGFloat) {
view.widthAnchor.constraint(equalToConstant: width).isActive = true
}
func set(view: UIView, withFixedHeight height: CGFloat) {
view.heightAnchor.constraint(equalToConstant: height).isActive = true
}
//MARK: UI helpers
func createLabel(with textColor: UIColor, fontSize: CGFloat, isBold: Bool = false, allignment: NSTextAlignment = .left) -> UILabel {
let label = UILabel()
let font = isBold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
label.textColor = textColor
label.font = font
label.textAlignment = allignment
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
func createButton(with textColor: UIColor, fontSize: CGFloat, isBold: Bool = false, withIcon icon: ButtonIcon = .none) -> UIButton {
let button = UIButton()
button.setTitleColor(textColor, for: .normal)
button.titleLabel?.font = isBold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
button.titleLabel?.textColor = textColor
button.setImage(UIImage(systemName: icon.rawValue), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}
func createEmptyView() -> UIView {
let emptyView = UIView()
emptyView.translatesAutoresizingMaskIntoConstraints = false
return emptyView
}
}
| 39.549724 | 163 | 0.657121 |
9c2d53f42e376606c5df2c62dc32bcf4145e8aff | 1,256 | // Created by Eric Marchand on 07/06/2017.
// Copyright © 2017 Eric Marchand. All rights reserved.
//
import Foundation
public struct MomEntity {
public var name: String
public var representedClassName: String
public var syncable: Bool = true
public var codeGenerationType: String
public var userInfo = MomUserInfo()
public var uniquenessConstraints: MomUniquenessConstraints?
//TODO public var elementID: String?
//TODO public var versionHashModifier: String?
public init(name: String, representedClassName: String? = nil, codeGenerationType: String = "class") {
self.name = name
self.representedClassName = representedClassName ?? name
self.codeGenerationType = codeGenerationType
}
public var attributes: [MomAttribute] = []
public var relationship: [MomRelationship] = []
public var fetchProperties: [MomFetchedProperty] = []
public var fetchIndexes: [MomFetchIndex] = []
// TODO MomCompoundIndex (deprecated)
}
extension MomEntity {
var relationshipByName: [String: MomRelationship] {
return relationship.dictionaryBy { $0.name }
}
var attributesByName: [String: MomAttribute] {
return attributes.dictionaryBy { $0.name }
}
}
| 31.4 | 106 | 0.705414 |
098af7aa569f977224783f29ed76063c1b0ddc0e | 1,441 | //
// GroupsSplitViewController.swift
// MEGameTracker
//
// Created by Emily Ivie on 2/22/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
class GroupSplitViewController: UIViewController, MESplitViewController, DeepLinkable {
@IBOutlet weak var mainPlaceholder: IBIncludedSubThing?
@IBOutlet weak var detailBorderLeftView: UIView?
@IBOutlet weak var detailPlaceholder: IBIncludedSubThing?
var ferriedSegue: FerriedPrepareForSegueClosure?
var dontSplitViewInPage = false
@IBAction func closeDetailStoryboard(_ sender: AnyObject?) {
closeDetailStoryboard()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
ferriedSegue?(segue.destination)
}
// MARK: DeepLinkable protocol
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let person = deepLinkedPerson {
showPerson(person)
}
isPageLoaded = true
}
var deepLinkedPerson: Person?
var isPageLoaded = false
func deepLink(_ object: DeepLinkType?, type: String? = nil) {
// first, verify is acceptable object:
if let person = object as? Person {
// second, make sure page is done loading:
if isPageLoaded {
showPerson(person)
} else {
deepLinkedPerson = person // wait for viewWillAppear()
}
}
}
func showPerson(_ person: Person) {
deepLinkedPerson = nil
(mainPlaceholder?.includedController as? PersonsGroupsController)?.deepLink(person)
}
}
| 25.280702 | 87 | 0.74601 |
e8be0aa561c5d6888f9e52aa3b4d1a8250aada70 | 8,938 | //
// MainViewController.swift
// Example
//
// Created by Pierluigi D'Andrea on 23/11/17.
// Copyright © 2017 Pierluigi D'Andrea. All rights reserved.
//
import SatispayInStore
import UIKit
class MainViewController: UITableViewController {
private var transactions: [[Transaction]] = [[], []] {
didSet {
var sectionsToReload = IndexSet()
for (section, newTransactions) in transactions.enumerated() where oldValue[section] != newTransactions {
sectionsToReload.insert(section)
}
guard !sectionsToReload.isEmpty else {
return
}
tableView.beginUpdates()
tableView.reloadSections(sectionsToReload, with: .automatic)
tableView.endUpdates()
}
}
private lazy var transactionsController = TransactionsController()
private lazy var currencyFormatter: NumberFormatter = {
let locale = Locale(identifier: "it_IT")
let formatter = NumberFormatter()
formatter.generatesDecimalNumbers = true
formatter.numberStyle = .currency
if let currencySymbol = (locale as NSLocale).object(forKey: NSLocale.Key.currencySymbol) as? String {
formatter.currencySymbol = currencySymbol
}
if let currencyCode = (locale as NSLocale).object(forKey: NSLocale.Key.currencyCode) as? String {
formatter.currencyCode = currencyCode
}
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.refreshControl = {
let control = UIRefreshControl()
control.addTarget(self, action: #selector(refreshTransactions(_:)), for: .valueChanged)
return control
}()
refreshTransactions(nil)
}
}
// MARK: - ProfileRequiring
extension MainViewController: ProfileRequiring {
func configure(with profile: Profile) {
title = profile.shop.name
}
}
// MARK: - Updating
extension MainViewController {
private func updatePendingTransactions(from response: PaginatedResponse<Transaction>) {
transactions[0] = response.list.filter { $0.state == .pending }
}
private func updateApprovedTransactions(from response: PaginatedResponse<Transaction>) {
transactions[1] = response.list.filter { $0.state == .approved }
}
}
// MARK: - UITableViewDataSource
extension MainViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return transactions.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "PendingTransactionCell", for: indexPath)
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "TransactionCell", for: indexPath)
}
let transaction = transactions[indexPath.section][indexPath.row]
cell.textLabel?.text = {
let payer = transaction.consumerName
let type = transaction.type?.rawValue
return "\(payer ?? "Unknown") (\(type ?? "unknown type"))"
}()
cell.detailTextLabel?.text = {
let amount = NSDecimalNumber(value: transaction.amount).dividing(by: NSDecimalNumber(value: 100))
return currencyFormatter.string(from: amount)
}()
return cell
}
}
// MARK: - UITableViewDelegate
extension MainViewController {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Pending"
case 1:
return "Approved"
default:
return nil
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
switch indexPath.section {
case 0:
return rowActionsForPendingTransaction()
default:
return rowActionsForApprovedTransaction(at: indexPath.row)
}
}
private func rowActionsForPendingTransaction() -> [UITableViewRowAction] {
let confirmAction = UITableViewRowAction(style: .normal, title: "Confirm") { [weak self] (_, indexPath) in
self?.updateStateOfTransaction(at: indexPath, to: .approved)
}
let cancelAction = UITableViewRowAction(style: .destructive, title: "Cancel") { [weak self] (_, indexPath) in
self?.updateStateOfTransaction(at: indexPath, to: .cancelled)
}
return [confirmAction, cancelAction]
}
private func rowActionsForApprovedTransaction(at index: Int) -> [UITableViewRowAction] {
guard transactions[1][index].type == .c2b else {
return []
}
let refundAction = UITableViewRowAction(style: .normal, title: "Refund") { [weak self] (_, indexPath) in
self?.refundTransaction(at: indexPath)
}
return [refundAction]
}
}
// MARK: - Transaction update/refund
extension MainViewController {
private func updateStateOfTransaction(at indexPath: IndexPath, to newState: TransactionState) {
guard indexPath.section == 0, transactions[0].count > indexPath.row else {
return
}
let transaction = transactions[indexPath.section][indexPath.row]
_ = TransactionsController().updateState(of: transaction.id, with: newState, completionHandler: { [weak self] (_, error) in
guard error == nil else {
self?.failUpdate(of: transaction, to: newState)
return
}
self?.refreshTransactions(nil)
})
}
private func failUpdate(of transaction: Transaction, to newState: TransactionState) {
let errorController = UIAlertController(title: "Error",
message: "Couldn't update transaction \(transaction.id) state to \(newState.rawValue)",
preferredStyle: .alert)
errorController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(errorController, animated: true, completion: nil)
}
private func refundTransaction(at indexPath: IndexPath) {
guard indexPath.section == 1, transactions[1].count > indexPath.row else {
return
}
let transaction = transactions[indexPath.section][indexPath.row]
_ = TransactionsController().refund(transactionId: transaction.id) { [weak self] (_, error) in
guard error == nil else {
self?.failRefund(of: transaction)
return
}
self?.refreshTransactions(nil)
}
}
private func failRefund(of transaction: Transaction) {
let errorController = UIAlertController(title: "Error",
message: "Couldn't refund transaction \(transaction.id)",
preferredStyle: .alert)
errorController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(errorController, animated: true, completion: nil)
}
}
// MARK: - Refreshing
extension MainViewController {
@objc func refreshTransactions(_ refreshControl: UIRefreshControl?) {
let group = DispatchGroup()
let analytics = TransactionsListRequest.Analytics(softwareHouse: "Satispay",
softwareName: "SatispayInStore example app",
softwareVersion: "1.0",
deviceInfo: UIDevice.current.modelName)
group.enter()
_ = transactionsController.transactions(filter: "proposed", analytics: analytics) { [weak self] (response, _) in
if let response = response {
self?.updatePendingTransactions(from: response)
}
group.leave()
}
group.enter()
_ = transactionsController.transactions(analytics: analytics) { [weak self] (response, _) in
if let response = response {
self?.updateApprovedTransactions(from: response)
}
group.leave()
}
group.notify(queue: .main) {
refreshControl?.endRefreshing()
}
}
}
| 27.084848 | 135 | 0.612777 |
7675dd1a4dccbbd2c459e9ffc1e7aa8576b7102d | 1,196 | //
// PageViewControllerDemoUITests.swift
// PageViewControllerDemoUITests
//
// Created by Quan Li on 2019/8/16.
// Copyright © 2019 Quan Li All rights reserved.
//
import XCTest
class PageViewControllerDemoUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.171429 | 182 | 0.699833 |
69eff465941386747465fa09af83182ba7eb6fae | 898 | //
// RegionAnnotation.swift
// Orchextra
//
// Created by Carlos Vicente on 25/8/17.
// Copyright © 2017 Gigigo Mobile Services S.L. All rights reserved.
//
import Foundation
import MapKit
class RegionAnnotation: NSObject, MKAnnotation {
// MARK: - Attributes
var title: String?
let coordinate: CLLocationCoordinate2D
// MARK: - Initializers
init(title: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate
}
func annotationView() -> MKAnnotationView {
let annotationView = MKAnnotationView(
annotation: self,
reuseIdentifier: "RegionAnnotation"
)
annotationView.isEnabled = true
annotationView.canShowCallout = true
annotationView.image = #imageLiteral(resourceName: "geofence-blue")
return annotationView
}
}
| 25.657143 | 75 | 0.657016 |
e8da38ecc419719d8cb26a60e0718f1ad100852f | 2,815 | import ProjectDescription
let nameAttribute: Template.Attribute = .required("name")
let platformAttribute: Template.Attribute = .optional("platform", default: "iOS")
let projectPath = "."
let appPath = "Targets/\(nameAttribute)"
let kitFrameworkPath = "Targets/\(nameAttribute)Kit"
let uiFrameworkPath = "Targets/\(nameAttribute)UI"
let taskPath = "Plugins/\(nameAttribute)"
func templatePath(_ path: String) -> Path {
"../\(path)"
}
let template = Template(
description: "Default template",
attributes: [
nameAttribute,
platformAttribute,
],
items: [
.file(
path: "Tuist/ProjectDescriptionHelpers/Project+Templates.swift",
templatePath: templatePath("Project+Templates.stencil")
),
.file(
path: projectPath + "/Project.swift",
templatePath: templatePath("AppProject.stencil")
),
.file(
path: appPath + "/Sources/AppDelegate.swift",
templatePath: "AppDelegate.stencil"
),
.file(
path: appPath + "/Resources/LaunchScreen.storyboard",
templatePath: templatePath("LaunchScreen+\(platformAttribute).stencil")
),
.file(
path: appPath + "/Tests/AppTests.swift",
templatePath: templatePath("AppTests.stencil")
),
.file(
path: kitFrameworkPath + "/Sources/\(nameAttribute)Kit.swift",
templatePath: templatePath("/KitSource.stencil")
),
.file(
path: kitFrameworkPath + "/Tests/\(nameAttribute)KitTests.swift",
templatePath: templatePath("/KitTests.stencil")
),
.file(
path: uiFrameworkPath + "/Sources/\(nameAttribute)UI.swift",
templatePath: templatePath("/UISource.stencil")
),
.file(
path: uiFrameworkPath + "/Tests/\(nameAttribute)UITests.swift",
templatePath: templatePath("/UITests.stencil")
),
.file(
path: taskPath + "/Sources/tuist-my-cli/main.swift",
templatePath: templatePath("/main.stencil")
),
.file(
path: taskPath + "/ProjectDescriptionHelpers/LocalHelper.swift",
templatePath: templatePath("/LocalHelper.stencil")
),
.file(
path: taskPath + "/Package.swift",
templatePath: templatePath("/Package.stencil")
),
.file(
path: taskPath + "/Plugin.swift",
templatePath: templatePath("/Plugin.stencil")
),
.file(
path: ".gitignore",
templatePath: templatePath("Gitignore.stencil")
),
.file(
path: "Tuist/Config.swift",
templatePath: templatePath("Config.stencil")
),
]
)
| 33.511905 | 83 | 0.57833 |
9b3a68d134bfab764a0eba1150f6118eb7a968fa | 1,018 | //
// PhotoDetailsViewController.swift
// Tumblr
//
// Created by Kristine Laranjo on 2/7/18.
// Copyright © 2018 Kristine Laranjo. All rights reserved.
//
import UIKit
class PhotoDetailsViewController: UIViewController {
@IBOutlet weak var detailImageView: UIImageView!
var detailImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
detailImageView.image = detailImage
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 25.45 | 106 | 0.681729 |
0a8abfca25d3d4a0f70f144594731b612c4c9cdd | 1,934 | import Foundation
import Toml
struct CodeOptions {
let codePaths: [String]
let localizablePaths: [String]
let defaultToKeys: Bool
let additive: Bool
let customFunction: String?
let customLocalizableName: String?
let unstripped: Bool
let plistArguments: Bool
}
extension CodeOptions: TomlCodable {
static func make(toml: Toml) throws -> CodeOptions {
let update: String = "update"
let code: String = "code"
return CodeOptions(
codePaths: toml.filePaths(update, code, singularKey: "codePath", pluralKey: "codePaths"),
localizablePaths: toml.filePaths(update, code, singularKey: "localizablePath", pluralKey: "localizablePaths"),
defaultToKeys: toml.bool(update, code, "defaultToKeys") ?? false,
additive: toml.bool(update, code, "additive") ?? true,
customFunction: toml.string(update, code, "customFunction"),
customLocalizableName: toml.string(update, code, "customLocalizableName"),
unstripped: toml.bool(update, code, "unstripped") ?? false,
plistArguments: toml.bool(update, code, "plistArguments") ?? true
)
}
func tomlContents() -> String {
var lines: [String] = ["[update.code]"]
lines.append("codePaths = \(codePaths)")
lines.append("localizablePaths = \(localizablePaths)")
lines.append("defaultToKeys = \(defaultToKeys)")
lines.append("additive = \(additive)")
if let customFunction = customFunction {
lines.append("customFunction = \"\(customFunction)\"")
}
if let customLocalizableName = customLocalizableName {
lines.append("customLocalizableName = \"\(customLocalizableName)\"")
}
lines.append("unstripped = \(unstripped)")
lines.append("plistArguments = \(plistArguments)")
return lines.joined(separator: "\n")
}
}
| 35.814815 | 122 | 0.639607 |
146d2c044f7b5a48849509b1c289415353fd345a | 1,116 | /*
TestCase.swift
This source file is part of the SDGCornerstone open source project.
https://sdggiesbrecht.github.io/SDGCornerstone
Copyright ©2018–2021 Jeremy David Giesbrecht and the SDGCornerstone project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
import XCTest
import SDGLogic
import SDGPersistence
import SDGTesting
/// A test case which simplifies testing for targets which link against the `SDGCornerstone` package.
open class TestCase: XCTestCase {
private static var initialized = false
open override func setUp() {
if ¬TestCase.initialized {
TestCase.initialized = true
#if !PLATFORM_LACKS_FOUNDATION_PROCESS_INFO
ProcessInfo.applicationIdentifier =
"ca.solideogloria.SDGCornerstone.SharedTestingDomain"
#endif
}
testAssertionMethod = XCTAssert
#if !PLATFORM_LACKS_FOUNDATION_THREAD
// The default of .userInteractive is absurd.
Thread.current.qualityOfService = .utility
#endif
super.setUp()
}
}
| 25.363636 | 101 | 0.747312 |
67407aca2b6fea2360f1e6d1d483da4dcaa8bfa5 | 12,187 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension String: StringProtocol {}
extension String: RangeReplaceableCollection {
/// Creates a string representing the given character repeated the specified
/// number of times.
///
/// For example, use this initializer to create a string with ten `"0"`
/// characters in a row.
///
/// let zeroes = String(repeating: "0" as Character, count: 10)
/// print(zeroes)
/// // Prints "0000000000"
///
/// - Parameters:
/// - repeatedValue: The character to repeat.
/// - count: The number of times to repeat `repeatedValue` in the
/// resulting string.
public init(repeating repeatedValue: Character, count: Int) {
self.init(repeating: repeatedValue._str, count: count)
}
// This initializer disambiguates between the following intitializers, now
// that String conforms to Collection:
// - init<T>(_ value: T) where T : LosslessStringConvertible
// - init<S>(_ characters: S) where S : Sequence, S.Element == Character
/// Creates a new string containing the characters in the given sequence.
///
/// You can use this initializer to create a new string from the result of
/// one or more collection operations on a string's characters. For example:
///
/// let str = "The rain in Spain stays mainly in the plain."
///
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// let disemvoweled = String(str.lazy.filter { !vowels.contains($0) })
///
/// print(disemvoweled)
/// // Prints "Th rn n Spn stys mnly n th pln."
///
/// - Parameter other: A string instance or another sequence of
/// characters.
@_specialize(where S == String)
@_specialize(where S == Substring)
public init<S : Sequence & LosslessStringConvertible>(_ other: S)
where S.Element == Character {
if let str = other as? String {
self = str
return
}
self = other.description
}
/// Creates a new string containing the characters in the given sequence.
///
/// You can use this initializer to create a new string from the result of
/// one or more collection operations on a string's characters. For example:
///
/// let str = "The rain in Spain stays mainly in the plain."
///
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// let disemvoweled = String(str.lazy.filter { !vowels.contains($0) })
///
/// print(disemvoweled)
/// // Prints "Th rn n Spn stys mnly n th pln."
///
/// - Parameter characters: A string instance or another sequence of
/// characters.
@_specialize(where S == String)
@_specialize(where S == Substring)
@_specialize(where S == Array<Character>)
public init<S : Sequence>(_ characters: S)
where S.Iterator.Element == Character {
if let str = characters as? String {
self = str
return
}
if let subStr = characters as? Substring {
self.init(subStr)
return
}
self = ""
self.append(contentsOf: characters)
}
/// Reserves enough space in the string's underlying storage to store the
/// specified number of ASCII characters.
///
/// Because each character in a string can require more than a single ASCII
/// character's worth of storage, additional allocation may be necessary
/// when adding characters to a string after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*)
public mutating func reserveCapacity(_ n: Int) {
self._guts.reserveCapacity(n)
}
/// Appends the given string to this string.
///
/// The following example builds a customized greeting by using the
/// `append(_:)` method:
///
/// var greeting = "Hello, "
/// if let name = getUserName() {
/// greeting.append(name)
/// } else {
/// greeting.append("friend")
/// }
/// print(greeting)
/// // Prints "Hello, friend"
///
/// - Parameter other: Another string.
@_semantics("string.append")
public mutating func append(_ other: String) {
if self.isEmpty && !_guts.hasNativeStorage {
self = other
return
}
self._guts.append(other._guts)
}
/// Appends the given character to the string.
///
/// The following example adds an emoji globe to the end of a string.
///
/// var globe = "Globe "
/// globe.append("🌍")
/// print(globe)
/// // Prints "Globe 🌍"
///
/// - Parameter c: The character to append to the string.
public mutating func append(_ c: Character) {
self.append(c._str)
}
public mutating func append(contentsOf newElements: String) {
self.append(newElements)
}
public mutating func append(contentsOf newElements: Substring) {
self._guts.append(newElements._gutsSlice)
}
/// Appends the characters in the given sequence to the string.
///
/// - Parameter newElements: A sequence of characters.
@_specialize(where S == String)
@_specialize(where S == Substring)
@_specialize(where S == Array<Character>)
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Character {
if let str = newElements as? String {
self.append(str)
return
}
if let substr = newElements as? Substring {
self.append(contentsOf: substr)
return
}
for c in newElements {
self.append(c._str)
}
}
/// Replaces the text within the specified bounds with the given characters.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - bounds: The range of text to replace. The bounds of the range must be
/// valid indices of the string.
/// - newElements: The new characters to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the string and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes text at the end of the string, the complexity is O(*n*), where
/// *n* is equal to `bounds.count`.
@_specialize(where C == String)
@_specialize(where C == Substring)
@_specialize(where C == Array<Character>)
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Iterator.Element == Character {
_guts.replaceSubrange(bounds, with: newElements)
}
/// Inserts a new character at the specified position.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - newElement: The new character to insert into the string.
/// - i: A valid index of the string. If `i` is equal to the string's end
/// index, this methods appends `newElement` to the string.
///
/// - Complexity: O(*n*), where *n* is the length of the string.
public mutating func insert(_ newElement: Character, at i: Index) {
self.replaceSubrange(i..<i, with: newElement._str)
}
/// Inserts a collection of characters at the specified position.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - newElements: A collection of `Character` elements to insert into the
/// string.
/// - i: A valid index of the string. If `i` is equal to the string's end
/// index, this methods appends the contents of `newElements` to the
/// string.
///
/// - Complexity: O(*n*), where *n* is the combined length of the string and
/// `newElements`.
@_specialize(where S == String)
@_specialize(where S == Substring)
@_specialize(where S == Array<Character>)
public mutating func insert<S : Collection>(
contentsOf newElements: S, at i: Index
) where S.Element == Character {
self.replaceSubrange(i..<i, with: newElements)
}
/// Removes and returns the character at the specified position.
///
/// All the elements following `i` are moved to close the gap. This example
/// removes the hyphen from the middle of a string.
///
/// var nonempty = "non-empty"
/// if let i = nonempty.firstIndex(of: "-") {
/// nonempty.remove(at: i)
/// }
/// print(nonempty)
/// // Prints "nonempty"
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameter i: The position of the character to remove. `i` must be a
/// valid index of the string that is not equal to the string's end index.
/// - Returns: The character that was removed.
@discardableResult
public mutating func remove(at i: Index) -> Character {
let result = self[i]
_guts.remove(from: i, to: self.index(after: i))
return result
}
/// Removes the characters in the given range.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameter bounds: The range of the elements to remove. The upper and
/// lower bounds of `bounds` must be valid indices of the string and not
/// equal to the string's end index.
/// - Parameter bounds: The range of the elements to remove. The upper and
/// lower bounds of `bounds` must be valid indices of the string.
public mutating func removeSubrange(_ bounds: Range<Index>) {
_guts.remove(from: bounds.lowerBound, to: bounds.upperBound)
}
/// Replaces this string with the empty string.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameter keepCapacity: Pass `true` to prevent the release of the
/// string's allocated storage. Retaining the storage can be a useful
/// optimization when you're planning to grow the string again. The
/// default value is `false`.
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
guard keepCapacity else {
self = ""
return
}
_guts.clear()
}
}
extension String {
@inlinable @inline(__always)
internal func _boundsCheck(_ index: Index) {
_precondition(index._encodedOffset >= 0 && index._encodedOffset < _guts.count,
"String index is out of bounds")
}
@inlinable @inline(__always)
internal func _boundsCheck(_ range: Range<Index>) {
_precondition(
range.lowerBound._encodedOffset >= 0 &&
range.upperBound._encodedOffset <= _guts.count,
"String index range is out of bounds")
}
@inlinable @inline(__always)
internal func _boundsCheck(_ range: ClosedRange<Index>) {
_precondition(
range.lowerBound._encodedOffset >= 0 &&
range.upperBound._encodedOffset < _guts.count,
"String index range is out of bounds")
}
}
extension String {
// This is needed because of the issue described in SR-4660 which causes
// source compatibility issues when String becomes a collection
@_transparent
public func max<T : Comparable>(_ x: T, _ y: T) -> T {
return Swift.max(x,y)
}
// This is needed because of the issue described in SR-4660 which causes
// source compatibility issues when String becomes a collection
@_transparent
public func min<T : Comparable>(_ x: T, _ y: T) -> T {
return Swift.min(x,y)
}
}
extension Sequence where Element == String {
@available(*, unavailable, message: "Operator '+' cannot be used to append a String to a sequence of strings")
public static func + (lhs: Self, rhs: String) -> Never {
fatalError()
}
@available(*, unavailable, message: "Operator '+' cannot be used to append a String to a sequence of strings")
public static func + (lhs: String, rhs: Self) -> Never {
fatalError()
}
}
| 34.82 | 112 | 0.645032 |
1abfc010b68df6ee661df4d0c2ac3d5e8a437f58 | 969 | //
// puzzleTests.swift
// puzzleTests
//
// Created by globalwings on 2018/9/17.
// Copyright © 2018年 globalwings . All rights reserved.
//
import XCTest
@testable import puzzle
class puzzleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.189189 | 111 | 0.631579 |
69fcc4022a824913683f4b8b7a4291a405be1e9d | 6,866 | //
// OrdersMemStore.swift
// CleanStore
//
// Created by Raymond Law on 2/12/19.
// Copyright © 2019 Clean Swift LLC. All rights reserved.
//
import Foundation
class OrdersMemStore: OrdersStoreProtocol, OrdersStoreUtilityProtocol
{
// MARK: - Data
static var billingAddress = Address(street1: "1 Infinite Loop", street2: "", city: "Cupertino", state: "CA", zip: "95014")
static var shipmentAddress = Address(street1: "One Microsoft Way", street2: "", city: "Redmond", state: "WA", zip: "98052-7329")
static var paymentMethod = PaymentMethod(creditCardNumber: "1234-123456-1234", expirationDate: Date(), cvv: "999")
static var shipmentMethod = ShipmentMethod(speed: .OneDay)
static var orders = [
Order(firstName: "Amy", lastName: "Apple", phone: "111-111-1111", email: "[email protected]", billingAddress: billingAddress, paymentMethod: paymentMethod, shipmentAddress: shipmentAddress, shipmentMethod: shipmentMethod, id: "abc123", date: Date(), total: NSDecimalNumber(string: "1.23")),
Order(firstName: "Bob", lastName: "Battery", phone: "222-222-2222", email: "[email protected]", billingAddress: billingAddress, paymentMethod: paymentMethod, shipmentAddress: shipmentAddress, shipmentMethod: shipmentMethod, id: "def456", date: Date(), total: NSDecimalNumber(string: "4.56"))
]
// MARK: - CRUD operations - Optional error
func fetchOrders(completionHandler: @escaping ([Order], OrdersStoreError?) -> Void)
{
completionHandler(type(of: self).orders, nil)
}
func fetchOrder(id: String, completionHandler: @escaping (Order?, OrdersStoreError?) -> Void)
{
if let index = indexOfOrderWithID(id: id) {
let order = type(of: self).orders[index]
completionHandler(order, nil)
} else {
completionHandler(nil, OrdersStoreError.CannotFetch("Cannot fetch order with id \(id)"))
}
}
func createOrder(orderToCreate: Order, completionHandler: @escaping (Order?, OrdersStoreError?) -> Void)
{
var order = orderToCreate
generateOrderID(order: &order)
calculateOrderTotal(order: &order)
type(of: self).orders.append(order)
completionHandler(order, nil)
}
func updateOrder(orderToUpdate: Order, completionHandler: @escaping (Order?, OrdersStoreError?) -> Void)
{
if let index = indexOfOrderWithID(id: orderToUpdate.id) {
type(of: self).orders[index] = orderToUpdate
let order = type(of: self).orders[index]
completionHandler(order, nil)
} else {
completionHandler(nil, OrdersStoreError.CannotUpdate("Cannot fetch order with id \(String(describing: orderToUpdate.id)) to update"))
}
}
func deleteOrder(id: String, completionHandler: @escaping (Order?, OrdersStoreError?) -> Void)
{
if let index = indexOfOrderWithID(id: id) {
let order = type(of: self).orders.remove(at: index)
completionHandler(order, nil)
return
}
completionHandler(nil, OrdersStoreError.CannotDelete("Cannot fetch order with id \(id) to delete"))
}
// MARK: - CRUD operations - Generic enum result type
func fetchOrders(completionHandler: @escaping OrdersStoreFetchOrdersCompletionHandler)
{
completionHandler(OrdersStoreResult.Success(result: type(of: self).orders))
}
func fetchOrder(id: String, completionHandler: @escaping OrdersStoreFetchOrderCompletionHandler)
{
let order = type(of: self).orders.filter { (order: Order) -> Bool in
return order.id == id
}.first
if let order = order {
completionHandler(OrdersStoreResult.Success(result: order))
} else {
completionHandler(OrdersStoreResult.Failure(error: OrdersStoreError.CannotFetch("Cannot fetch order with id \(id)")))
}
}
func createOrder(orderToCreate: Order, completionHandler: @escaping OrdersStoreCreateOrderCompletionHandler)
{
var order = orderToCreate
generateOrderID(order: &order)
calculateOrderTotal(order: &order)
type(of: self).orders.append(order)
completionHandler(OrdersStoreResult.Success(result: order))
}
func updateOrder(orderToUpdate: Order, completionHandler: @escaping OrdersStoreUpdateOrderCompletionHandler)
{
if let index = indexOfOrderWithID(id: orderToUpdate.id) {
type(of: self).orders[index] = orderToUpdate
let order = type(of: self).orders[index]
completionHandler(OrdersStoreResult.Success(result: order))
} else {
completionHandler(OrdersStoreResult.Failure(error: OrdersStoreError.CannotUpdate("Cannot update order with id \(String(describing: orderToUpdate.id)) to update")))
}
}
func deleteOrder(id: String, completionHandler: @escaping OrdersStoreDeleteOrderCompletionHandler)
{
if let index = indexOfOrderWithID(id: id) {
let order = type(of: self).orders.remove(at: index)
completionHandler(OrdersStoreResult.Success(result: order))
return
}
completionHandler(OrdersStoreResult.Failure(error: OrdersStoreError.CannotDelete("Cannot delete order with id \(id) to delete")))
}
// MARK: - CRUD operations - Inner closure
func fetchOrders(completionHandler: @escaping (() throws -> [Order]) -> Void)
{
completionHandler { return type(of: self).orders }
}
func fetchOrder(id: String, completionHandler: @escaping (() throws -> Order?) -> Void)
{
if let index = indexOfOrderWithID(id: id) {
completionHandler { return type(of: self).orders[index] }
} else {
completionHandler { throw OrdersStoreError.CannotFetch("Cannot fetch order with id \(id)") }
}
}
func createOrder(orderToCreate: Order, completionHandler: @escaping (() throws -> Order?) -> Void)
{
var order = orderToCreate
generateOrderID(order: &order)
calculateOrderTotal(order: &order)
type(of: self).orders.append(order)
completionHandler { return order }
}
func updateOrder(orderToUpdate: Order, completionHandler: @escaping (() throws -> Order?) -> Void)
{
if let index = indexOfOrderWithID(id: orderToUpdate.id) {
type(of: self).orders[index] = orderToUpdate
let order = type(of: self).orders[index]
completionHandler { return order }
} else {
completionHandler { throw OrdersStoreError.CannotUpdate("Cannot fetch order with id \(String(describing: orderToUpdate.id)) to update") }
}
}
func deleteOrder(id: String, completionHandler: @escaping (() throws -> Order?) -> Void)
{
if let index = indexOfOrderWithID(id: id) {
let order = type(of: self).orders.remove(at: index)
completionHandler { return order }
} else {
completionHandler { throw OrdersStoreError.CannotDelete("Cannot fetch order with id \(id) to delete") }
}
}
// MARK: - Convenience methods
private func indexOfOrderWithID(id: String?) -> Int?
{
return type(of: self).orders.index { return $0.id == id }
}
}
| 39.45977 | 305 | 0.700699 |
7210b78eb7e8dfc0fa93cb1b49fef4943e8b3caf | 914 | #if !canImport(ObjectiveC)
import XCTest
extension JWTKitTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__JWTKitTests = [
("testECDSAGenerate", testECDSAGenerate),
("testECDSAPublicPrivate", testECDSAPublicPrivate),
("testExpirationDecoding", testExpirationDecoding),
("testExpirationEncoding", testExpirationEncoding),
("testExpired", testExpired),
("testJWKS", testJWKS),
("testJWKSigner", testJWKSigner),
("testJWTioExample", testJWTioExample),
("testParse", testParse),
("testRSA", testRSA),
("testRSASignWithPublic", testRSASignWithPublic),
("testSigners", testSigners),
]
}
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(JWTKitTests.__allTests__JWTKitTests),
]
}
#endif
| 30.466667 | 59 | 0.658643 |
dbe5bc3f9802a4f1d9a7c2442282d6f94d30feec | 3,424 | //
// ViewController.swift
// MusicWithColor
//
// Created by Marcy Vernon on 5/28/20.
// Copyright © 2020 Marcy Vernon. All rights reserved.
//
// Wallpaper by Kevin MacLeod
// Link: https://incompetech.filmmusic.io/song/4604-wallpaper
// License: http://creativecommons.org/licenses/by/4.0/
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet var buttonMusic: UIButton!
private var audioManager: AudioPlayerManager = AudioPlayerManager()
private let gradientLayer = CAGradientLayer()
private weak var timer : Timer?
private var previousColor = UIColor.clear
private var hasStarted : Bool = false
private var random : CGFloat { return .random(in: 0...1) }
private var color : CGColor { return UIColor(red: random, green: random, blue: random, alpha: 1).cgColor }
private var point : CGPoint { return CGPoint(x: random, y: random) }
override func viewDidLoad() {
super.viewDidLoad()
audioManager.setupPlayer(soundName: "wallpaper", soundType: .mp3)
setNotifications()
setupGradient()
}
private func setNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterBackground),
name: .sceneDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.willEnterForeground),
name: .sceneWillEnterForeground, object: nil)
}
private func setupGradient() {
gradientLayer.frame = view.bounds
view.layer.addSublayer(gradientLayer)
}
@IBAction func playMusic(_ sender: Any) {
hasStarted = true
if timer == nil {
setupGradient()
audioManager.play()
previousColor = view.backgroundColor ?? UIColor.clear
setupTimer()
} else {
timer?.invalidate()
audioManager.pause()
gradientLayer.removeFromSuperlayer()
view.backgroundColor = previousColor
}
}
private func setupTimer() {
if timer == nil {
timer = Timer.scheduledTimer(timeInterval : 0.5,
target : self,
selector : #selector(changeGradient),
userInfo : nil, repeats : true)
}
}
@objc func changeGradient() {
gradientLayer.startPoint = point
gradientLayer.endPoint = point
let typeArray: [ CAGradientLayerType ] = [.radial, .axial, .radial, .conic, .radial, .axial]
let index = Int.random(in: 0...5)
gradientLayer.type = typeArray[index]
let color1 = color
let color2 = color
gradientLayer.colors = [ color1, color2, color1, color2, color1, color2, color1, color2, color1, color2,
color1, color2, color1, color2, color1, color2, color1]
}
@objc func didEnterBackground() {
timer?.invalidate()
}
@objc func willEnterForeground() {
if hasStarted { setupTimer() }
}
override var prefersStatusBarHidden: Bool {
return true
}
} // end of ViewController
| 31.703704 | 116 | 0.580315 |
db6d9e55da5a35680229292c77b2b502a1fe3810 | 1,123 | import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import AppKit
class NSImageViewSpec: QuickSpec {
override func spec() {
var imageView: NSImageView!
weak var _imageView: NSImageView?
beforeEach {
imageView = NSImageView(frame: .zero)
_imageView = imageView
}
afterEach {
imageView = nil
expect(_imageView).to(beNil())
}
it("should accept changes from bindings to its enabling state") {
imageView.isEnabled = false
let (pipeSignal, observer) = Signal<Bool, Never>.pipe()
imageView.reactive.isEnabled <~ SignalProducer(pipeSignal)
observer.send(value: true)
expect(imageView.isEnabled) == true
observer.send(value: false)
expect(imageView.isEnabled) == false
}
it("should accept changes from bindings to its image") {
let (pipeSignal, observer) = Signal<NSImage?, Never>.pipe()
imageView.reactive.image <~ SignalProducer(pipeSignal)
let theImage = NSImage(named: NSImage.userName)
observer.send(value: theImage)
expect(imageView.image) == theImage
observer.send(value: nil)
expect(imageView.image).to(beNil())
}
}
}
| 22.019608 | 67 | 0.71683 |
bb698548531c8321e29d921852f4102c4a3391c8 | 3,109 | /**
* Copyright IBM Corporation 2018
*
* 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 KituraStencil
import LoggerAPI
import Stencil
func initializeStencilRoutes(app: App) {
// add Stencil Template Engine with a extension with a custom tag
let _extension = Extension()
// from https://github.com/kylef/Stencil/blob/master/ARCHITECTURE.md#simple-tags
_extension.registerSimpleTag("custom") { _ in
return "Hello World"
}
let templateEngine = StencilTemplateEngine(extension: _extension)
app.router.add(templateEngine: templateEngine,
forFileExtensions: ["html"])
// the example from https://github.com/kylef/Stencil
let stencilContext: [String: Any] = [
"articles": [
[ "title": "Migrating from OCUnit to XCTest", "author": "Kyle Fuller" ],
[ "title": "Memory Management with ARC", "author": "Kyle Fuller" ],
]
]
app.router.get("/articles") { _, response, next in
defer {
next()
}
do {
try response.render("document.stencil", context: stencilContext).end()
} catch {
Log.error("Failed to render template \(error)")
}
}
app.router.get("/articles.html") { _, response, next in
defer {
next()
}
do {
// we have to specify file extension here since it is not the extension of Stencil
try response.render("document.html", context: stencilContext).end()
} catch {
Log.error("Failed to render template \(error)")
}
}
app.router.get("/articles_subdirectory") { _, response, next in
defer {
next()
}
do {
try response.render("subdirectory/documentInSubdirectory.stencil",
context: stencilContext).end()
} catch {
Log.error("Failed to render template \(error)")
}
}
app.router.get("/articles_include") { _, response, next in
defer {
next()
}
do {
try response.render("includingDocument.stencil",
context: stencilContext).end()
} catch {
Log.error("Failed to render template \(error)")
}
}
app.router.get("/custom_tag_stencil") { _, response, next in
defer {
next()
}
do {
try response.render("customTag.stencil", context: [:]).end()
} catch {
Log.error("Failed to render template \(error)")
}
}
}
| 31.40404 | 94 | 0.587327 |
4a14a5f28bc2acb24364b0c473a41f4f4bff7d35 | 760 | #if MIXBOX_ENABLE_IN_APP_SERVICES
public final class RandomSetGenerator<T: Hashable>: Generator<Set<T>> {
public init(anyGenerator: AnyGenerator, lengthGenerator: Generator<Int>) {
super.init {
var set = Set<T>()
let length = try lengthGenerator.generate()
// It is not perfect, but it probably can generate something for most cases.
// Of course it can't generate set of unique booleans of size 3.
let attemptsToGenerateUniqueValue = length * 2
for _ in 0..<attemptsToGenerateUniqueValue where set.count < length {
set.insert(try anyGenerator.generate())
}
return set
}
}
}
#endif
| 31.666667 | 88 | 0.590789 |
d935128bee4844077342f5f97c78cfc7b6937e1f | 3,440 | //
// CartDeliveryCompleteTabDetailsCell.swift
// chef
//
// Created by Eddie Ha on 19/8/19.
// Copyright © 2019 MacBook Pro. All rights reserved.
//
import UIKit
class CartDeliveryCompleteTabDetailsCell: UICollectionViewCell {
//MARK: Properties
public let CLASS_NAME = CartDeliveryCompleteTabDetailsCell.self.description()
open var deliveryCompleteCartItemList = [CartItem](){
didSet{
self.cvCartList.reloadData()
}
}
//MARK: Outlets
@IBOutlet weak var uivContainer: UIView!
@IBOutlet weak var cvCartList: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
initialization()
}
//MARK: Intsance Method
//initialization
private func initialization() -> Void {
//init collectionviews
cvCartList.delegate = self
cvCartList.dataSource = self
//set collection view cell item cell
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
// layout.itemSize = CGSize(width: (cvTabBar.frame.width/2)-15, height: (cvTabBar.frame.width/2)-15)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .vertical
cvCartList.collectionViewLayout = layout
//Register cell
cvCartList?.register(UINib(nibName: "CartDeliveryCompleteCell", bundle: nil), forCellWithReuseIdentifier: "CartDeliveryCompleteCell")
}
}
//MARK: Extension
//MARK: CollectionView
extension CartDeliveryCompleteTabDetailsCell : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if deliveryCompleteCartItemList.isEmpty{
collectionView.setEmptyMessage("Delivery orders appear here")
}else{
collectionView.restore()
}
return deliveryCompleteCartItemList.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//for tab bar cell
return CGSize(width: cvCartList.frame.width, height: 130)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//for first cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CartDeliveryCompleteCell", for: indexPath) as! CartDeliveryCompleteCell
cell.uivContainer.elevate(elevation: 15, cornerRadius: 0, color : ColorGenerator.UIColorFromHex(rgbValue: 0x000000, alpha: 0.3))
let deliveryCompleteOrder = deliveryCompleteCartItemList[indexPath.row]
cell.lblTitle.text = deliveryCompleteOrder.name
cell.lblPrice.text = "$\(deliveryCompleteOrder.price ?? 0)"
if let imageUrl = deliveryCompleteOrder.featuredImage {
cell.ivFoodImage.setImageFromUrl(url: imageUrl)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
| 33.72549 | 160 | 0.677035 |
0129ccc8c8cfc593a038a7b05a35a900c15c0a84 | 348 | //
// Laser.swift
// NavalWars
//
// Created by Damian Modernell on 21/05/2019.
// Copyright © 2019 Damian Modernell. All rights reserved.
//
import Foundation
public final class Laser: Directionable {
public var direction: PointingDirection
public init(direction: PointingDirection) {
self.direction = direction
}
}
| 19.333333 | 59 | 0.692529 |
ac0688cf646d8bc28fffbc3d4974f71c3aad93d4 | 697 | import EmceeLib
import Foundation
import PathLib
import RunnerModels
import SimulatorPoolModels
import TestHelpers
public final class FakeSimulatorSetPathDeterminer: SimulatorSetPathDeterminer {
public var provider: (SimulatorLocation) throws -> AbsolutePath
public init(provider: @escaping (SimulatorLocation) throws -> AbsolutePath = { throw ErrorForTestingPurposes(text: "Error getting simulator set path for test tool with location \($0)") }) {
self.provider = provider
}
public func simulatorSetPathSuitableForTestRunnerTool(
simulatorLocation: SimulatorLocation
) throws -> AbsolutePath {
return try provider(simulatorLocation)
}
}
| 33.190476 | 193 | 0.758967 |
ef0534e8a600de58078187f268a79fee0599855c | 386 | //
// TryItOutEnumView.swift
// Swagger
//
// Created by 李鹏飞 on 2020/4/24.
// Copyright © 2020 LPF. All rights reserved.
//
import UIKit
class TryItOutEnumView: TryItOutPropertyView {
@IBOutlet weak var enumButton: UIButton!
override var property: Property? {
didSet {
enumButton.setTitle(property?.enums?.first, for: .normal)
}
}
}
| 17.545455 | 69 | 0.634715 |
ab24a048afc132804bf2b2750f0dc69d825de177 | 2,702 | //
// Copyright (c) Vatsal Manot
//
import Combine
import Swift
import SwiftUI
#if os(iOS) || os(macOS) || os(tvOS) || targetEnvironment(macCatalyst)
/// A set of properties for determining whether to recompute the size of items or their position in the layout.
public protocol CollectionViewLayout {
var hashValue: Int { get }
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
func _toUICollectionViewLayout() -> UICollectionViewLayout
#elseif os(macOS)
func _toNSCollectionViewLayout() -> NSCollectionViewLayout
#endif
}
// MARK: - API -
extension View {
public func collectionViewLayout(_ layout: CollectionViewLayout) -> some View {
environment(\.collectionViewLayout, layout)
}
}
// MARK: - Auxiliary Implementation -
private struct _CollectionViewLayoutEnvironmentKey: EnvironmentKey {
static let defaultValue: CollectionViewLayout = FlowCollectionViewLayout()
}
extension EnvironmentValues {
var collectionViewLayout: CollectionViewLayout {
get {
self[_CollectionViewLayoutEnvironmentKey]
} set {
self[_CollectionViewLayoutEnvironmentKey] = newValue
}
}
}
// MARK: - Conformances -
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
public struct FlowCollectionViewLayout: Hashable, CollectionViewLayout {
public let minimumLineSpacing: CGFloat?
public let minimumInteritemSpacing: CGFloat?
public init(
minimumLineSpacing: CGFloat? = nil,
minimumInteritemSpacing: CGFloat? = nil
) {
self.minimumLineSpacing = minimumLineSpacing
self.minimumInteritemSpacing = minimumInteritemSpacing
}
public func _toUICollectionViewLayout() -> UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
if let minimumLineSpacing = minimumLineSpacing {
layout.minimumLineSpacing = minimumLineSpacing
}
if let minimumInteritemSpacing = minimumInteritemSpacing {
layout.minimumInteritemSpacing = minimumInteritemSpacing
}
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
layout.itemSize = UICollectionViewFlowLayout.automaticSize
return layout
}
}
extension UICollectionViewLayout: CollectionViewLayout {
public func _toUICollectionViewLayout() -> UICollectionViewLayout {
self
}
}
#elseif os(macOS)
public struct FlowCollectionViewLayout: Hashable, CollectionViewLayout {
public init() {
}
public func _toNSCollectionViewLayout() -> NSCollectionViewLayout {
NSCollectionViewLayout()
}
}
#endif
#endif
| 26.752475 | 111 | 0.700222 |
fcd72f915530492fb9881d1535d4bf00026f7367 | 2,059 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// rdar://71642726 this test is crashing with optimizations.
// REQUIRES: swift_test_mode_optimize_none
import _Differentiation
import StdlibUnittest
var ZeroTangentVectorTests = TestSuite("zeroTangentVectorInitializer")
struct Generic<T: Differentiable, U: Differentiable>: Differentiable {
var x: T
var y: U
}
struct Nested<T: Differentiable, U: Differentiable>: Differentiable {
var generic: Generic<T, U>
}
ZeroTangentVectorTests.test("Derivation") {
typealias G = Generic<[Float], [[Float]]>
let generic = G(x: [1, 2, 3], y: [[4, 5, 6], [], [2]])
let genericZero = G.TangentVector(x: [0, 0, 0], y: [[0, 0, 0], [], [0]])
expectEqual(generic.zeroTangentVector, genericZero)
let nested = Nested(generic: generic)
let nestedZero = Nested.TangentVector(generic: genericZero)
expectEqual(nested.zeroTangentVector, nestedZero)
}
// Test differentiation correctness involving projection operations and
// per-instance zeros.
ZeroTangentVectorTests.test("DifferentiationCorrectness") {
struct Struct: Differentiable {
var x, y: [Float]
}
func concatenated(_ lhs: Struct, _ rhs: Struct) -> Struct {
return Struct(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
func test(_ s: Struct) -> [Float] {
let result = concatenated(s, s).withDerivative { dresult in
// FIXME(TF-1008): Fix incorrect derivative values for
// "projection operation" operands when differentiation transform uses
// `Differentiable.zeroTangentVectorInitializer`.
// Actual: TangentVector(x: [1.0, 1.0, 1.0], y: [])
// Expected: TangentVector(x: [1.0, 1.0, 1.0], y: [1.0, 1.0, 1.0])
expectEqual(dresult, Struct.TangentVector(x: [1, 1, 1], y: [1, 1, 1]))
}
return result.x
}
let s = Struct(x: [1, 2, 3], y: [1, 2, 3])
let pb = pullback(at: s, in: test)
// FIXME(TF-1008): Remove `expectCrash` when differentiation transform uses
// `Differentiable.zeroTangentVectorInitializer`.
expectCrash {
_ = pb([1, 1, 1])
}
}
runAllTests()
| 33.209677 | 77 | 0.681399 |
fb58413e5c66eea40699c5d416573e9600c3df3a | 886 | //
// TitleCheckBoxButton.swift
// YogiYoCloneIOS
//
// Created by 김동현 on 2020/08/26.
// Copyright © 2020 김동현. All rights reserved.
//
import UIKit
class CheckBoxButton: UIButton {
// MARK: Init
override init(frame: CGRect) {
super.init(frame: frame)
configureViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: ConfigureViews
private func configureViews() {
setImage(UIImage(named: "EmptyBox"), for: .normal)
imageView?.contentMode = .scaleAspectFit
titleEdgeInsets = UIEdgeInsets(top: 0, left: -17, bottom: 0, right: 0)
setTitle("약관 전체동의", for: .normal)
setTitleColor(.black, for: .normal)
titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
contentHorizontalAlignment = .left
}
}
| 26.058824 | 78 | 0.626411 |
3adfeb3114115a7e7438d1af8662e2467cba7a42 | 800 | //
// DispatchOnce.swift
// BetterKit
//
// Created by Nathan Jangula on 3/15/18.
//
import Foundation
internal class DispatchOnce : NSObject {
private var locked: Bool
@objc public func perform(_ block: () -> Void) {
if !locked {
locked = true
block()
}
}
private override init() {
locked = false
}
public static func load(key: UnsafeRawPointer) -> DispatchOnce {
var dispatch = objc_getAssociatedObject(NSObject.self, key) as? DispatchOnce
if dispatch == nil {
dispatch = DispatchOnce()
objc_setAssociatedObject(NSObject.self, key, dispatch, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return dispatch!
}
}
| 22.222222 | 124 | 0.59 |
eb57e312660f7e5f60b0645c22aa680fb62aa946 | 1,525 | // Copyright 2016-2018 Cisco Systems 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
extension URL {
var queryParameters: [String: String] {
var queryParameters = [String: String]()
let pairs = self.query?.components(separatedBy: "&") ?? []
for pair in pairs {
let kv = pair.components(separatedBy: "=")
queryParameters.updateValue(kv[1], forKey: kv[0])
}
return queryParameters
}
}
| 42.361111 | 80 | 0.712787 |
f4cdd6890cfb00205e3e4419cc189eac46be3e87 | 1,098 | //
// ViewController.swift
// preWork
//
// Created by David Cristobal on 9/1/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var tipAmountLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calculateTip(_ sender: Any) {
let bill = Double(billAmountTextField.text!) ?? 0
//ttl tip by multiplying tip* tpercentage
let tipPercentages = [0.15, 0.18, 0.2]
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
//updtae tip amt
tipAmountLabel.text = String(format: "$%.2f", tip)
//update ttl amt
totalLabel.text = String(format: "$%.2f", total)
}
}
| 24.954545 | 80 | 0.569217 |
fcb5c0f21039d854c2bd30f2feee9d7f54f3cb8c | 597 | //
// SettingFirstCell.swift
// DouYuTV
//
// Created by 单琦 on 2018/5/25.
// Copyright © 2018年 单琦. All rights reserved.
//
import UIKit
class SettingFirstCell: UITableViewCell,RegisterCellFromNib {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.111111 | 65 | 0.673367 |
d512cd46d39f531958458bdd4fcecee46c6604d9 | 2,810 | // CoachMarkArrowDefaultView.swift
//
// Copyright (c) 2015, 2016 Frédéric Maquin <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// swiftlint:disable line_length
// MARK: - Default Class
/// A concrete implementation of the coach mark arrow view and the
/// default one provided by the library.
public class CoachMarkArrowDefaultView: UIImageView, CoachMarkArrowView {
// MARK: - Initialization
public init(orientation: CoachMarkArrowOrientation) {
let image, highlightedImage: UIImage?
if orientation == .top {
image = UIImage(namedInInstructions: "arrow-top")
highlightedImage = UIImage(namedInInstructions: "arrow-top-highlighted")
} else {
image = UIImage(namedInInstructions: "arrow-bottom")
highlightedImage = UIImage(namedInInstructions: "arrow-bottom-highlighted")
}
super.init(image: image, highlightedImage: highlightedImage)
initializeConstraints()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding.")
}
}
// MARK: - Private Inner Setup
private extension CoachMarkArrowDefaultView {
func initializeConstraints() {
self.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.image!.size.width))
constraints.append(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.image!.size.height))
self.addConstraints(constraints)
}
}
| 43.230769 | 188 | 0.731317 |
2980550e3cb53d0f7ebb7f2a202e11144a8aad62 | 948 | //
// Pet.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
/** A pet for sale in the pet store */
public struct Pet: Codable {
public enum Status: String, Codable, CaseIterable {
case available = "available"
case pending = "pending"
case sold = "sold"
}
public var id: Int64?
public var category: Category?
public var name: String?
@available(*, deprecated, message: "This property is deprecated.")
public var photoUrls: [String]
public var tags: [Tag]?
/** pet status in the store */
public var status: Status?
public init(id: Int64? = nil, category: Category? = nil, name: String?, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) {
self.id = id
self.category = category
self.name = name
self.photoUrls = photoUrls
self.tags = tags
self.status = status
}
}
| 25.621622 | 141 | 0.616034 |
110f1adf3b6349b9c9485fc8f9065119de09e941 | 3,253 | //
// TipItemTests.swift
// TipSee_Example
//
// Created by Farshad Jahanmanesh on 7/19/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import XCTest
import TipSee
class TipItemTests: XCTestCase {
let id = "55"
var sut : TipSee.TipItem!
var targetView : UIView!
var bubbleContetView : UIView!
override func setUp() {
super.setUp()
targetView = UIView()
bubbleContetView = UIView()
sut = TipSee.TipItem(ID: id, pointTo: targetView, contentView: bubbleContetView)
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
sut = nil
targetView = nil
bubbleContetView = nil
super.tearDown()
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testDefaultOption(){
XCTAssertNil(sut.bubbleOptions)
}
func testCustomConfig(){
// when
sut.bubbleOptions = TipSee.Options.Bubble.default().with{
$0.backgroundColor = .blue
}
XCTAssertNotNil(sut.bubbleOptions)
XCTAssertNotNil(sut.bubbleOptions!.backgroundColor == .blue)
}
func testEquality(){
// given
var new = TipSee.TipItem(ID: "2", pointTo: UIView(), contentView: UIView())
// when
new.ID = id
// then
XCTAssertEqual(new, sut)
}
func testCustomConfigInInit(){
// given
let new = TipSee.TipItem(ID: "2", pointTo: UIView(), contentView: UIView(),bubbleOptions: TipSee.Options.Bubble.default().with{$0.backgroundColor = .blue})
// when
sut.bubbleOptions = TipSee.Options.Bubble.default().with{
$0.backgroundColor = .blue
}
// then
XCTAssertEqual(new.bubbleOptions!.backgroundColor, sut.bubbleOptions!.backgroundColor)
}
func testCustomBubbeTap(){
// when
sut.bubbleOptions = TipSee.Options.Bubble.default().with{
$0.backgroundColor = .blue
$0.onBubbleTap = {_ in }
}
// then
XCTAssertNotNil(sut.bubbleOptions!.onBubbleTap)
}
func testCustomFont(){
// given
let new = TipSee.createItem(for: SimpleTipTarget(on: .zero,cornerRadius: 0), text: "XYS",with: TipSee.Options.Bubble.default().with{$0.font = .italicSystemFont(ofSize: 100)})
// then
XCTAssertEqual((new.contentView as! UILabel).font, UIFont.italicSystemFont(ofSize: 100))
}
func testMEMORYLEAK(){
// given
var xView : UIView? = UIView()
let count = CFGetRetainCount(xView!)
let _ = TipSee.TipItem(ID: "2", pointTo: xView!, contentView: UIView(),bubbleOptions: TipSee.Options.Bubble.default().with{$0.backgroundColor = .blue})
let _ = TipSee.TipItem(ID: "2", pointTo: xView!, contentView: UIView(),bubbleOptions: TipSee.Options.Bubble.default().with{$0.backgroundColor = .blue})
let _ = TipSee.TipItem(ID: "2", pointTo: xView!, contentView: UIView(),bubbleOptions: TipSee.Options.Bubble.default().with{$0.backgroundColor = .blue})
let count2 = CFGetRetainCount(xView!)
xView = nil
// then
XCTAssertEqual(count2, count)
XCTAssertNil(xView)
}
}
| 29.844037 | 176 | 0.640332 |
3375ee2c8d68b0ff33129bd0e28ec8329bc449e4 | 457 | //
// UIButton+Combine.swift
// CombineCocoa
//
// Created by Shai Mishali on 02/08/2019.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if !(os(iOS) && (arch(i386) || arch(arm)))
import Combine
import UIKit
@available(iOS 13.0, *)
public extension UIButton {
/// A publisher emitting tap events from this button.
var tapPublisher: AnyPublisher<Void, Never> {
controlEventPublisher(for: .touchUpInside)
}
}
#endif
| 21.761905 | 60 | 0.680525 |
289335a1bfdcf1a5f90fff30dae73be98b94feca | 1,124 | //
// ByteBuffer+SubAckPacket.swift
// NIOMQTT
//
// Created by Bofei Zhu on 8/14/19.
// Copyright © 2019 HealthTap Inc. All rights reserved.
//
import NIO
extension ByteBuffer {
mutating func readSubAckPacket(with fixedHeader: FixedHeader) throws -> SubAckPacket {
// MARK: Read variable header
let packetIdentifier = try readPacketIdentifier()
var variableHeaderLength = UInt16.byteCount
let properties = try readProperties()
variableHeaderLength += properties.mqttByteCount
let variableHeader = SubAckPacket.VariableHeader(
packetIdentifier: packetIdentifier,
properties: properties)
// MARK: Read payload
let remainingLength = Int(fixedHeader.remainingLength.value)
let payloadLength = remainingLength - variableHeaderLength
let reasonCodes: [SubAckPacket.ReasonCode] = try readReasonCodeList(length: payloadLength)
let payload = SubAckPacket.Payload(reasonCodes: reasonCodes)
return SubAckPacket(fixedHeader: fixedHeader, variableHeader: variableHeader, payload: payload)
}
}
| 29.578947 | 103 | 0.709075 |
e6a1ad85bea1398b33c7b56e031a5237b971ff71 | 1,932 | //
// AutomaticScreenViewsTracker.swift
// Ometria
//
// Created by Cata on 7/30/20.
// Copyright © 2020 Cata. All rights reserved.
//
import Foundation
import UIKit
class AutomaticScreenViewsTracker {
var isRunning = false
func startTracking() {
guard !isRunning else {
return
}
isRunning = true
swizzleViewDidAppear()
}
func stopTracking() {
guard isRunning else {
return
}
isRunning = false
unswizzleViewDidAppear()
}
func swizzleViewDidAppear() {
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
let swizzledSelector = #selector(UIViewController.om_viewDidAppear(_:))
Swizzler.swizzleSelector(originalSelector, withSelector: swizzledSelector, for: UIViewController.self, name: "OmetriaViewDidAppear") { (_, _, _, _) in
}
}
func unswizzleViewDidAppear() {
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
Swizzler.unswizzleSelector(originalSelector, aClass: UIViewController.self)
}
}
extension UIViewController {
@objc func om_viewDidAppear(_ animated: Bool) {
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
if let swizzle = Swizzler.getSwizzle(for: originalSelector, in: type(of: self)) {
typealias MyCFunction = @convention(c) (AnyObject, Selector, Bool) -> Void
let curriedImplementation = unsafeBitCast(swizzle.originalMethod, to: MyCFunction.self)
curriedImplementation(self, originalSelector, animated)
}
let screenClassName = String(describing:type(of:self))
Logger.verbose(message: "Custom view did appear: \(screenClassName)")
Ometria.sharedInstance().trackScreenViewedAutomaticEvent(screenName: screenClassName)
}
}
| 30.666667 | 158 | 0.654762 |
397c6e61d7ca2dc10b7abf54e2ef33a2b3db8611 | 1,155 | //
// MainSceneFactory.swift
//
//
// © Copyright IBM Deutschland GmbH 2021
// SPDX-License-Identifier: Apache-2.0
//
import CovPassCommon
import CovPassUI
import UIKit
struct MainSceneFactory: SceneFactory {
// MARK: - Properties
private let sceneCoordinator: SceneCoordinator
// MARK: - Lifecycle
init(sceneCoordinator: SceneCoordinator) {
self.sceneCoordinator = sceneCoordinator
}
func make() -> UIViewController {
UserDefaults.StartupInfo.bool(.onboarding) ?
mainViewController() :
welcomeViewController()
}
private func welcomeViewController() -> UIViewController {
let router = WelcomeRouter(sceneCoordinator: sceneCoordinator)
let factory = WelcomeSceneFactory(router: router)
let viewController = factory.make()
return viewController
}
private func mainViewController() -> UIViewController {
let router = ValidatorOverviewRouter(sceneCoordinator: sceneCoordinator)
let factory = ValidatorOverviewSceneFactory(router: router)
let viewController = factory.make()
return viewController
}
}
| 26.25 | 80 | 0.692641 |
fcd61614564673c972bfa2df69c05e2d40324a04 | 803 | //
// ButtonClose.swift
// CloudSquad
//
// Created by Alberto Lourenço on 2/13/20.
// Copyright © 2020 Alberto Lourenço. All rights reserved.
//
import SwiftUI
struct ButtonClose: View {
var body: some View {
VStack {
HStack {
Spacer()
Image(systemName: "xmark")
.frame(width: 36, height: 36)
.foregroundColor(.white)
.background(Color.black)
.clipShape(Circle())
}
}
.offset(x: -16)
.transition(.move(edge: .top))
.animation(.spring(response: 0.6, dampingFraction: 0.8, blendDuration: 0))
}
}
struct ButtonClose_Previews: PreviewProvider {
static var previews: some View {
ButtonClose()
}
}
| 21.702703 | 82 | 0.531756 |
f719bc0b9197fd26764c9e26377a9c48f7b10b58 | 9,485 | //
// WalkingSpeedUtilities.swift
// SmoothWalker
//
// Created by Terence Chan on 3/26/21.
// Copyright © 2021 Apple. All rights reserved.
//
import UIKit
import Foundation
import HealthKit
//
// This file contains utility functions and data to support
// the gathering and display of daily, weekly and monthly
// walking speed charts and tables.
//
// -------------------------------------------------------------------------
// Walking speed HKUnit
//
let meterPerSecond = HKUnit(from: "m/s")
let WEEK_SUFFIX = " wk"
//
// -------------------------------------------------------------------------
// Utilities to handle the display of different
// walking speed timelines
//
enum Timeline : String, CaseIterable {
case daily = "Daily"
case weekly = "Weekly"
case monthly = "Monthly"
}
struct HealthDataValueTemp {
var startDate : Date
var endDate : Date
var valueSum : (Double,Int)
}
//
// -------------------------------------------------------------------------
//
// Calendar month titles
//
let monthTitles = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
//
// Maximum days of each calendar month (leap year is handled separately)
//
fileprivate let daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
//
// Extract month, day and year from a given date
//
func extractDate(_ inDate : Date ) -> (year : Int, month : Int, day : Int)
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let results = dateFormatter.string(for:inDate)?.components(separatedBy: "-"),
results.count == 3,
let year = Int(results[0]), let month = Int(results[1]), let day = Int(results[2])
{
return (year,month,day)
}
return (-1,-1,-1)
}
//
// Check a given year is a leap year
//
private func leapYear(_ year : Int) -> Bool {
(year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)
}
//
// Return the max days of a given month, take into account of leap year
//
func maxDaysOfMonth(_ month : Int, _ year : Int) -> Int {
return month == 2 && leapYear(year) ? 29 : daysPerMonth[month-1]
}
//
// Create a Date object from the given year, month and day
//
func composeDate(_ year : Int, _ month : Int, _ day : Int) -> Date?
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let newDay = day == -1 ? maxDaysOfMonth(month,year) : day
return dateFormatter.date(from: "\(year)-\(month)-\(newDay)")
}
//
// Return a Date object based on the given year,month.day and offset days
// the offset can be a positive or negative number
//
func composeOffsetDate(_ year : Int, _ month : Int,
_ day : Int, _ offset : Int) -> Date?
{
var newDay = day + offset
if newDay > maxDaysOfMonth(month,year) {
newDay -= maxDaysOfMonth(month,year)
let newMonth = month + 1
if newMonth > 12 {
return composeDate(year+1,1,newDay)
}
return composeDate(year,newMonth,newDay)
}
else if newDay <= 0 {
var newYear = year
var newMonth = month - 1
if newMonth == 0 {
newMonth = 12
newYear -= 1
}
newDay = maxDaysOfMonth(newMonth,newYear) + newDay
return composeDate(newYear,newMonth,newDay)
}
return composeDate(year,month,newDay)
}
//
// -------------------------------------------------------------------------
// Utility functions to compose weekly and monthly walking speed data
// from the daily walking speed data
//
//
// Add a dummy data record for weekly and monthly charts
//
private func addPlaceholderData(_ year : Int, _ month : Int,
_ day : Int, _ offset : Int,
_ dataValues : inout [HealthDataTypeValue])
{
if (month >= 1 && month <= 12) {
if let date = composeDate(year,month,day),
let endDate = offset == -1 ? composeDate(year,month,-1) : composeOffsetDate(year,month,day,offset)
{
dataValues.append( HealthDataTypeValue(startDate:date, endDate:endDate,value:0.0))
}
}
}
//
// Check a data is in the weekly range of any bucket, and update value
//
private func findAddItemValue(_ data : HealthDataTypeValue,_ dataValues : inout [HealthDataValueTemp]) -> Bool
{
for (pos,item) in dataValues.enumerated().reversed() {
if data.startDate >= item.startDate &&
data.startDate <= item.endDate
{
dataValues[pos].valueSum.0 += data.value
dataValues[pos].valueSum.1 += 1
return true
}
}
return false
}
//
// Translate daily walking speed data to weekly walking speed data
//
func xlateWeeklyDataValues(_ rawData : [HealthDataTypeValue]) -> [HealthDataTypeValue]
{
var dataValues = [HealthDataTypeValue]()
var tmpValues = [HealthDataValueTemp]()
let calendar: Calendar = .current
rawData.forEach {
if !findAddItemValue($0,&tmpValues) {
// create a new bucket for a calendar week
let (year,month,day) = extractDate($0.startDate)
let weekday = calendar.component(.weekday, from: $0.startDate)
var firstWeekDate = composeOffsetDate(year,month,day,-weekday+1)
if firstWeekDate == nil {
print("**** Got firstWeekDate failed!")
firstWeekDate = $0.startDate
}
let lastWeekDate = composeOffsetDate(year,month,day,7-weekday)!
let data = HealthDataValueTemp(startDate: firstWeekDate!, endDate: lastWeekDate, valueSum: ($0.value,1) )
tmpValues.append(data)
}
}
tmpValues.forEach {
let dataVal = HealthDataTypeValue( startDate: $0.startDate,
endDate: $0.endDate,
value: $0.valueSum.0 / Double($0.valueSum.1)
)
dataValues.append(dataVal)
}
// Optional: make the chart looks pretty
if !dataValues.isEmpty && dataValues.count <= 2 {
dataValues.sort{ $0.startDate < $1.startDate }
// add a dummy week at the start of list
var placeholder = [HealthDataTypeValue]()
let (year,month,day) = extractDate(dataValues.first!.startDate)
addPlaceholderData(year,month,day-7,6,&placeholder)
dataValues = placeholder + dataValues
// add a dummy week at the end of list
let (year2,month2,day2) = extractDate(dataValues.last!.endDate)
addPlaceholderData(year2,month2,day2+1,6,&dataValues)
}
return dataValues
}
//
// Create a date range time stamp for all charts
//
func getChartTimeStamp(_ dataValues : [HealthDataTypeValue]) -> String?
{
var startDate, endDate : Date?
dataValues.forEach {
if $0.value > 0.0 {
if startDate == nil {
startDate = $0.startDate
}
endDate = $0.endDate
}
}
if startDate != nil && endDate != nil {
let (year,month,day) = extractDate(startDate!)
let (year2,month2,day2) = extractDate(endDate!)
return monthTitles[month-1] + " \(day)" +
(year == year2 ? "" : ", \(year)") + " - " +
(month == month2 && year == year2 ? "" : monthTitles[month2-1] + " ") + "\(day2), \(year)"
}
return nil
}
//
// Translate daily walking speed data to monthly walking speed data
//
func xlateMonthlyDataValues(_ rawData : [HealthDataTypeValue]) ->
[HealthDataTypeValue]
{
var dataValues = [HealthDataTypeValue]()
var xlateMap = [String:(Double,Int)]()
rawData.forEach {
let (year,month,_) = extractDate($0.startDate)
let key = "\(year)-\(month)"
if let (value,sum) = xlateMap[key] {
xlateMap[key] = (value + $0.value, sum + 1)
}
else {
xlateMap[key] = ($0.value, 1)
}
}
for (key,sum) in xlateMap {
let timeStamp = key.components(separatedBy: "-")
if let year = Int(timeStamp[0]),
let month = Int(timeStamp[1])
{
let startDate = composeDate(year,month,1)
let endDate = composeDate(year,month,-1)
let data = HealthDataTypeValue(startDate:startDate!, endDate:endDate!,value:sum.0/Double(sum.1))
dataValues.append(data)
}
}
// HashMap is not sorted
dataValues.sort { $0.startDate < $1.startDate }
// Optional: add dummy month records before and after to make
// the chart looks pretty
if (dataValues.count <= 2) {
var tmp = [HealthDataTypeValue]()
let (year,month,_) = extractDate(dataValues.first!.startDate)
addPlaceholderData(year,month-1,1,-1,&tmp)
tmp += dataValues
let (year2,month2,_) = extractDate(dataValues.last!.endDate)
addPlaceholderData(year2,month2+1,1,-1,&tmp)
return tmp
}
return dataValues
}
//
// -------------------------------------------------------------------------
//
// Compute the nearest value higher than the given target value
//
func computeMaxValue(_ targetValue : Double) -> CGFloat
{
CGFloat(Double(((Int(targetValue * 100.0) / 25) + 1)) * 0.25)
}
| 30.303514 | 117 | 0.563838 |
9195090f2666be8e7441305db4c0c062595e0806 | 6,497 | //
// BRHTTPServerTests.swift
// ravenwallet
//
// Created by Samuel Sutch on 12/7/16.
// Copyright © 2018 Ravenwallet Team. All rights reserved.
//
import XCTest
@testable import Ravencoin
class BRHTTPServerTests: XCTestCase {
var server: BRHTTPServer!
var bundle1Url: URL?
var bundle1Data: Data?
override func setUp() {
super.setUp()
let fm = FileManager.default
let documentsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
// download test files
func download(_ urlStr: String, resultingUrl: inout URL?, resultingData: inout Data?) {
let url = URL(string: urlStr)!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
if fm.fileExists(atPath: destinationUrl.path) {
print("file already exists [\(destinationUrl.path)]")
resultingData = try? Data(contentsOf: destinationUrl)
resultingUrl = destinationUrl
} else if let dataFromURL = try? Data(contentsOf: url){
if (try? dataFromURL.write(to: destinationUrl, options: [.atomic])) != nil {
print("file saved [\(destinationUrl.path)]")
resultingData = dataFromURL
resultingUrl = destinationUrl
} else {
XCTFail("error saving file")
}
} else {
XCTFail("error downloading file")
}
}
download("https://s3.amazonaws.com/breadwallet-assets/bread-buy/bundle.tar",
resultingUrl: &bundle1Url, resultingData: &bundle1Data)
server = BRHTTPServer()
server.prependMiddleware(middleware: BRHTTPFileMiddleware(baseURL: documentsUrl))
do {
try server.start()
} catch let e {
XCTFail("could not start server \(e)")
}
}
override func tearDown() {
super.tearDown()
server.stop()
server = nil
}
func testDownloadFile() {
let exp = expectation(description: "load")
let url = URL(string: "http://localhost:\(server.port)/bundle.tar")!
let req = URLRequest(url: url)
URLSession.shared.dataTask(with: req, completionHandler: { (data, resp, error) -> Void in
NSLog("error: \(String(describing: error))")
let httpResp = resp as! HTTPURLResponse
NSLog("status: \(httpResp.statusCode)")
NSLog("headers: \(httpResp.allHeaderFields)")
XCTAssert(data! == self.bundle1Data!, "data should be equal to that stored on disk")
exp.fulfill()
}) .resume()
waitForExpectations(timeout: 5.0) { (err) -> Void in
if err != nil {
NSLog("timeout error \(String(describing: err))")
}
}
}
}
class BRTestHTTPRequest: BRHTTPRequest {
var fd: Int32 = 0
var method: String = "GET"
var path: String = "/"
var queryString: String = ""
var query: [String: [String]] = [String: [String]]()
var headers: [String: [String]] = [String: [String]]()
var isKeepAlive: Bool = false
var hasBody: Bool = false
var contentType: String = "application/octet-stream"
var contentLength: Int = 0
var queue: DispatchQueue = DispatchQueue.main
var start = Date()
init(m: String, p: String) {
method = m
path = p
}
func body() -> Data? {
return nil
}
func json() -> AnyObject? {
return nil
}
}
class BRHTTPRouteTests: XCTestCase {
func testRouteMatching() {
var m: BRHTTPRouteMatch!
// simple
var x = BRHTTPRoutePair(method: "GET", path: "/hello")
if (x.match(BRTestHTTPRequest(m: "GET", p: "/hello")) == nil) { XCTFail() }
// trailing strash stripping
if (x.match(BRTestHTTPRequest(m: "GET", p: "/hello/")) == nil) { XCTFail() }
// simple multi-component
x = BRHTTPRoutePair(method: "GET", path: "/hello/foo")
if (x.match(BRTestHTTPRequest(m: "GET", p: "/hello/foo")) == nil) { XCTFail() }
// should fail
x = BRHTTPRoutePair(method: "GET", path: "/hello/soo")
if (x.match(BRTestHTTPRequest(m: "GET", p: "/hello")) != nil) { XCTFail() }
if (x.match(BRTestHTTPRequest(m: "GET", p: "/hello/loo")) != nil) { XCTFail() }
if (x.match(BRTestHTTPRequest(m: "GET", p: "/hello/loo")) != nil) { XCTFail() }
// single capture
x = BRHTTPRoutePair(method: "GET", path: "/(omg)")
m = x.match(BRTestHTTPRequest(m: "GET", p: "/lol"))
if m == nil { XCTFail() }
if m["omg"]![0] != "lol" { XCTFail() }
// single capture multi-component
x = BRHTTPRoutePair(method: "GET", path: "/omg/(omg)/omg/")
m = x.match(BRTestHTTPRequest(m: "GET", p: "/omg/lol/omg/"))
if m == nil { XCTFail() }
if m["omg"]![0] != "lol" { XCTFail() }
// multi-same-capture multi-component
x = BRHTTPRoutePair(method: "GET", path: "/(omg)/(omg)/omg")
m = x.match(BRTestHTTPRequest(m: "GET", p: "/omg/lol/omg/"))
if m == nil { XCTFail() }
if m["omg"]![0] != "omg" { XCTFail() }
if m["omg"]![1] != "lol" { XCTFail() }
// multi-capture multi-component
x = BRHTTPRoutePair(method: "GET", path: "/(lol)/(omg)")
m = x.match(BRTestHTTPRequest(m: "GET", p: "/lol/omg"))
if m == nil { return XCTFail() }
if m["lol"]![0] != "lol" { XCTFail() }
if m["omg"]![0] != "omg" { XCTFail() }
// wildcard
x = BRHTTPRoutePair(method: "GET", path: "/api/(rest*)")
m = x.match(BRTestHTTPRequest(m: "GET", p: "/api/p1/p2/p3"))
if m == nil { XCTFail() }
if m["rest"]![0] != "p1/p2/p3" { XCTFail() }
}
func testRouter() {
let router = BRHTTPRouter()
router.get("/hello") { (request, match) -> BRHTTPResponse in
return BRHTTPResponse(request: request, code: 500)
}
let exp = expectation(description: "handle func")
router.handle(BRTestHTTPRequest(m: "GET", p: "/hello")) { (resp) -> Void in
if resp.response?.statusCode != 500 { XCTFail() }
exp.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
}
| 36.5 | 97 | 0.543328 |
de18da046a98b63161ba76cd74384ef33b89b8ab | 5,984 | import Foundation
@testable import ProjectDescription
extension Config {
public static func test(
generationOptions: Config.GenerationOptions = .options(),
plugins: [PluginLocation] = []
) -> Config {
Config(plugins: plugins, generationOptions: generationOptions)
}
}
extension Template {
public static func test(
description: String = "Template",
attributes: [Attribute] = [],
items: [Template.Item] = []
) -> Template {
Template(
description: description,
attributes: attributes,
items: items
)
}
}
extension Workspace {
public static func test(
name: String = "Workspace",
projects: [Path] = [],
schemes: [Scheme] = [],
additionalFiles: [FileElement] = []
) -> Workspace {
Workspace(
name: name,
projects: projects,
schemes: schemes,
additionalFiles: additionalFiles
)
}
}
extension Project {
public static func test(
name: String = "Project",
organizationName: String? = nil,
settings: Settings? = nil,
targets: [Target] = [],
additionalFiles: [FileElement] = []
) -> Project {
Project(
name: name,
organizationName: organizationName,
settings: settings,
targets: targets,
additionalFiles: additionalFiles
)
}
}
extension Target {
public static func test(
name: String = "Target",
platform: Platform = .iOS,
product: Product = .framework,
productName: String? = nil,
bundleId: String = "com.some.bundle.id",
infoPlist: InfoPlist = .file(path: "Info.plist"),
sources: SourceFilesList = "Sources/**",
resources: ResourceFileElements = "Resources/**",
headers: Headers? = nil,
entitlements: Path? = Path("app.entitlements"),
scripts: [TargetScript] = [],
dependencies: [TargetDependency] = [],
settings: Settings? = nil,
coreDataModels: [CoreDataModel] = [],
environment: [String: String] = [:]
) -> Target {
Target(
name: name,
platform: platform,
product: product,
productName: productName,
bundleId: bundleId,
infoPlist: infoPlist,
sources: sources,
resources: resources,
headers: headers,
entitlements: entitlements,
scripts: scripts,
dependencies: dependencies,
settings: settings,
coreDataModels: coreDataModels,
environment: environment
)
}
}
extension TargetScript {
public static func test(
name: String = "Action",
tool: String = "",
order: Order = .pre,
arguments: [String] = [],
inputPaths: [Path] = [],
inputFileListPaths: [Path] = [],
outputPaths: [Path] = [],
outputFileListPaths: [Path] = []
) -> TargetScript {
TargetScript(
name: name,
script: .tool(path: tool, args: arguments),
order: order,
inputPaths: inputPaths,
inputFileListPaths: inputFileListPaths,
outputPaths: outputPaths,
outputFileListPaths: outputFileListPaths
)
}
}
extension Scheme {
public static func test(
name: String = "Scheme",
shared: Bool = false,
buildAction: BuildAction? = nil,
testAction: TestAction? = nil,
runAction: RunAction? = nil
) -> Scheme {
Scheme(
name: name,
shared: shared,
buildAction: buildAction,
testAction: testAction,
runAction: runAction
)
}
}
extension BuildAction {
public static func test(targets: [TargetReference] = []) -> BuildAction {
BuildAction(
targets: targets,
preActions: [ExecutionAction.test()],
postActions: [ExecutionAction.test()]
)
}
}
extension TestAction {
public static func test(
targets: [TestableTarget] = [],
arguments: Arguments? = nil,
configuration: ConfigurationName = .debug,
coverage: Bool = true
) -> TestAction {
TestAction.targets(
targets,
arguments: arguments,
configuration: configuration,
preActions: [ExecutionAction.test()],
postActions: [ExecutionAction.test()],
options: .options(coverage: coverage)
)
}
}
extension RunAction {
public static func test(
configuration: ConfigurationName = .debug,
executable: TargetReference? = nil,
arguments: Arguments? = nil
) -> RunAction {
RunAction(
configuration: configuration,
executable: executable,
arguments: arguments
)
}
}
extension ExecutionAction {
public static func test(
title: String = "Test Script",
scriptText: String = "echo Test",
target: TargetReference? = TargetReference(projectPath: nil, target: "Target")
) -> ExecutionAction {
ExecutionAction(
title: title,
scriptText: scriptText,
target: target
)
}
}
extension Arguments {
public static func test(
environment: [String: String] = [:],
launchArguments: [LaunchArgument] = []
) -> Arguments {
Arguments(
environment: environment,
launchArguments: launchArguments
)
}
}
extension Dependencies {
public static func test(carthageDependencies: CarthageDependencies? = nil) -> Dependencies {
Dependencies(carthage: carthageDependencies)
}
}
extension Plugin {
public static func test(name: String = "Plugin") -> Plugin {
Plugin(name: name)
}
}
| 27.324201 | 96 | 0.559492 |
117a958bdbe90515391c07ea69ef1ffbfd222ef4 | 4,368 |
//
// ShadeCap.swift
//
// Generated on 20/09/18
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import RxSwift
import PromiseKit
// MARK: Constants
extension Constants {
public static var shadeNamespace: String = "shade"
public static var shadeName: String = "Shade"
}
// MARK: Attributes
fileprivate struct Attributes {
static let shadeLevel: String = "shade:level"
static let shadeShadestate: String = "shade:shadestate"
static let shadeLevelchanged: String = "shade:levelchanged"
}
public protocol ArcusShadeCapability: class, RxArcusService {
/** The percentage that the shades are open (raised/lowered). May also be used to set how closed (lowered) or open (raised) the shade is where 100% is fully open and 0% is fully closed. For devices that only support being set fully Open (Raised) or Closed (Lowered), use 0% for Closed (Lowered) and 100% for Open (Raised). */
func getShadeLevel(_ model: DeviceModel) -> Int?
/** The percentage that the shades are open (raised/lowered). May also be used to set how closed (lowered) or open (raised) the shade is where 100% is fully open and 0% is fully closed. For devices that only support being set fully Open (Raised) or Closed (Lowered), use 0% for Closed (Lowered) and 100% for Open (Raised). */
func setShadeLevel(_ level: Int, model: DeviceModel)
/** Reflects the current state of the shade. Obstruction implying that something is preventing the opening or closing of the shade. */
func getShadeShadestate(_ model: DeviceModel) -> ShadeShadestate?
/** UTC time of last level change. */
func getShadeLevelchanged(_ model: DeviceModel) -> Date?
/** Move the shade to a pre-programmed OPEN position. */
func requestShadeGoToOpen(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent>/** Move the shade to a pre-programmed CLOSED position. */
func requestShadeGoToClosed(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent>/** Move the shade to a pre-programmed FAVORITE position. */
func requestShadeGoToFavorite(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent>
}
extension ArcusShadeCapability {
public func getShadeLevel(_ model: DeviceModel) -> Int? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.shadeLevel] as? Int
}
public func setShadeLevel(_ level: Int, model: DeviceModel) {
model.set([Attributes.shadeLevel: level as AnyObject])
}
public func getShadeShadestate(_ model: DeviceModel) -> ShadeShadestate? {
let attributes: [String: AnyObject] = model.get()
guard let attribute = attributes[Attributes.shadeShadestate] as? String,
let enumAttr: ShadeShadestate = ShadeShadestate(rawValue: attribute) else { return nil }
return enumAttr
}
public func getShadeLevelchanged(_ model: DeviceModel) -> Date? {
let attributes: [String: AnyObject] = model.get()
if let timestamp = attributes[Attributes.shadeLevelchanged] as? Double {
return Date(milliseconds: timestamp)
}
return nil
}
public func requestShadeGoToOpen(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent> {
let request: ShadeGoToOpenRequest = ShadeGoToOpenRequest()
request.source = model.address
return try sendRequest(request)
}
public func requestShadeGoToClosed(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent> {
let request: ShadeGoToClosedRequest = ShadeGoToClosedRequest()
request.source = model.address
return try sendRequest(request)
}
public func requestShadeGoToFavorite(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent> {
let request: ShadeGoToFavoriteRequest = ShadeGoToFavoriteRequest()
request.source = model.address
return try sendRequest(request)
}
}
| 40.444444 | 327 | 0.736951 |
e5a58c3fd000e94306851ca8464bb3564695af5a | 332 | //
// Complete.swift
// Mczo Download
//
// Created by Wirspe on 2019/11/22.
// Copyright © 2019 Wirspe. All rights reserved.
//
import Foundation
import CoreData
import Combine
public class ModelComplete: CoreDataDownload, Managed, Identifiable {
@NSManaged public var size: Int64
@NSManaged public var ext: String
}
| 19.529412 | 69 | 0.728916 |
e5deb8b1570a41c4a88b216e3c1080232ae94ff4 | 4,389 | //
// NewsFeed.swift
//
//
// Created by macosx on 20.06.17.
//
//
import UIKit
class NewsFeed: UIViewController {
//Mark: IBOutlets
@IBOutlet weak var topBar: UIView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var tableView: UITableView!
fileprivate let identifier_table = "xxTableCellxx"
fileprivate let identifier_collection = "xxCollectionCellxx"
// MARK: - Data Object
fileprivate lazy var dataObject = [UserObject]()
// MARK: - View LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
fetchInformation() // fetch information
}
// This function will call HTTPWorker which i have created in Core folder
// after http worker will give us some result we should make action using it
private func fetchInformation () {
DispatchQueue.global(qos: .userInitiated).async {
let worker = HttpWorker()
worker.fetchUserInformationFromRemoteServer { [weak self] (object) in
if object != nil {
self?.dataObject = object!
self?.dataSourceAndDelegation(with: true) // we have objects so lets init tableView and CollectionView
} else {
self?.dataSourceAndDelegation(with: false) // we do not have any object so lets deAlloc Table and Collection
}
}
}
}
// MARK: - Assign TableView Delegates
private func dataSourceAndDelegation (with status: Bool) {
DispatchQueue.main.async { [weak self] in
if status {
self?.tableView.delegate = self
self?.tableView.dataSource = self
self?.collectionView.delegate = self
self?.collectionView.dataSource = self
} else {
self?.tableView.delegate = nil
self?.tableView.dataSource = nil
self?.collectionView.delegate = nil
self?.collectionView.dataSource = nil
}
self?.collectionView.reloadData()
self?.tableView.reloadData()
}
}
}
// MARK: - UICollectionViewDelegate & UICollectionViewDataSource
extension NewsFeed: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataObject.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier_collection, for: indexPath) as? NewsCollCell else {
fatalError("Could not dequeue cell with identifier xxCollectionCellxx")
}
let object = self.dataObject[indexPath.item]
// assign avatar
let url = URL(string: object.img) // cast string to url
cell.avatar.sd_setImage(with: url)
cell.userName.text = object.userName
return cell
}
}
// MARK: - UITableViewDelegate & UITableViewDataSource
extension NewsFeed: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataObject.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: identifier_table, for: indexPath) as? NewsTableCell else {
fatalError("Could not dequeue cell with identifier xxxNewsFeedTabCell")
}
cell.tag = indexPath.row
let object = self.dataObject[indexPath.row]
if cell.tag == indexPath.row { // trick to disable redraw for incorrect cells
// assign avatar
let url = URL(string: object.img)
cell.avatar.sd_setImage(with: url)
cell.userImage.sd_setImage(with: url)
cell.name.text = object.userName
cell.like.text = object.likes + " likes"
cell.views.text = "View all \(object.views!) comments"
}
return cell
}
}
| 36.272727 | 143 | 0.624516 |
dde92a51f847e65ba028271eac357bcc352211f9 | 293 | //
// Array+Extension.swift
// Wallshapes
//
// Created by Bruna Baudel on 3/1/21.
//
import Foundation
extension Array where Element: Equatable {
mutating func remove(object: Element) {
guard let index = firstIndex(of: object) else {return}
remove(at: index)
}
}
| 18.3125 | 62 | 0.651877 |
239f43cc6a11ad070eb7598f22d884115adc55fc | 2,254 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* 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
/**
Configuration object to setup an OAuth1a module
*/
public class OAuth1Config {
/**
Applies the baseURL to the configuration.
*/
public let baseURL: String
/**
Applies the "callback URL" once request token issued.
*/
public let redirectURL: String
/**
Applies the "initial request token endpoint" to the request token.
*/
public var requestTokenEndpoint: String
/**
Applies the "authorization endpoint" to the request token.
*/
public var authorizeEndpoint: String
/**
Applies the "access token endpoint" to the exchange code for access token.
*/
public var accessTokenEndpoint: String
/**
Applies the "client id" obtained with the client registration process.
*/
public let clientId: String
/**
Applies the "client secret" obtained with the client registration process.
*/
public let clientSecret: String
public let accountId: String?
public init(accountId:String, base: String,
requestTokenEndpoint: String,
authorizeEndpoint: String,
accessTokenEndpoint: String,
redirectURL: String,
clientId: String,
clientSecret: String) {
self.accountId = accountId
self.baseURL = base
self.requestTokenEndpoint = requestTokenEndpoint
self.authorizeEndpoint = authorizeEndpoint
self.redirectURL = redirectURL
self.accessTokenEndpoint = accessTokenEndpoint
self.clientId = clientId
self.clientSecret = clientSecret
}
} | 29.272727 | 78 | 0.686779 |
ac7867ded2b1033dc78266f494ade3fb971d345b | 4,312 | //
// BoidRenderer.swift
// GraphicsHub
//
// Created by Noah Pikielny on 7/16/21.
//
import MetalKit
class BoidRenderer: RayMarchingRenderer {
private var boidCount: Int
private var boidBuffer: MTLBuffer!
private var previousBuffer: MTLBuffer!
private var boidComputePipeline: MTLComputePipelineState!
required init(device: MTLDevice, size: CGSize) {
var boids = [Boid]()
boidCount = 25
for _ in 0..<boidCount {
boids.append(Boid(heading: SIMD3<Float>(Float.random(in: -0.5...0.5), Float.random(in: -0.5...0.5), Float.random(in: -0.5...0.5)) * 4,
position: SIMD3<Float>(Float.random(in: -0.5...0.5), Float.random(in: -0.5...0.5), Float.random(in: -0.5...0.5)) * 100))
}
boidBuffer = device.makeBuffer(bytes: boids, length: MemoryLayout<Boid>.stride * boidCount, options: .storageModeManaged)
previousBuffer = device.makeBuffer(length: MemoryLayout<Boid>.stride * boidCount, options: .storageModePrivate)
let coneAngle: Float = Float.pi / 3
super.init(device: device,
size: size,
objects: boids.map {
Object.cone(materialType: .solid, point: $0.position, size: SIMD3<Float>(cos(coneAngle), sin(coneAngle), 3), rotation: SIMD3<Float>(Float.random(in: 0...Float.pi * 2), Float.random(in: 0...Float.pi * 2), Float.random(in: 0...Float.pi * 2)))
},
inputManager: BoidInputManager(renderSpecificInputs: [], imageSize: size))
name = "Boids Renderer"
let function = createFunctions("boid")
if let boidFunction = function {
do {
boidComputePipeline = try device.makeComputePipelineState(function: boidFunction)
} catch {
print(error)
fatalError()
}
}
}
override func draw(commandBuffer: MTLCommandBuffer, view: MTKView) {
let inputManager = inputManager as! BoidInputManager
let copyEncoder = commandBuffer.makeBlitCommandEncoder()
copyEncoder?.copy(from: boidBuffer, sourceOffset: 0, to: previousBuffer, destinationOffset: 0, size: boidBuffer.length)
copyEncoder?.endEncoding()
for _ in 0..<inputManager.framesPerFrame {
let boidEncoder = commandBuffer.makeComputeCommandEncoder()
boidEncoder?.setComputePipelineState(boidComputePipeline)
boidEncoder?.setBuffer(previousBuffer, offset: 0, index: 0)
boidEncoder?.setBuffer(boidBuffer, offset: 0, index: 1)
boidEncoder?.setBuffer(objectBuffer, offset: 0, index: 2)
boidEncoder?.setBytes([Int32(boidCount)], length: MemoryLayout<Int32>.stride, index: 3)
boidEncoder?.setBytes([inputManager.perceptionDistance], length: MemoryLayout<Float>.stride, index: 4)
boidEncoder?.setBytes([inputManager.perceptionAngle], length: MemoryLayout<Float>.stride, index: 5)
boidEncoder?.setBytes([inputManager.step], length: MemoryLayout<Float>.stride, index: 6)
boidEncoder?.dispatchThreadgroups(MTLSize(width: (boidCount + 7) / 8, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 8, height: 1, depth: 1))
boidEncoder?.endEncoding()
}
super.draw(commandBuffer: commandBuffer, view: view)
}
struct Boid {
var heading: SIMD3<Float>
var position: SIMD3<Float>
}
}
class BoidInputManager: RealTimeRayMarchingInputManager {
var perceptionDistance: Float { Float((getInput(16) as! SliderInput).output) }
var perceptionAngle: Float { Float((getInput(17) as! SliderInput).output) }
var step: Float { Float((getInput(18) as! SliderInput).output) }
override init(renderSpecificInputs: [NSView], imageSize: CGSize?) {
let perceptionDistance = SliderInput(name: "Perception", minValue: 1, currentValue: 5, maxValue: 10)
let perceptionAngle = SliderInput(name: "Angle", minValue: 0, currentValue: 1, maxValue: 3)
let step = SliderInput(name: "Step Size", minValue: 0, currentValue: 0, maxValue: 10)
super.init(renderSpecificInputs: [perceptionDistance, perceptionAngle, step] + renderSpecificInputs, imageSize: imageSize)
}
}
| 49.563218 | 260 | 0.64564 |
9b3e9678e8b80986014dd17469fe1b8cbcc80516 | 6,438 | //
// Observable+Creation.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func create<E>(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- returns: An observable sequence with no elements.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func empty<E>() -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- returns: An observable sequence whose observers will never get called.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func never<E>() -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func just<E>(element: E) -> Observable<E> {
return Just(element: element)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sequenceOf<E>(elements: E ...) -> Observable<E> {
return AnonymousObservable { observer in
for element in elements {
observer.on(.Next(element))
}
observer.on(.Completed)
return NopDisposable.instance
}
}
extension SequenceType {
/**
Converts a sequence to an observable sequence.
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func asObservable() -> Observable<Generator.Element> {
return AnonymousObservable { observer in
for element in self {
observer.on(.Next(element))
}
observer.on(.Completed)
return NopDisposable.instance
}
}
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- returns: The observable sequence that terminates with specified error.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func failWith<E>(error: ErrorType) -> Observable<E> {
return FailWith(error: error)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func deferred<E>(observableFactory: () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func generate<E>(initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func range(start: Int, _ count: Int, _ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Int> {
return RangeProducer<Int>(start: start, count: count, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func repeatElement<E>(element: E, _ scheduler: ImmediateSchedulerType) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func using<S, R: Disposable>(resourceFactory: () throws -> R, observableFactory: R throws -> Observable<S>) -> Observable<S> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
| 36.372881 | 181 | 0.745263 |
ef6383004b2852bd47badb197b18ab662c2b2347 | 866 | //
// LowPowerModeSwitch.swift
// OnlySwitch
//
// Created by Jacklandrin on 2022/1/1.
//
import Foundation
class LowPowerModeSwitch:SwitchProvider {
var type: SwitchType = .lowpowerMode
weak var delegate: SwitchDelegate?
func currentStatus() -> Bool {
let result = LowpowerModeCMD.status.runAppleScript(isShellCMD: true)
let content = result.1 as! String
return content.contains("1")
}
func currentInfo() -> String {
return "require password"
}
func operationSwitch(isOn: Bool) async -> Bool {
if isOn {
return LowpowerModeCMD.on.runAppleScript(isShellCMD: true, with: true).0
} else {
return LowpowerModeCMD.off.runAppleScript(isShellCMD: true, with: true).0
}
}
func isVisable() -> Bool {
return true
}
}
| 23.405405 | 85 | 0.616628 |
565c427deae782722a59385c111fc0e0770e4ec3 | 2,180 | //
// AppDelegate.swift
// Keyboard+Toolbar
//
// Created by KoKang Chu on 2017/6/22.
// Copyright © 2017年 KoKang Chu. All rights reserved.
//
import UIKit
@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:.
}
}
| 46.382979 | 285 | 0.755505 |
20b62a1d0651d420c26d839289d4ed372c8bf404 | 312 | //
// Constants.swift
// CustomLoginDemo
//
// Created by Tomas Sanislo on 30/07/2019.
// Copyright © 2019 Tomas Sanislo. All rights reserved.
//
import Foundation
struct Constants {
struct Storyboard {
static let homeViewController = "HomeVC"
static let viewController = "VC"
}
}
| 18.352941 | 56 | 0.663462 |
d931fa0f4acb5656439663ba3d46ba348211cfa3 | 6,017 | //
// UIScrollViewExtension-XW.swift
// XWRefresh
//
// Created by Xiong Wei on 15/9/9.
// Copyright © 2015年 Xiong Wei. All rights reserved.
// 简书:猫爪
import UIKit
private var XWRefreshHeaderKey:Void?
private var XWRefreshFooterKey:Void?
private var XWRefreshReloadDataClosureKey:Void?
typealias xwClosureParamCountType = (Int)->Void
public class xwReloadDataClosureInClass {
var reloadDataClosure:xwClosureParamCountType = { (Int)->Void in }
}
//用于加强一个引用
//var xwRetainClosureClass = xwReloadDataClosureInClass()
public extension UIScrollView {
/** ===========================================================================================
1.2 version
===============================================================================================*/
//MARK: 1.2 version
/** reloadDataClosure */
var reloadDataClosureClass:xwReloadDataClosureInClass {
set{
self.willChangeValueForKey("reloadDataClosure")
//因为闭包不属于class 所以不合适 AnyObject
objc_setAssociatedObject(self, &XWRefreshReloadDataClosureKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
self.didChangeValueForKey("reloadDataClosure")
}
get{
if let realClosure = objc_getAssociatedObject(self, &XWRefreshReloadDataClosureKey) {
return realClosure as! xwReloadDataClosureInClass
}
return xwReloadDataClosureInClass()
}
}
/** 下拉刷新的控件 */
var headerView:XWRefreshHeader?{
set{
if self.headerView == newValue { return }
self.headerView?.removeFromSuperview()
objc_setAssociatedObject(self,&XWRefreshHeaderKey, newValue , objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
if let newHeaderView = newValue {
self.addSubview(newHeaderView)
}
}
get{
return objc_getAssociatedObject(self, &XWRefreshHeaderKey) as? XWRefreshHeader
}
}
/** 上拉刷新的控件 */
var footerView:XWRefreshFooter?{
set{
if self.footerView == newValue { return }
self.footerView?.removeFromSuperview()
objc_setAssociatedObject(self,&XWRefreshFooterKey, newValue , objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
if let newFooterView = newValue {
self.addSubview(newFooterView)
}
}
get{
return objc_getAssociatedObject(self, &XWRefreshFooterKey) as? XWRefreshFooter
}
}
var totalDataCount:Int{
get{
var totalCount:Int = 0
if self.isKindOfClass(UITableView){
let tableView = self as! UITableView
for var section = 0 ; section < tableView.numberOfSections ; ++section {
totalCount += tableView.numberOfRowsInSection(section)
}
}else if self.isKindOfClass(UICollectionView) {
let collectionView = self as! UICollectionView
for var section = 0 ; section < collectionView.numberOfSections() ; ++section {
totalCount += collectionView.numberOfItemsInSection(section)
}
}
return totalCount
}
}
func executeReloadDataClosure(){
self.reloadDataClosureClass.reloadDataClosure(self.totalDataCount)
}
/** ===========================================================================================
1.0 version deprecated
===============================================================================================*/
//MARK: 1.0 version
@available(*, deprecated=1.0, message="Use -self.tableView.headerView = XWRefreshNormalHeader(target: self, action: Selector ) instead.")
/**
添加上拉刷新回调
- parameter callBack: 闭包代码块,当心循环引用 使用 [weak self]
*/
func addHeaderWithCallback(callBack:Void->()){
self.headerView = XWRefreshNormalHeader(ComponentRefreshingClosure: callBack)
}
@available(*, deprecated=1.0, message="Use -self.tableView.footerView = XWRefreshAutoNormalFooter(target: self, action: Selector) instead.")
/** 添加下拉刷新回调,当心循环引用 使用 [weak self] */
func addFooterWithCallback(callBack:Void->()){
self.footerView = XWRefreshAutoNormalFooter(ComponentRefreshingClosure: callBack)
}
@available(*, deprecated=1.0, message="Use -self.tableView.headerView?.beginRefreshing() instead.")
/** 开始headerView刷新 */
func beginHeaderRefreshing(){
if let real = self.headerView {
real.beginRefreshing()
}
}
@available(*, deprecated=1.0, message="Use -self.tableView.headerView?.endRefreshing() instead.")
/** 停止headerView刷新 */
func endHeaderRefreshing(){
if let real = self.headerView {
real.endRefreshing()
}
}
@available(*, deprecated=1.0, message="Use -self.tableView.footerView?.beginRefreshing() instead.")
/** 开始footerView刷新 */
func beginFooterRefreshing(){
if let real = self.footerView {
real.beginRefreshing()
}
}
@available(*, deprecated=1.0, message="Use -self.tableView.footerView?.endRefreshing() instead.")
/** 停止footerView刷新 */
func endFooterRefreshing(){
if let real = self.footerView {
real.endRefreshing()
}
}
}
extension UITableView {
public override class func initialize(){
if self != UITableView.self { return }
struct once{
static var onceTaken:dispatch_once_t = 0
}
dispatch_once(&once.onceTaken) { () -> Void in
self.exchangeInstanceMethod1(Selector("reloadData"), method2: Selector("xwReloadData"))
}
}
func xwReloadData(){
//正因为交换了方法,所以这里其实是执行的系统自己的 reloadData 方法
self.xwReloadData()
self.executeReloadDataClosure()
}
}
| 26.742222 | 144 | 0.584012 |
d77fe4351b24177d3737d7ec25d2d177ebfc9529 | 609 | //: Playground - noun: a place where people can play
import UIKit
extension Collection {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
var arr: [Int] = [1, 2, 3, 4, 5, 7, 8, 9, 10]
func element(at index: Int) -> Int {
if let elem = arr[safe: index] {
return elem
} else {
return -1
}
}
let index = element(at: 3) // returns '4'
let twelve = element(at: 12) // returns '-1'
let eight = element(at: 6) // returns '8'
| 23.423077 | 90 | 0.604269 |
28972f062dbf96cfae768cf3a1d582295c2c8895 | 2,920 | //
// ProjectSettingsViewController.swift
// FSNotes
//
// Created by Oleksandr Glushchenko on 11/23/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import Cocoa
import Carbon.HIToolbox
class ProjectSettingsViewController: NSViewController {
private var project: Project?
@IBOutlet weak var modificationDate: NSButton!
@IBOutlet weak var creationDate: NSButton!
@IBOutlet weak var titleButton: NSButton!
@IBOutlet weak var sortByGlobal: NSButton!
@IBOutlet weak var directionASC: NSButton!
@IBOutlet weak var directionDESC: NSButton!
@IBOutlet weak var showInAll: NSButton!
@IBOutlet weak var firstLineAsTitle: NSButton!
@IBAction func sortBy(_ sender: NSButton) {
guard let project = project else { return }
let sortBy = SortBy(rawValue: sender.identifier!.rawValue)!
if sortBy != .none {
project.sortBy = sortBy
}
project.sortBy = sortBy
project.saveSettings()
guard let vc = ViewController.shared() else { return }
vc.updateTable()
}
@IBAction func sortDirection(_ sender: NSButton) {
guard let project = project else { return }
project.sortDirection = SortDirection(rawValue: sender.identifier!.rawValue)!
project.saveSettings()
guard let vc = ViewController.shared() else { return }
vc.updateTable()
}
@IBAction func showNotesInMainList(_ sender: NSButton) {
project?.showInCommon = sender.state == .on
project?.saveSettings()
}
@IBAction func firstLineAsTitle(_ sender: NSButton) {
guard let project = self.project else { return }
project.firstLineAsTitle = sender.state == .on
project.saveSettings()
let notes = Storage.sharedInstance().getNotesBy(project: project)
for note in notes {
note.invalidateCache()
}
guard let vc = ViewController.shared() else { return }
vc.notesTableView.reloadData()
}
@IBAction func close(_ sender: Any) {
self.dismiss(nil)
}
override func keyDown(with event: NSEvent) {
if event.keyCode == kVK_Return || event.keyCode == kVK_Escape {
self.dismiss(nil)
}
}
public func load(project: Project) {
showInAll.state = project.showInCommon ? .on : .off
firstLineAsTitle.state = project.firstLineAsTitle ? .on : .off
modificationDate.state = project.sortBy == .modificationDate ? .on : .off
creationDate.state = project.sortBy == .creationDate ? .on : .off
titleButton.state = project.sortBy == .title ? .on : .off
sortByGlobal.state = project.sortBy == .none ? .on : .off
directionASC.state = project.sortDirection == .asc ? .on : .off
directionDESC.state = project.sortDirection == .desc ? .on : .off
self.project = project
}
}
| 29.795918 | 85 | 0.64589 |
8ffda8802b1eb9357311070baf19adfc93ef7562 | 2,802 | /*
* Copyright (c) scott.cgi All Rights Reserved.
*
* This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub.
* The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion.
*
* License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE
* GitHub : https://github.com/scottcgi/Mojoc
* CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md
*
* Since : 2017-3-13
* Update : 2019-2-21
* Author : scott.cgi
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
AApplication.Init()
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.
AApplication.Pause()
}
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.
AApplication.SaveData(nil)
}
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.
AApplication.Resume()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:
AApplication.SaveData(nil)
AApplication.Destroy()
}
}
| 44.47619 | 285 | 0.730193 |
75599531f1437a2ec4605d2c78ee7566bf8f2eba | 3,888 | import Foundation
public typealias CompletionHandler = () -> Void
/**
A cache consists of both in-memory and on-disk components, both of which can be reset.
*/
@objc(MBBimodalCache)
public protocol BimodalCache {
func clearMemory()
func clearDisk(completion: CompletionHandler?)
}
/**
A cache which supports storing images
*/
public protocol BimodalImageCache: BimodalCache {
func store(_ image: UIImage, forKey key: String, toDisk: Bool, completion completionBlock: CompletionHandler?)
func image(forKey: String?) -> UIImage?
}
/**
A cache which supports storing data
*/
public protocol BimodalDataCache: BimodalCache {
func store(_ data: Data, forKey key: String, toDisk: Bool, completion completionBlock: CompletionHandler?)
func data(forKey: String?) -> Data?
}
/**
A general purpose on-disk cache used by both the ImageCache and DataCache implementations
*/
internal class FileCache {
let diskCacheURL: URL = {
let fileManager = FileManager.default
let basePath = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
let identifier = Bundle.mapboxNavigation.bundleIdentifier!
return basePath.appendingPathComponent(identifier + ".downloadedFiles")
}()
let diskAccessQueue = DispatchQueue(label: Bundle.mapboxNavigation.bundleIdentifier! + ".diskAccess")
var fileManager: FileManager?
init() {
diskAccessQueue.sync {
fileManager = FileManager()
}
}
/**
Stores data in the file cache for the given key, and calls the completion handler when finished.
*/
public func store(_ data: Data, forKey key: String, completion: CompletionHandler?) {
guard let fileManager = fileManager else {
completion?()
return
}
diskAccessQueue.async {
self.createCacheDirIfNeeded(self.diskCacheURL, fileManager: fileManager)
let cacheURL = self.cacheURLWithKey(key)
do {
try data.write(to: cacheURL)
} catch {
NSLog("================> Failed to write data to URL \(cacheURL)")
}
completion?()
}
}
/**
Returns data from the file cache for the given key, if any.
*/
public func dataFromFileCache(forKey key: String?) -> Data? {
guard let key = key else {
return nil
}
do {
return try Data.init(contentsOf: cacheURLWithKey(key))
} catch {
return nil
}
}
/**
Clears the disk cache by removing and recreating the cache directory, and calls the completion handler when finished.
*/
public func clearDisk(completion: CompletionHandler?) {
guard let fileManager = fileManager else {
return
}
let cacheURL = self.diskCacheURL
self.diskAccessQueue.async {
do {
try fileManager.removeItem(at: cacheURL)
} catch {
NSLog("================> Failed to remove cache dir: \(cacheURL)")
}
self.createCacheDirIfNeeded(cacheURL, fileManager: fileManager)
completion?()
}
}
func cacheURLWithKey(_ key: String) -> URL {
let cacheKey = cacheKeyForKey(key)
return diskCacheURL.appendingPathComponent(cacheKey)
}
func cacheKeyForKey(_ key: String) -> String {
return key.md5
}
private func createCacheDirIfNeeded(_ url: URL, fileManager: FileManager) {
if fileManager.fileExists(atPath: url.absoluteString) == false {
do {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
NSLog("================> Failed to create directory: \(url)")
}
}
}
}
| 30.375 | 122 | 0.616255 |
642bc2d0bc5fd8b25538d24f2a8e5c4e7540cc7a | 789 | // 给定两个数组,编写一个函数来计算它们的交集。
func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
guard !nums1.isEmpty, !nums2.isEmpty else { return [] }
var cache = [Int: Int]() // key: 目标数, value: 较小数组重复次数
let minNums = nums1.count > nums2.count ? nums2 : nums1
let maxNums = nums1.count > nums2.count ? nums1 : nums2
for num in minNums {
if var count = cache[num] {
count += 1
cache[num] = count
} else {
cache[num] = 1
}
}
var results = [Int]()
for num in maxNums {
if var count = cache[num], count > 0 {
count -= 1
cache[num] = count
results.append(num)
}
}
return results
}
intersect([1, 2, 2, 1], [2, 2])
intersect([4, 9, 5], [9, 4, 9, 8, 4])
| 28.178571 | 59 | 0.510773 |
14a679c85a5aff745f8e4c10d7ca87c7aa23d05a | 11,579 | //
// Client+Deprecated.swift
// Filestack
//
// Created by Ruben Nine on 11/09/2019.
// Copyright © 2019 Filestack. All rights reserved.
//
import FilestackSDK
import UIKit
extension Client {
// MARK: - Deprecated
/// Uploads a file directly to a given storage location (currently only S3 is supported.)
///
/// - Parameter localURL: The URL of the local file to be uploaded.
/// - Parameter storeOptions: An object containing the store options (e.g. location, region, container, access, etc.
/// If none given, S3 location with default options is assumed.
/// - Parameter useIntelligentIngestionIfAvailable: Attempts to use Intelligent Ingestion for file uploading.
/// Defaults to `true`.
/// - Parameter queue: The queue on which the upload progress and completion handlers are dispatched.
/// - Parameter uploadProgress: Sets a closure to be called periodically during the lifecycle of the upload process
/// as data is uploaded to the server. `nil` by default.
/// - Parameter completionHandler: Adds a handler to be called once the upload has finished.
///
/// - Returns: An `Uploader` that allows starting, cancelling and monitoring the upload.
@objc
@available(*, deprecated, message: "Marked for removal in version 3.0. Please use upload(using:options:queue:uploadProgress:completionHandler:) instead")
@discardableResult
public func upload(from localURL: URL,
storeOptions: StorageOptions = .defaults,
useIntelligentIngestionIfAvailable: Bool = true,
queue: DispatchQueue = .main,
uploadProgress: ((Progress) -> Void)? = nil,
completionHandler: @escaping (JSONResponse?) -> Void) -> Uploader {
let uploadOptions = UploadOptions(preferIntelligentIngestion: useIntelligentIngestionIfAvailable,
startImmediately: true,
deleteTemporaryFilesAfterUpload: false,
storeOptions: storeOptions)
return upload(using: localURL,
options: uploadOptions,
queue: queue,
uploadProgress: uploadProgress,
completionHandler: completionHandler)
}
/// Uploads a file to a given storage location picked interactively from the camera or the photo library.
///
/// - Parameter viewController: The view controller that will present the picker.
/// - Parameter sourceType: The desired source type (e.g. camera, photo library.)
/// - Parameter storeOptions: An object containing the store options (e.g. location, region, container, access, etc.)
/// If none given, S3 location with default options is assumed.
/// - Parameter useIntelligentIngestionIfAvailable: Attempts to use Intelligent Ingestion for file uploading.
/// Defaults to `true`.
/// - Parameter queue: The queue on which the upload progress and completion handlers are dispatched.
/// - Parameter uploadProgress: Sets a closure to be called periodically during the lifecycle of the upload process
/// as data is uploaded to the server. `nil` by default.
/// - Parameter completionHandler: Adds a handler to be called once the upload has finished.
///
/// - Returns: A `Cancellable & Monitorizable` that allows cancelling and monitoring the upload.
@objc
@available(*, deprecated, message: "Marked for removal in version 3.0. Please use uploadFromImagePicker(viewController:sourceType:options:queue:uploadProgress:completionHandler:) instead")
@discardableResult
public func uploadFromImagePicker(viewController: UIViewController,
sourceType: UIImagePickerController.SourceType,
storeOptions: StorageOptions = .defaults,
useIntelligentIngestionIfAvailable: Bool = true,
queue: DispatchQueue = .main,
uploadProgress: ((Progress) -> Void)? = nil,
completionHandler: @escaping ([JSONResponse]) -> Void) -> Cancellable & Monitorizable {
let uploadOptions = UploadOptions(preferIntelligentIngestion: useIntelligentIngestionIfAvailable,
startImmediately: false,
deleteTemporaryFilesAfterUpload: false,
storeOptions: storeOptions)
return uploadFromImagePicker(viewController: viewController,
sourceType: sourceType,
options: uploadOptions,
queue: queue,
uploadProgress: uploadProgress,
completionHandler: completionHandler)
}
/// Uploads a file to a given storage location picked interactively from the device's documents, iCloud Drive or
/// other third-party cloud services.
///
/// - Parameter viewController: The view controller that will present the picker.
/// - Parameter storeOptions: An object containing the store options (e.g. location, region, container, access, etc.)
/// If none given, S3 location with default options is assumed.
/// - Parameter useIntelligentIngestionIfAvailable: Attempts to use Intelligent Ingestion for file uploading.
/// Defaults to `true`.
/// - Parameter queue: The queue on which the upload progress and completion handlers are dispatched.
/// - Parameter uploadProgress: Sets a closure to be called periodically during the lifecycle of the upload process
/// as data is uploaded to the server. `nil` by default.
/// - Parameter completionHandler: Adds a handler to be called once the upload has finished.
///
/// - Returns: A `Cancellable & Monitorizable` that allows cancelling and monitoring the upload.
@objc
@available(*, deprecated, message: "Marked for removal in version 3.0. Please use uploadFromDocumentPicker(viewController:options:queue:uploadProgress:completionHandler:) instead")
@discardableResult
public func uploadFromDocumentPicker(viewController: UIViewController,
storeOptions: StorageOptions = .defaults,
useIntelligentIngestionIfAvailable: Bool = true,
queue: DispatchQueue = .main,
uploadProgress: ((Progress) -> Void)? = nil,
completionHandler: @escaping ([JSONResponse]) -> Void) -> Cancellable & Monitorizable {
let uploadOptions = UploadOptions(preferIntelligentIngestion: useIntelligentIngestionIfAvailable,
startImmediately: false,
deleteTemporaryFilesAfterUpload: false,
storeOptions: storeOptions)
return uploadFromDocumentPicker(viewController: viewController,
options: uploadOptions,
queue: queue,
uploadProgress: uploadProgress,
completionHandler: completionHandler)
}
/// Uploads a file to a given storage location picked interactively from the camera or the photo library.
///
/// - Parameter viewController: The view controller that will present the picker.
/// - Parameter sourceType: The desired source type (e.g. camera, photo library.)
/// - Parameter options: A set of upload options (see `UploadOptions` for more information.)
/// - Parameter queue: The queue on which the upload progress and completion handlers are dispatched.
/// - Parameter uploadProgress: Sets a closure to be called periodically during the lifecycle of the upload process
/// as data is uploaded to the server. `nil` by default.
/// - Parameter completionHandler: Adds a handler to be called once the upload has finished.
///
/// - Returns: A `Cancellable & Monitorizable` that allows cancelling and monitoring the upload.
@available(*, deprecated, message: "Marked for removal in version 3.0. Use `pickFiles` instead. Additionally, please notice that the `uploadProgress` argument is no longer honored. Instead, you may observe progress on the `Monitorizable` returned by this function.")
@discardableResult
public func uploadFromImagePicker(viewController: UIViewController,
sourceType: UIImagePickerController.SourceType,
options: UploadOptions = .defaults,
queue: DispatchQueue = .main,
uploadProgress: ((Progress) -> Void)? = nil,
completionHandler: @escaping ([JSONResponse]) -> Void) -> Cancellable & Monitorizable {
let source: LocalSource
switch sourceType {
case .camera:
source = LocalSource.camera
default:
source = LocalSource.photoLibrary
}
return pickFiles(using: viewController,
source: source,
behavior: .uploadAndStore(uploadOptions: options),
pickCompletionHandler: nil,
uploadCompletionHandler: completionHandler)
}
/// Uploads a file to a given storage location picked interactively from the device's documents, iCloud Drive or
/// other third-party cloud services.
///
/// - Parameter viewController: The view controller that will present the picker.
/// - Parameter options: A set of upload options (see `UploadOptions` for more information.)
/// - Parameter queue: The queue on which the upload progress and completion handlers are dispatched.
/// - Parameter uploadProgress: Sets a closure to be called periodically during the lifecycle of the upload process
/// as data is uploaded to the server. `nil` by default.
/// - Parameter completionHandler: Adds a handler to be called once the upload has finished.
///
/// - Returns: A `Cancellable & Monitorizable` that allows cancelling and monitoring the upload.
@available(*, deprecated, message: "Marked for removal in version 3.0. Use `pickFiles` instead. Additionally, please notice that the `uploadProgress` argument is no longer honored. Instead, you may observe progress on the `Monitorizable` returned by this function.")
@discardableResult
public func uploadFromDocumentPicker(viewController: UIViewController,
options: UploadOptions = .defaults,
queue: DispatchQueue = .main,
uploadProgress: ((Progress) -> Void)? = nil,
completionHandler: @escaping ([JSONResponse]) -> Void) -> Cancellable & Monitorizable {
return pickFiles(using: viewController,
source: .documents,
behavior: .uploadAndStore(uploadOptions: options),
pickCompletionHandler: nil,
uploadCompletionHandler: completionHandler)
}
}
| 63.972376 | 270 | 0.623111 |
cc6a77050b195aad0c3d013efe35e55c9cc1b743 | 6,399 | import Foundation
import UIKit
import Turf
import MapboxMaps
/**
A label that is used to show a road name and a shield icon.
*/
@objc(MBWayNameLabel)
open class WayNameLabel: StylableLabel {}
/**
A host view for `WayNameLabel` that shows a road name and a shield icon.
`WayNameView` is hidden or shown depending on the road name information availability. In case if
such information is not present, `WayNameView` is automatically hidden. If you'd like to completely
hide `WayNameView` set `WayNameView.isHidden` property to `true`.
*/
@objc(MBWayNameView)
open class WayNameView: UIView {
private static let textInsets = UIEdgeInsets(top: 3, left: 14, bottom: 3, right: 14)
lazy var label: WayNameLabel = .forAutoLayout()
/**
A host view for the `WayNameLabel` instance that is used internally to show or hide
`WayNameLabel` depending on the road name data availability.
*/
lazy var containerView: UIView = .forAutoLayout()
var text: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
var attributedText: NSAttributedString? {
get {
return label.attributedText
}
set {
label.attributedText = newValue
}
}
open override var layer: CALayer {
containerView.layer
}
/**
The background color of the `WayNameView`.
*/
@objc dynamic public override var backgroundColor: UIColor? {
get {
containerView.backgroundColor
}
set {
containerView.backgroundColor = newValue
}
}
/**
The color of the `WayNameView`'s border.
*/
@objc dynamic public var borderColor: UIColor? {
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
set {
layer.borderColor = newValue?.cgColor
}
}
/**
The width of the `WayNameView`'s border.
*/
@objc dynamic public var borderWidth: CGFloat {
get {
layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
commonInit()
}
private func commonInit() {
addSubview(containerView)
containerView.pinInSuperview(respectingMargins: false)
containerView.addSubview(label)
label.pinInSuperview(respectingMargins: true)
}
open override func layoutSubviews() {
super.layoutSubviews()
containerView.layer.cornerRadius = bounds.midY
}
/**
Fills contents of the `WayNameLabel` with the road name and shield icon by extracting it from the
`Turf.Feature` and `MapboxMaps.Style` objects (if it's valid and available).
- parameter feature: `Turf.Feature` object, properties of which will be checked for the appropriate
shield image related information.
- parameter style: Style of the map view instance.
- returns: `true` if operation was successful, `false` otherwise.
*/
@discardableResult
func setupWith(feature: Turf.Feature, using style: MapboxMaps.Style?) -> Bool {
var currentShieldName: NSAttributedString?, currentRoadName: String?
var didSetup = false
if case let .string(ref) = feature.properties?["ref"],
case let .string(shield) = feature.properties?["shield"],
case let .number(reflen) = feature.properties?["reflen"] {
let textColor = roadShieldTextColor(line: feature) ?? .black
let imageName = "\(shield)-\(Int(reflen))"
currentShieldName = roadShieldAttributedText(for: ref, textColor: textColor, style: style, imageName: imageName)
}
if case let .string(roadName) = feature.properties?["name"], !roadName.isEmpty {
currentRoadName = roadName
self.text = roadName
didSetup = true
}
if let compositeShieldImage = currentShieldName, let roadName = currentRoadName {
let compositeShield = NSMutableAttributedString(string: " \(roadName)")
compositeShield.insert(compositeShieldImage, at: 0)
self.attributedText = compositeShield
didSetup = true
}
return didSetup
}
private func roadShieldTextColor(line: Turf.Feature) -> UIColor? {
guard case let .string(shield) = line.properties?["shield"] else {
return nil
}
// shield_text_color is present in Mapbox Streets source v8 but not v7.
guard case let .string(shieldTextColor) = line.properties?["shield_text_color"] else {
let currentShield = HighwayShield.RoadType(rawValue: shield)
return currentShield?.textColor
}
switch shieldTextColor {
case "black":
return .black
case "blue":
return .blue
case "white":
return .white
case "yellow":
return .yellow
case "orange":
return .orange
default:
return .black
}
}
private func roadShieldAttributedText(for text: String,
textColor: UIColor,
style: MapboxMaps.Style?,
imageName: String) -> NSAttributedString? {
guard let image = style?.image(withId: imageName) else { return nil }
let attachment = ShieldAttachment()
// To correctly scale size of the font its height is based on the label where it is shown.
let fontSize = label.frame.size.height / 2.5
attachment.image = image.withCenteredText(text,
color: textColor,
font: UIFont.boldSystemFont(ofSize: fontSize),
size: label.frame.size)
return NSAttributedString(attachment: attachment)
}
}
| 32.482234 | 124 | 0.584779 |
5b19d98b6544bf4b981980fd9ede7ecd5fc8f95f | 2,169 | //
// AppDelegate.swift
// SCOptionPageDemo
//
// Created by abon on 2018/1/19.
// Copyright © 2018年 kaito. All rights reserved.
//
import UIKit
@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:.
}
}
| 46.148936 | 285 | 0.755648 |
39180e4457f03e1e7cc270114ea251ad21c4394b | 499 | //
// WeatherDetail.swift
// utilityApp
//
// Created by the_world on 2/10/19.
// Copyright © 2019 the_world. All rights reserved.
//
import Foundation
class WeatherDetail{
var detailname: String
var content: String
init() {
// init empty for test purpose
self.detailname = "WIND"
self.content = "SE 2 MPH"
}
init(withAttr attr: String, withContent content: String){
self.detailname = attr
self.content = content
}
}
| 17.821429 | 61 | 0.611222 |
d7e5cb7b95e2bdb7d0dafffa2e25f483c709a351 | 2,977 | //
// StudentInformation.swift
// OnTheMap
//
// Created by Luke Van In on 2017/01/13.
// Copyright © 2017 Luke Van In. All rights reserved.
//
// Record containing the name, location, and media URL for a student.
//
import Foundation
struct StudentInformation {
//
// Unique identifier of the object. Assigned by the web service API when the object is added. The object may be
// updated by passing this objectId when making an update request to the API.
//
let objectId: String
//
// Key assigned by the app when the object is added to the API. Recommended to be set to the users' account ID
// although this is not actually necessarily unique and can contain any value.
//
let uniqueKey: String
//
// Information specific to the user, e.g. the user's name.
//
let user: User
//
// Information pertaining to the map location, e.g. coordinates and URL.
//
let location: StudentLocation
}
//
// Extension on StudentInformation for creating instances from JSON data. Most of the fields are required, and an
// exception will be thrown if the field is missing, or not in the expected format. Entities with missing or invalid
// fields are excluded from the results.
//
// Some fields are optional (e.g. mediaURL) and will resolve to nil values. The entity will still be included in the
// results but without the optional information.
//
extension StudentInformation: JSONEntity {
init(json: Any) throws {
// Parse required values.
guard let entity = json as? [String: Any] else {
throw JSONError.format("dictionary")
}
guard let firstName = entity["firstName"] as? String else {
throw JSONError.format("firstName")
}
guard let lastName = entity["lastName"] as? String else {
throw JSONError.format("lastName")
}
guard let latitude = entity["latitude"] as? Double else {
throw JSONError.format("latitude")
}
guard let longitude = entity["longitude"] as? Double else {
throw JSONError.format("longitude")
}
guard let objectId = entity["objectId"] as? String else {
throw JSONError.format("objectId")
}
guard let uniqueKey = entity["uniqueKey"] as? String else {
throw JSONError.format("uniqueKey")
}
// Optional values.
let mediaURL = entity["mediaURL"] as? String
let mapString = entity["mapString"] as? String
// Instantiate objects.
self.objectId = objectId
self.uniqueKey = uniqueKey
self.user = User(
firstName: firstName,
lastName: lastName
)
self.location = StudentLocation(
mediaURL: mediaURL,
mapString: mapString,
longitude: longitude,
latitude: latitude
)
}
}
| 32.714286 | 118 | 0.620423 |
6a0ac2f23c8a0aee3a32978939ee2b5313e94539 | 987 | //
// Logger.swift
// CYaml
//
// Created by 林煒峻 on 2019/10/1.
//
import Foundation
import Rainbow
public enum Logger {
private static var eventImplicitCount: Int = 0
private static var isPrintEvent: Bool = false
public static func set(logEvent enable: Bool) {
self.isPrintEvent = enable
}
public static func summery() {
print("""
\("[FIX IMPLICIT TYPE]: \(eventImplicitCount)".applyingColor(.green))
""")
}
public static func add(event: Event) {
self.classify(event: event)
guard isPrintEvent else { return }
print(event)
}
private static func classify(event: Event) {
switch event {
case .implicitType:
self.eventImplicitCount += 1
default:
return
}
}
// TODO:
// \("[FIX IBAction]: \(count)".applyingColor(.green))
// \("[FIX IBOutlet]: \(count)".applyingColor(.green))
}
| 21.456522 | 77 | 0.560284 |
625c499e8513292f057250e5a6db774c22a38bbc | 4,177 |
import Foundation
public protocol IQuestConfig: Codable {
func GetId()->Int
func GetText()->String
func GetType()->eQuestType
// func GetJSON()->Any
// func GetDBValue()->String
//
// func SetText(text: String)
// func SetDBValue(value: String)
// func SetId(value: Int)
//
func isHaveCondition()->Bool
func GetCondition()->conditionModel
//Config tanımını geçerli olup olmasığını değilse hatayı çevirir.
//func ValidateConfig()->UIValidMessage
}
public class allConfigModel: Codable{
public var id: Int?
public var dbvalue: String?
public var text: String = ""
public var required: Bool? = true
public var type: String? = ""
public var desc: String? = ""
var condition: conditionModel?
//test
public var maxlength: Int? = 0
public var minlength: Int? = 0
public var placeholder: String? = ""
//numeric
var maxvalue: Int?
var minvalue: Int?
var decimallimit: Int?
//info
var infotype: String? = ""
var flagcode: Int? = 0
//single-multi
var options: [OptionBasicConfigModel]? = []
init() {
}
public func GetQuest() -> IQuestConfig{
switch type {
case "text":
print("text quest")
let q: textConfigModel = textConfigModel()
q.id = self.id!
q.dbvalue = self.dbvalue!
q.text = self.text
q.required = self.required
q.type = eQuestType.text
q.desc = self.desc
q.condition = self.condition
q.maxlength = self.maxlength
q.minlength = self.minlength
q.placeholder = self.placeholder
return q
case "numeric":
print("numeric quest")
let q: numericConfigModel = numericConfigModel()
q.id = self.id!
q.dbvalue = self.dbvalue!
q.text = self.text
q.required = self.required
q.type = eQuestType.numeric
q.desc = self.desc
q.condition = self.condition
q.maxvalue = self.maxvalue
q.minvalue = self.minvalue
q.decimallimit = self.decimallimit
q.placeholder = self.placeholder
return q
case "single":
print("single quest")
let q: singleConfigModel = singleConfigModel()
q.id = self.id!
q.dbvalue = self.dbvalue!
q.text = self.text
q.required = self.required
q.type = eQuestType.single
q.desc = self.desc
q.condition = self.condition
q.options = self.options!
return q
case "multi":
print("multi quest")
let q: multiConfigModel = multiConfigModel()
q.id = self.id!
q.dbvalue = self.dbvalue!
q.text = self.text
q.required = self.required
q.type = eQuestType.multi
q.desc = self.desc
q.condition = self.condition
q.options = self.options!
return q
case "info":
print("info quest")
let q: infoConfigModel = infoConfigModel()
q.id = self.id!
q.dbvalue = self.dbvalue!
q.text = self.text
q.required = self.required
q.type = eQuestType.info
q.desc = self.desc
q.condition = self.condition
q.infotype = self.infotype
q.flagcode = self.flagcode
return q
default:
let q: infoConfigModel = infoConfigModel()
q.id = self.id!
q.dbvalue = self.dbvalue!
q.text = self.text
q.required = self.required
q.type = eQuestType.info
q.desc = self.desc
q.condition = self.condition
q.infotype = "none"
q.flagcode = 1
return q
}
}
}
| 26.10625 | 69 | 0.510175 |
eb2c1785f7d5b25fd87b784e64f66663bc3f170b | 10,384 | import SafariServices
import OSLog
let log = OSLog(subsystem: "com.kishikawakatsumi.SourceKitForSafari", category: "Safari Extension")
final class SafariExtensionHandler: SFSafariExtensionHandler {
private let service = SourceKitServiceProxy.shared
override init() {
super.init()
Settings.shared.prepare()
}
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
switch messageName {
case "initialize":
page.getPropertiesWithCompletionHandler { [weak self] (properties) in
guard let self = self else { return }
guard let properties = properties, let url = properties.url else {
return
}
guard let repositoryURL = self.parseGitHubURL(url) else {
return
}
self.service.synchronizeRepository(repositoryURL) { (_, _) in }
}
case "didOpen":
guard let userInfo = userInfo,
let resource = userInfo["resource"] as? String,
let slug = userInfo["slug"] as? String,
let filepath = userInfo["filepath"] as? String,
let text = userInfo["text"] as? String
else { break }
os_log("[SafariExtension] didOpen(file: %{public}s)", log: log, type: .debug, filepath)
service.sendInitializeRequest(resource: resource, slug: slug) { [weak self] (successfully, _) in
guard let self = self else { return }
if successfully {
self.service.sendInitializedNotification(resource: resource, slug: slug) { [weak self] (successfully, _) in
guard let self = self else { return }
if successfully {
self.service.sendDidOpenNotification(resource: resource, slug: slug, path: filepath, text: text) { [weak self] (successfully, _) in
guard let self = self else { return }
if successfully {
self.service.sendDocumentSymbolRequest(resource: resource, slug: slug, path: filepath) { (successfully, response) in
guard let value = response["value"] else { return }
page.dispatchMessageToScript(withName: "response", userInfo: ["request": "documentSymbol", "result": "success", "value": value])
}
}
}
}
}
}
}
case "hover":
guard let userInfo = userInfo,
let resource = userInfo["resource"] as? String,
let slug = userInfo["slug"] as? String,
let filepath = userInfo["filepath"] as? String ,
let line = userInfo["line"] as? Int,
let character = userInfo["character"] as? Int,
let text = userInfo["text"] as? String
else { break }
var skip = 0
for character in text {
if character == " " || character == "." {
skip += 1
} else {
break
}
}
os_log("[SafariExtension] hover(file: %{public}s, line: %d, character: %d)", log: log, type: .debug, filepath, line, character + skip)
service.sendHoverRequest(resource: resource, slug: slug, path: filepath, line: line, character: character + skip) { (successfully, response) in
if successfully {
if let value = response["value"] as? String {
page.dispatchMessageToScript(
withName: "response",
userInfo: ["request": "hover", "result": "success", "value": value, "line": line, "character": character, "text": text]
)
}
} else {
page.dispatchMessageToScript(withName: "response", userInfo: ["request": "hover", "result": "error"])
}
}
case "definition":
guard let userInfo = userInfo,
let resource = userInfo["resource"] as? String,
let slug = userInfo["slug"] as? String,
let filepath = userInfo["filepath"] as? String ,
let line = userInfo["line"] as? Int,
let character = userInfo["character"] as? Int,
let text = userInfo["text"] as? String
else { break }
var skip = 0
for character in text {
if character == " " || character == "." {
skip += 1
} else {
break
}
}
os_log("[SafariExtension] definition(file: %{public}s, line: %d, character: %d)", log: log, type: .debug, filepath, line, character + skip)
service.sendDefinitionRequest(resource: resource, slug: slug, path: filepath, line: line, character: character + skip) { (successfully, response) in
if successfully {
if let value = response["value"] as? [[String: Any]] {
let locations = value.compactMap { (location) -> [String: Any]? in
guard let uri = location["uri"] as? String, let start = location["start"] as? [String: Any],
let line = start["line"] as? Int else { return nil }
let filename = location["filename"] ?? ""
let content = location["content"] ?? ""
if !uri.isEmpty {
let ref = uri
.replacingOccurrences(of: resource, with: "")
.replacingOccurrences(of: slug, with: "")
.split(separator: "/")
.joined(separator: "/")
.appending("#L\(line + 1)")
return ["uri": ref, "filename": filename, "content": content]
} else {
return ["uri": "", "filename": filename, "content": content]
}
}
guard !locations.isEmpty else { return }
page.dispatchMessageToScript(
withName: "response",
userInfo: ["request": "definition", "result": "success", "value": ["locations": locations], "line": line, "character": character, "text": text]
)
}
} else {
page.dispatchMessageToScript(withName: "response", userInfo: ["request": "definition", "result": "error"])
}
}
default:
break
}
}
override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) {
validationHandler(true, "")
}
override func popoverWillShow(in window: SFSafariWindow) {
let viewController = SafariExtensionViewController.shared
viewController.updateUI()
window.getActiveTab { (activeTab) in
guard let activeTab = activeTab else {
return
}
activeTab.getActivePage { (activePage) in
guard let activePage = activePage else {
return
}
activePage.getPropertiesWithCompletionHandler { [weak self] (properties) in
guard let properties = properties, let url = properties.url else {
return
}
guard let repositoryURL = self?.parseGitHubURL(url) else {
viewController.repository = ""
return
}
viewController.repository = repositoryURL.absoluteString
}
}
}
if Settings.shared.serverPathOption == .default {
service.defaultLanguageServerPath { (successfully, response) in
if successfully {
Settings.shared.serverPath = response
viewController.updateUI()
}
}
}
service.defaultSDKPath(for: Settings.shared.SDKOption.rawValue) { (successfully, response) in
if successfully {
Settings.shared.SDKPath = response
viewController.updateUI()
}
}
}
override func popoverViewController() -> SFSafariExtensionViewController {
let viewController = SafariExtensionViewController.shared
return viewController
}
private func sendLogMessage(_ level: LogLevel, _ message: String) {
SFSafariApplication.getActiveWindow { (window) in
guard let window = window else {
return
}
window.getActiveTab { (activeTab) in
guard let activeTab = activeTab else {
return
}
activeTab.getActivePage { (activePage) in
guard let activePage = activePage else {
return
}
activePage.dispatchMessageToScript(withName: "log", userInfo: ["value": "[\(level.rawValue.uppercased())] \(message)"])
}
}
}
}
private func parseGitHubURL(_ url: URL) -> URL? {
guard let scheme = url.scheme, scheme == "https" ,let host = url.host, host == "github.com", url.pathComponents.count >= 3 else {
return nil
}
return URL(string: "\(scheme)://\(host)/\(url.pathComponents.dropFirst().prefix(2).joined(separator: "/")).git")
}
private enum LogLevel: String {
case debug
case info
case warn
case error
}
}
| 42.73251 | 171 | 0.489118 |
087874725da275f24148e5e4c8a616c5784cc715 | 2,163 | //
// AppDelegate.swift
// FlappyBird
//
// Created by Hossam Ghareeb on 9/5/14.
// Copyright (c) 2014 AppCoda. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.021277 | 285 | 0.744799 |
f728b7ad4f50ad3273b68c192436fe26785c8275 | 12,194 | //
// SilentScrollable.swift
// SilentScrolly
//
// Created by Takuma Horiuchi on 2018/02/22.
// Copyright © 2018年 Takuma Horiuchi. All rights reserved.
//
import UIKit
public protocol SilentScrollable: class {
var silentScrolly: SilentScrolly? { get set }
func statusBarStyle(showStyle: UIStatusBarStyle, hideStyle: UIStatusBarStyle) -> UIStatusBarStyle
func configureSilentScrolly(_ scrollView: UIScrollView, followBottomView: UIView?, completion: (() -> Void)?)
func showNavigationBar()
func hideNavigationBar()
func silentWillDisappear()
func silentDidDisappear()
func silentDidLayoutSubviews()
func silentWillTranstion()
func silentDidScroll()
func silentDidZoom()
}
public extension SilentScrollable where Self: UIViewController {
public func statusBarStyle(showStyle: UIStatusBarStyle, hideStyle: UIStatusBarStyle) -> UIStatusBarStyle {
guard let preferredStatusBarStyle = silentScrolly?.preferredStatusBarStyle else {
/// To consider whether statusBarStyle and configureSilentScrolly precede.
if silentScrolly == nil {
silentScrolly = SilentScrolly()
}
silentScrolly?.preferredStatusBarStyle = showStyle
silentScrolly?.showStatusBarStyle = showStyle
silentScrolly?.hideStatusBarStyle = hideStyle
return showStyle
}
return preferredStatusBarStyle
}
private func setStatusBarAppearanceShow() {
guard let showStyle = silentScrolly?.showStatusBarStyle else {
return
}
silentScrolly?.preferredStatusBarStyle = showStyle
setNeedsStatusBarAppearanceUpdate()
}
private func setStatusBarAppearanceHide() {
guard let hideStyle = silentScrolly?.hideStatusBarStyle else {
return
}
silentScrolly?.preferredStatusBarStyle = hideStyle
setNeedsStatusBarAppearanceUpdate()
}
public func configureSilentScrolly(_ scrollView: UIScrollView, followBottomView: UIView?, completion: (() -> Void)? = nil) {
guard let navigationBarHeight = navigationController?.navigationBar.bounds.height,
let safeAreaInsetsBottom = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else {
return
}
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let totalHeight = statusBarHeight + navigationBarHeight
/// To consider whether statusBarStyle and configureSilentScrolly precede.
if silentScrolly == nil {
silentScrolly = SilentScrolly()
}
silentScrolly?.scrollView = scrollView
silentScrolly?.isNavigationBarShow = true
silentScrolly?.isTransitionCompleted = true
silentScrolly?.showNavigationBarFrameOriginY = statusBarHeight
silentScrolly?.hideNavigationBarFrameOriginY = -navigationBarHeight
silentScrolly?.showScrollIndicatorInsetsTop = scrollView.scrollIndicatorInsets.top
silentScrolly?.hideScrollIndicatorInsetsTop = scrollView.scrollIndicatorInsets.top - totalHeight
// FIXME: Because the following adjusts it to the setting that I showed with a example.
if let bottomView = followBottomView {
let screenHeight = UIScreen.main.bounds.height
let eitherSafeAreaInsetsBottom = bottomView is UITabBar ? 0 : safeAreaInsetsBottom
let bottomViewHeight = bottomView.bounds.height + eitherSafeAreaInsetsBottom
silentScrolly?.bottomView = bottomView
silentScrolly?.showBottomViewFrameOriginY = screenHeight - bottomViewHeight
silentScrolly?.hideBottomViewFrameOriginY = screenHeight
silentScrolly?.showContentInsetBottom = bottomView is UITabBar ? 0 : bottomViewHeight
silentScrolly?.hideContentInsetBottom = bottomView is UITabBar ? -bottomViewHeight : -eitherSafeAreaInsetsBottom
}
if let isAddObserver = silentScrolly?.isAddObserver {
if isAddObserver {
NotificationCenter.default.addObserver(forName: .UIDeviceOrientationDidChange, object: nil, queue: nil) { [weak self] in
self?.orientationDidChange($0)
}
NotificationCenter.default.addObserver(forName: .UIApplicationDidEnterBackground, object: nil, queue: nil) { [weak self] in
self?.didEnterBackground($0)
}
}
silentScrolly?.isAddObserver = false
}
completion?()
}
private func orientationDidChange(_ notification: Notification) {
guard isViewLoaded,
let _ = view.window,
let scrollView = silentScrolly?.scrollView,
let isShow = silentScrolly?.isNavigationBarShow else {
return
}
adjustEitherView(scrollView, isShow: isShow, animated: false)
}
private func didEnterBackground(_ notification: Notification) {
guard isViewLoaded,
let _ = view.window,
let scrollView = silentScrolly?.scrollView else {
return
}
adjustEitherView(scrollView, isShow: true, animated: false)
}
public func showNavigationBar() {
guard let scrollView = silentScrolly?.scrollView else {
return
}
adjustEitherView(scrollView, isShow: true)
}
public func hideNavigationBar() {
guard let scrollView = silentScrolly?.scrollView else {
return
}
adjustEitherView(scrollView, isShow: false)
}
public func silentWillDisappear() {
showNavigationBar()
silentScrolly?.isTransitionCompleted = false
}
public func silentDidDisappear() {
silentScrolly?.isTransitionCompleted = true
}
public func silentDidLayoutSubviews() {
guard let scrollView = silentScrolly?.scrollView else {
return
}
// animation completed because the calculation is crazy
adjustEitherView(scrollView, isShow: true, animated: false) { [weak self] in
guard let me = self else { return }
me.configureSilentScrolly(scrollView, followBottomView: me.silentScrolly?.bottomView) { [weak self] in
self?.adjustEitherView(scrollView, isShow: true, animated: false)
scrollView.setZoomScale(1, animated: false)
}
}
}
public func silentWillTranstion() {
guard let scrollView = silentScrolly?.scrollView else {
return
}
adjustEitherView(scrollView, isShow: true, animated: false)
}
public func silentDidScroll() {
guard let scrollView = silentScrolly?.scrollView,
let prevPositiveContentOffsetY = silentScrolly?.prevPositiveContentOffsetY else {
return
}
if scrollView.contentSize.height < scrollView.bounds.height || scrollView.isZooming {
return
}
if scrollView.contentOffset.y <= 0 {
adjustEitherView(scrollView, isShow: true)
return
}
let positiveContentOffsetY = calcPositiveContentOffsetY(scrollView)
let velocityY = scrollView.panGestureRecognizer.velocity(in: view).y
if positiveContentOffsetY != prevPositiveContentOffsetY && scrollView.isTracking {
if velocityY < SilentScrolly.Const.minDoNothingAdjustNavigationBarVelocityY {
adjustEitherView(scrollView, isShow: false)
} else if velocityY > SilentScrolly.Const.maxDoNothingAdjustNavigationBarVelocityY {
adjustEitherView(scrollView, isShow: true)
}
}
silentScrolly?.prevPositiveContentOffsetY = positiveContentOffsetY
}
public func silentDidZoom() {
guard let scrollView = silentScrolly?.scrollView else {
return
}
func setNavigationBar() {
scrollView.zoomScale <= 1 ? showNavigationBar() : hideNavigationBar()
}
scrollView.isZooming ? setNavigationBar() : scrollView.setZoomScale(1, animated: true)
}
private func calcPositiveContentOffsetY(_ scrollView: UIScrollView) -> CGFloat {
var contentOffsetY = scrollView.contentOffset.y + scrollView.contentInset.top
contentOffsetY = contentOffsetY > 0 ? contentOffsetY : 0
return contentOffsetY
}
private func adjustEitherView(_ scrollView: UIScrollView, isShow: Bool, animated: Bool = true, completion: (() -> Void)? = nil) {
guard let isTransitionCompleted = silentScrolly?.isTransitionCompleted,
let showNavigationBarFrameOriginY = silentScrolly?.showNavigationBarFrameOriginY,
let hideNavigationBarFrameOriginY = silentScrolly?.hideNavigationBarFrameOriginY,
let showScrollIndicatorInsetsTop = silentScrolly?.showScrollIndicatorInsetsTop,
let hideScrollIndicatorInsetsTop = silentScrolly?.hideScrollIndicatorInsetsTop,
let currentNavigationBarOriginY = navigationController?.navigationBar.frame.origin.y else {
return
}
if scrollView.contentSize.height < scrollView.bounds.height || !isTransitionCompleted {
return
}
let eitherNavigationBarFrameOriginY = isShow ? showNavigationBarFrameOriginY : hideNavigationBarFrameOriginY
let eitherScrollIndicatorInsetsTop = isShow ? showScrollIndicatorInsetsTop : hideScrollIndicatorInsetsTop
let navigationBarContentsAlpha: CGFloat = isShow ? 1 : 0
func setPosition() {
if silentScrolly?.preferredStatusBarStyle != nil {
isShow ? setStatusBarAppearanceShow() : setStatusBarAppearanceHide()
}
navigationController?.navigationBar.frame.origin.y = eitherNavigationBarFrameOriginY
scrollView.scrollIndicatorInsets.top = eitherScrollIndicatorInsetsTop
setNavigationBarContentsAlpha(navigationBarContentsAlpha)
silentScrolly?.isNavigationBarShow = isShow
}
if !animated {
setPosition()
animateBottomView(scrollView, isShow: isShow, animated: animated)
completion?()
return
}
if currentNavigationBarOriginY != eitherNavigationBarFrameOriginY && scrollView.scrollIndicatorInsets.top != eitherScrollIndicatorInsetsTop {
UIView.animate(withDuration: SilentScrolly.Const.animateDuration, animations: {
setPosition()
}, completion: { _ in
completion?()
})
animateBottomView(scrollView, isShow: isShow, animated: animated)
}
}
private func animateBottomView(_ scrollView: UIScrollView, isShow: Bool, animated: Bool = true) {
guard let bottomView = silentScrolly?.bottomView,
let showBottomViewFrameOriginY = silentScrolly?.showBottomViewFrameOriginY,
let hideBottomViewFrameOriginY = silentScrolly?.hideBottomViewFrameOriginY,
let showContentInsetBottom = silentScrolly?.showContentInsetBottom,
let hideContentInsetBottom = silentScrolly?.hideContentInsetBottom else {
return
}
let eitherBottomViewFrameOriginY = isShow ? showBottomViewFrameOriginY : hideBottomViewFrameOriginY
let eitherContentInsetBottom = isShow ? showContentInsetBottom : hideContentInsetBottom
func setPosition() {
bottomView.frame.origin.y = eitherBottomViewFrameOriginY
scrollView.contentInset.bottom = eitherContentInsetBottom
scrollView.scrollIndicatorInsets.bottom = eitherContentInsetBottom
}
if !animated {
setPosition()
return
}
UIView.animate(withDuration: SilentScrolly.Const.animateDuration) {
setPosition()
}
}
private func setNavigationBarContentsAlpha(_ alpha: CGFloat) {
guard let navigationBar = navigationController?.navigationBar else {
return
}
navigationItem.titleView?.alpha = alpha
navigationBar.tintColor = navigationBar.tintColor.withAlphaComponent(alpha)
}
}
| 41.057239 | 149 | 0.67566 |
1d8aca1df3b5c746594373ca27b27a427e31c363 | 2,285 | //
// Copyright (C) 2017-2019 HERE Europe B.V.
//
// 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.
//
@testable import MSDKUI_Demo
import XCTest
final class IconButtonTests: XCTestCase {
// Is the button tapped?
private var isTapped = false
// MARK: - Tests
// Tests that there is a default type value and it is the expected value
func testDefaultValues() {
let button = IconButton(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
// Is the default type expected value?
XCTAssertEqual(button.type, .add, "Not the expected type .add!")
// Is the image set?
XCTAssertNotNil(button.image(for: .normal), "No image is set!")
}
// Tests that it is possible to set the type to a custom value
func testCustomType() {
let button = IconButton(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
// Set a custom type
button.type = .options
// Is the type expected value?
XCTAssertEqual(button.type, .options, "Not the expected type .options!")
// Is the image set?
XCTAssertNotNil(button.image(for: .normal), "No image is set!")
}
// Tests that the button tap handler works as expected
func testTapHandler() {
let button = IconButton(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
// Set the button tap handler method
button.addTarget(self, action: #selector(tapHandler(sender:)), for: .touchUpInside)
// Simulate touch
button.sendActions(for: .touchUpInside)
// Is the tap detected?
XCTAssertTrue(isTapped, "The tap wasn't detected!")
}
// MARK: - Private
@objc private func tapHandler(sender _: UIButton) {
isTapped = true
}
}
| 31.736111 | 91 | 0.653392 |
48946e38a203ecbb295090a37e7725ee491eadfe | 2,454 | /*
Copyright (C) 2017 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A simple class that holds information about an Asset.
*/
import AVFoundation
class Asset {
/// The AVURLAsset corresponding to this Asset.
var urlAsset: AVURLAsset
/// The underlying `Stream` associated with the Asset based on the contents of the `Streams.plist` entry.
let stream: Stream
init(stream: Stream, urlAsset: AVURLAsset) {
self.urlAsset = urlAsset
self.stream = stream
if self.stream.isProtected {
ContentKeyManager.shared.updateResourceLoaderDelegate(forAsset: self.urlAsset)
}
}
}
/// Extends `Asset` to conform to the `Equatable` protocol.
extension Asset: Equatable {
static func ==(lhs: Asset, rhs: Asset) -> Bool {
return (lhs.stream == rhs.stream) && (lhs.urlAsset == rhs.urlAsset)
}
}
/**
Extends `Asset` to add a simple download state enumeration used by the sample
to track the download states of Assets.
*/
extension Asset {
enum DownloadState: String {
/// The asset is not downloaded at all.
case notDownloaded
/// The asset has a download in progress.
case downloading
/// The asset is downloaded and saved on diek.
case downloaded
}
}
/**
Extends `Asset` to define a number of values to use as keys in dictionary lookups.
*/
extension Asset {
struct Keys {
/**
Key for the Asset name, used for `AssetDownloadProgressNotification` and
`AssetDownloadStateChangedNotification` Notifications as well as
AssetListManager.
*/
static let name = "AssetNameKey"
/**
Key for the Asset download percentage, used for
`AssetDownloadProgressNotification` Notification.
*/
static let percentDownloaded = "AssetPercentDownloadedKey"
/**
Key for the Asset download state, used for
`AssetDownloadStateChangedNotification` Notification.
*/
static let downloadState = "AssetDownloadStateKey"
/**
Key for the Asset download AVMediaSelection display Name, used for
`AssetDownloadStateChangedNotification` Notification.
*/
static let downloadSelectionDisplayName = "AssetDownloadSelectionDisplayNameKey"
}
}
| 29.214286 | 109 | 0.645477 |
8a0ec89a2cc4152e6ce7f326ffa10148bdc5aa92 | 1,063 | //
// PostRoutes.swift
// PostRoutes
//
// Created by Hao Qin on 8/17/21.
//
import Foundation
import KituraContracts
let iso8601Decoder: () -> BodyDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}
let iso8601Encoder: () -> BodyEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return encoder
}
func initializePostRoutes(app: App) {
app.router.get("/api/v1/posts", handler: getPosts)
app.router.post("/api/v1/posts", handler: addPost)
app.router.decoders[.json] = iso8601Decoder
app.router.encoders[.json] = iso8601Encoder
}
func getPosts(user: UserAuthentication, completion: @escaping ([Post]?, RequestError?) -> Void) {
Post.findAll(completion)
}
func addPost(user: UserAuthentication, post: Post, completion: @escaping (Post?, RequestError?) -> Void) {
var newPost = post
if newPost.createdByUser != user.id {
return completion(nil, RequestError.forbidden)
}
if newPost.id == nil {
newPost.id = UUID()
}
newPost.save(completion)
}
| 24.159091 | 106 | 0.707432 |
033218b1f2d71a04ed8f090368b5e02e55d0af78 | 362 | //
// String+Range.swift
// SavannaKit
//
// Created by Louis D'hauwe on 09/07/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import Foundation
extension String {
func nsRange(fromRange range: Range<Int>) -> NSRange {
let from = range.lowerBound
let to = range.upperBound
return NSRange(location: from, length: to - from)
}
}
| 17.238095 | 55 | 0.676796 |
dda73cf8e5c4d0f7963782459d944e24c871306c | 71 | import Cocoa
var a = 199 % (100 * 10)
var b = 199 % 100
print(a - b)
| 10.142857 | 24 | 0.56338 |
216dd17dda47f0723fad2362c218f8a492d16e7c | 1,822 | //
// Validation+LogicalOperators.swift
// ValidatedPropertyKit
//
// Created by Sven Tiigi on 20.06.19.
// Copyright © 2019 Sven Tiigi. All rights reserved.
//
import Foundation
// MARK: - Validation+Not
public extension Validation {
/// Performs a logical `NOT` (`!`) operation on a Validation
///
/// - Parameter validation: The Validation value to negate
/// - Returns: The negated Validation
static prefix func ! (_ validation: Validation) -> Validation {
return .init { value in
// Return negated validation result
return !validation.isValid(value: value)
}
}
}
// MARK: - Validation+And
public extension Validation {
/// Performs a logical `AND` (`&&`) operation on two Validations
///
/// - Parameters:
/// - lhs: The left-hand side of the operation
/// - rhs: The right-hand side of the operation
/// - Returns: The new Validation
static func && (lhs: Validation, rhs: @autoclosure @escaping () -> Validation) -> Validation {
return .init { value in
// Return logical AND operation result
return lhs.isValid(value: value) && rhs().isValid(value: value)
}
}
}
// MARK: - Validation+Or
public extension Validation {
/// Performs a logical `OR` (`||`) operation on two Validations
///
/// - Parameters:
/// - lhs: The left-hand side of the operation
/// - rhs: The right-hand side of the operation
/// - Returns: The new Validation
static func || (lhs: Validation, rhs: @autoclosure @escaping () -> Validation) -> Validation {
return .init { value in
// Return logical OR operation result
return lhs.isValid(value: value) || rhs().isValid(value: value)
}
}
}
| 28.030769 | 98 | 0.601537 |
894e0fe4679e0ac1ae1db8253baac4cf1cb4d6d5 | 1,362 | /**
* (C) Copyright IBM Corp. 2018, 2019.
*
* 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
/**
A list of PDF conversion settings.
*/
public struct PDFSettings: Codable, Equatable {
/**
Object containing heading detection conversion settings for PDF documents.
*/
public var heading: PDFHeadingDetection?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case heading = "heading"
}
/**
Initialize a `PDFSettings` with member variables.
- parameter heading: Object containing heading detection conversion settings for PDF documents.
- returns: An initialized `PDFSettings`.
*/
public init(
heading: PDFHeadingDetection? = nil
)
{
self.heading = heading
}
}
| 27.795918 | 100 | 0.696769 |
1ca1f74944a42aa218566ef17dc62fe02a79a00d | 18,626 | /**
Copyright IBM Corporation 2016, 2017, 2018, 2019
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 XCTest
import SwiftKuery
@testable import SwiftKueryPostgreSQL
#if os(Linux)
let tableInsert = "tableInsertLinux"
let tableInsert2 = "tableInsert2Linux"
let tableInsert3 = "tableInsert3Linux"
let tableInsert4 = "tableInsert4Linux"
#else
let tableInsert = "tableInsertOSX"
let tableInsert2 = "tableInsert2OSX"
let tableInsert3 = "tableInsert3OSX"
let tableInsert4 = "tableInsert4OSX"
#endif
class TestInsert: XCTestCase {
static var allTests: [(String, (TestInsert) -> () throws -> Void)] {
return [
("testInsert", testInsert),
("testInsertID", testInsertID),
("testInsertNil", testInsertNil),
]
}
class MyTable : Table {
let a = Column("a", autoIncrement: true, primaryKey: true)
let b = Column("b")
let tableName = tableInsert
}
class MyTable2 : Table {
let a = Column("a")
let b = Column("b")
let tableName = tableInsert2
}
class MyTable3 : Table {
let a = Column("a", autoIncrement: true, primaryKey: true)
let b = Column("b")
let tableName = tableInsert3
}
class MyTable4 : Table {
let a = Column("a", String.self)
let b = Column("b", Int64.self, autoIncrement:true, primaryKey: true)
let tableName = tableInsert4
}
func testInsert() {
let t = MyTable()
let t2 = MyTable2()
let pool = CommonUtils.sharedInstance.getConnectionPool()
performTest(asyncTasks: { expectation in
pool.getConnection() { connection, error in
guard let connection = connection else {
XCTFail("Failed to get connection")
return
}
cleanUp(table: t.tableName, connection: connection) { result in
cleanUp(table: t2.tableName, connection: connection) { result in
executeRawQuery("CREATE TABLE \"" + t.tableName + "\" (a varchar(40), b integer)", connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "CREATE TABLE failed")
XCTAssertNil(result.asError, "Error in CREATE TABLE: \(result.asError!)")
executeRawQuery("CREATE TABLE \"" + t2.tableName + "\" (a varchar(40), b integer)", connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "CREATE TABLE failed")
XCTAssertNil(result.asError, "Error in CREATE TABLE: \(result.asError!)")
let i1 = Insert(into: t, values: "apple", 10)
executeQuery(query: i1, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
let i2 = Insert(into: t, valueTuples: (t.a, "apricot"), (t.b, "3"))
.suffix("RETURNING *")
executeQuery(query: i2, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
XCTAssertNotNil(result.asResultSet, "INSERT returned no rows")
XCTAssertNotNil(rows, "INSERT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 1, "INSERT returned wrong number of rows: \(rows!.count) instead of 1")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles[0], "a", "Wrong column name: \(titles[0]) instead of a")
XCTAssertEqual(titles[1], "b", "Wrong column name: \(titles[1]) instead of b")
XCTAssertEqual(rows![0][0]! as! String, "apricot", "Wrong value in row 0 column 0")
XCTAssertEqual(rows![0][1]! as! Int32, 3, "Wrong value in row 1 column 0")
let i3 = Insert(into: t, columns: [t.a, t.b], values: ["banana", 17])
.suffix("RETURNING b")
executeQuery(query: i3, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
XCTAssertNotNil(result.asResultSet, "INSERT returned no rows")
XCTAssertNotNil(rows, "INSERT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 1, "INSERT returned wrong number of rows: \(rows!.count) instead of 1")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles[0], "b", "Wrong column name: \(titles[0]) instead of b")
XCTAssertEqual(titles.count, 1, "Wrong number of columns: \(titles.count) instead of 1")
XCTAssertEqual(rows![0][0]! as! Int32, 17, "Wrong value in row 0 column 0")
let i4 = Insert(into: t, rows: [["apple", 17], ["banana", -7], ["banana", 27]])
.suffix("RETURNING b")
executeQuery(query: i4, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
XCTAssertNotNil(result.asResultSet, "INSERT returned no rows")
XCTAssertNotNil(rows, "INSERT returned no rows")
XCTAssertEqual(rows!.count, 3, "INSERT returned wrong number of rows: \(rows!.count) instead of 3")
let i5 = Insert(into: t, rows: [["apple", 5], ["banana", 10], ["banana", 3]])
.suffix("RETURNING b, a")
executeQuery(query: i5, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
XCTAssertNotNil(result.asResultSet, "INSERT returned no rows")
XCTAssertNotNil(rows, "INSERT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 3, "INSERT returned wrong number of rows: \(rows!.count) instead of 3")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles.count, 2, "Wrong number of columns: \(titles.count) instead of 2")
let i6 = Insert(into: t2, Select(from: t).where(t.a == "apple"))
.suffix("RETURNING *")
executeQuery(query: i6, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
XCTAssertNotNil(rows, "INSERT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 3, "INSERT returned wrong number of rows: \(rows!.count) instead of 3")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles.count, 2, "Wrong number of columns: \(titles.count) instead of 2")
let s1 = Select(from: t)
executeQuery(query: s1, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "SELECT failed")
XCTAssertNil(result.asError, "Error in SELECT: \(result.asError!)")
XCTAssertNotNil(rows, "SELECT returned no rows")
XCTAssertEqual(rows!.count, 9, "INSERT returned wrong number of rows: \(rows!.count) instead of 9")
let dropT = Raw(query: "DROP TABLE", table: t)
executeQuery(query: dropT, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "DROP TABLE failed")
XCTAssertNil(result.asError, "Error in DELETE: \(result.asError!)")
expectation.fulfill()
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
})
}
func testInsertID() {
let t3 = MyTable3()
let pool = CommonUtils.sharedInstance.getConnectionPool()
performTest(asyncTasks: { expectation in
pool.getConnection() { connection, error in
guard let connection = connection else {
XCTFail("Failed to get connection")
return
}
cleanUp(table: t3.tableName, connection: connection) { result in
executeRawQuery("CREATE TABLE \"" + t3.tableName + "\" (a SERIAL PRIMARY KEY, b integer)", connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "CREATE TABLE failed")
XCTAssertNil(result.asError, "Error in CREATE TABLE: \(result.asError!)")
let i7 = Insert(into: t3, valueTuples: [(t3.b, 5)], returnID: true)
executeQuery(query: i7, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
XCTAssertNotNil(result.asResultSet, "INSERT returned no rows")
XCTAssertNotNil(rows, "INSERT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 1, "INSERT returned wrong number of rows: \(rows!.count) instead of 1")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles.count, 1, "Wrong number of columns: \(titles.count) instead of 1")
let dropT3 = Raw(query: "DROP TABLE", table: t3)
executeQuery(query: dropT3, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "DROP TABLE failed")
XCTAssertNil(result.asError, "Error in DELETE: \(result.asError!)")
expectation.fulfill()
}
}
}
}
}
}
})
}
func testInsertNil() {
let t = MyTable4()
let pool = CommonUtils.sharedInstance.getConnectionPool()
performTest(asyncTasks: { expectation in
pool.getConnection { connection, error in
guard let connection = connection else {
XCTFail("Failed to get connection")
return
}
cleanUp(table: t.tableName, connection: connection) { result in
executeRawQuery("CREATE TABLE \"" + t.tableName + "\" (a TEXT, b SERIAL PRIMARY KEY)", connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "CREATE TABLE failed")
XCTAssertNil(result.asError, "Error in CREATE TABLE: \(result.asError!)")
let optionalString: String? = nil
let insertNil = Insert(into: t, valueTuples: [(t.a, optionalString as Any)])
executeQuery(query: insertNil, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
let select = Select(from: t)
executeQuery(query: select, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "SELECT failed")
XCTAssertNil(result.asError, "Error in SELECT: \(result.asError!)")
XCTAssertNotNil(rows, "SELECT returned no rows")
XCTAssertEqual(rows?.count, 1, "SELECT returned wrong number of rows: \(String(describing: rows?.count)) instead of 1")
XCTAssertNil(rows?[0][0], "Expected value `nil` not found, returned: \(String(describing: rows?[0][0])) instead")
let drop = Raw(query: "DROP TABLE", table: t)
executeQuery(query: drop, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "DROP TABLE failed")
XCTAssertNil(result.asError, "Error in DELETE: \(result.asError!)")
expectation.fulfill()
}
}
}
}
}
}
})
}
}
| 62.925676 | 175 | 0.424299 |
28cb4586d6cca38bc70c012337656697126464bf | 420 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// GeoRegionProtocol is geographical region.
public protocol GeoRegionProtocol : ProxyOnlyResourceProtocol {
var properties: GeoRegionPropertiesProtocol? { get set }
}
| 42 | 96 | 0.771429 |
cc44e8858e792206826ec6582ddc58ab608718e3 | 601 | import HotKey
class Keys {
private static let keysToSkip = [
Key.home,
Key.pageUp,
Key.pageDown,
Key.end,
Key.leftArrow,
Key.rightArrow,
Key.downArrow,
Key.upArrow,
Key.space,
Key.return,
Key.escape,
Key.tab,
Key.f1,
Key.f2,
Key.f3,
Key.f4,
Key.f5,
Key.f6,
Key.f7,
Key.f8,
Key.f9,
Key.f10,
Key.f11,
Key.f12,
Key.f13,
Key.f14,
Key.f15,
Key.f16,
Key.f17,
Key.f18,
Key.f19,
]
static func shouldPassThrough(_ key: Key) -> Bool {
return keysToSkip.contains(key)
}
}
| 14.309524 | 53 | 0.547421 |
f8f5f628312568f184f36b809a8e0b5b3471e885 | 1,957 | //
// AKStereoFieldLimiterAudioUnit.swift
// AudioKit
//
// Created by Andrew Voelkel, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
import AVFoundation
public class AKStereoFieldLimiterAudioUnit: AKAudioUnitBase {
func setParameter(_ address: AKStereoFieldLimiterParameter, value: Double) {
setParameterWithAddress(AUParameterAddress(address.rawValue), value: Float(value))
}
func setParameterImmediately(_ address: AKStereoFieldLimiterParameter, value: Double) {
setParameterImmediatelyWithAddress(AUParameterAddress(address.rawValue), value: Float(value))
}
var amount: Double = 1.0 {
didSet { setParameter(.amount, value: amount) }
}
var rampDuration: Double = 0.0 {
didSet { setParameter(.rampDuration, value: rampDuration) }
}
public override func initDSP(withSampleRate sampleRate: Double,
channelCount count: AVAudioChannelCount) -> AKDSPRef {
return createStereoFieldLimiterDSP(Int32(count), sampleRate)
}
public override init(componentDescription: AudioComponentDescription,
options: AudioComponentInstantiationOptions = []) throws {
try super.init(componentDescription: componentDescription, options: options)
let flags: AudioUnitParameterOptions = [.flag_IsReadable, .flag_IsWritable, .flag_CanRamp]
let amount = AUParameterTree.createParameter(
withIdentifier: "amount",
name: "Limiting amount",
address: AUParameterAddress(0),
min: 0.0,
max: 1.0,
unit: .generic,
unitName: nil,
flags: flags,
valueStrings: nil,
dependentParameters: nil)
setParameterTree(AUParameterTree.createTree(withChildren: [amount]))
amount.value = 1.0
}
public override var canProcessInPlace: Bool { return true }
}
| 34.333333 | 101 | 0.672969 |
0175fe31a6e5a94c671def24c871c662abc49316 | 2,462 | //
// RecipesService.swift
// Recipes
//
// Created by Khoa Pham on 24.02.2018.
// Copyright © 2018 Khoa Pham. All rights reserved.
//
import Foundation
final class RecipesService {
private let baseUrl = URL(string: "https://food2fork.com/api")!
private let networking: Networking
init(networking: Networking) {
self.networking = networking
}
/// Fetch recipes with highest rating
///
/// - Parameter completion: Called when operation finishes
func fetchTopRating(completion: @escaping ([Recipe]) -> Void) {
let resource = Resource(url: baseUrl, path: "search", parameters: [
"key": AppConfig.apiKey
])
_ = networking.fetch(resource: resource, completion: { data in
DispatchQueue.main.async {
completion(data.flatMap({ RecipeListResponse.make(data: $0)?.recipes }) ?? [])
}
})
}
/// Fetch single entity based on recipe id
///
/// - Parameters:
/// - recipeId: The recipe id
/// - completion: Called when operation finishes
func fetch(recipeId: String, completion: @escaping (Recipe?) -> Void) {
let resource = Resource(url: baseUrl, path: "get", parameters: [
"key": AppConfig.apiKey,
"rId": recipeId
])
_ = networking.fetch(resource: resource, completion: { data in
DispatchQueue.main.async {
completion(data.flatMap({ RecipeResponse.make(data: $0)?.recipe }))
}
})
}
/// Search recipes based on query
///
/// - Parameters:
/// - query: The search query
/// - completion: Called when operation finishes
/// - Returns: The network task
@discardableResult func search(query: String, completion: @escaping ([Recipe]) -> Void) -> URLSessionTask? {
let resource = Resource(url: baseUrl, path: "search", parameters: [
"key": AppConfig.apiKey,
"q": query
])
return networking.fetch(resource: resource, completion: { data in
DispatchQueue.main.async {
completion(data.flatMap({ RecipeListResponse.make(data: $0)?.recipes }) ?? [])
}
})
}
}
private class RecipeListResponse: Decodable {
let count: Int
let recipes: [Recipe]
static func make(data: Data) -> RecipeListResponse? {
return try? JSONDecoder().decode(RecipeListResponse.self, from: data)
}
}
private class RecipeResponse: Decodable {
let recipe: Recipe
static func make(data: Data) -> RecipeResponse? {
return try? JSONDecoder().decode(RecipeResponse.self, from: data)
}
}
| 27.977273 | 110 | 0.652721 |
c19cf0a5700ca35d5d50570bae6cefce4ea99ac2 | 2,076 | //
// UserDefaultsManager.swift
// ZeroMessger
//
// Created by Sandeep Mukherjee on 8/13/20.
// Copyright © 2020 Sandeep Mukherjee. All rights reserved.
//
import UIKit
import Firebase
let userDefaults = UserDefaultsManager()
class UserDefaultsManager: NSObject {
fileprivate let defaults = UserDefaults.standard
let authVerificationID = "authVerificationID"
let changeNumberAuthVerificationID = "ChangeNumberAuthVerificationID"
let selectedTheme = "SelectedTheme"
let hasRunBefore = "hasRunBefore"
let biometricType = "biometricType"
let inAppNotifications = "In-AppNotifications"
let inAppSounds = "In-AppSounds"
let inAppVibration = "In-AppVibration"
let biometricalAuth = "BiometricalAuth"
//updating
func updateObject(for key: String, with data: Any?) {
defaults.set(data, forKey: key)
defaults.synchronize()
}
//
//removing
func removeObject(for key: String) {
defaults.removeObject(forKey: key)
}
//
//current state
func currentStringObjectState(for key: String) -> String? {
return defaults.string(forKey: key)
}
func currentIntObjectState(for key: String) -> Int? {
return defaults.integer(forKey: key)
}
func currentBoolObjectState(for key: String) -> Bool {
return defaults.bool(forKey: key)
}
//
// other
func configureInitialLaunch() {
if defaults.bool(forKey: hasRunBefore) != true {
do { try Auth.auth().signOut() } catch {}
updateObject(for: hasRunBefore, with: true)
}
setDefaultsForSettings()
}
func setDefaultsForSettings() {
if defaults.object(forKey: inAppNotifications) == nil {
updateObject(for: inAppNotifications, with: true)
}
if defaults.object(forKey: inAppSounds) == nil {
updateObject(for: inAppSounds, with: true)
}
if defaults.object(forKey: inAppVibration) == nil {
updateObject(for: inAppVibration, with: true)
}
if defaults.object(forKey: biometricalAuth) == nil {
updateObject(for: biometricalAuth, with: false)
}
}
}
| 24.714286 | 71 | 0.686898 |
1d1ec5e83b943bd484d27f00c868f171a54d5f5a | 5,645 | //
// RankingGameScene.swift
// Pazudora
//
// Created by 鈴木 雅也 on 2018/03/27.
// Copyright © 2018年 masamon. All rights reserved.
//
import Foundation
import SpriteKit
import GameplayKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import SwiftyJSON
class RankingGameScene : SKScene {
//Firebase
var ref:DatabaseReference!
var number1 = 0
var number2 = 0
var number3 = 0
var number4 = 0
var number5 = 0
override func didMove(to view: SKView) {
// 「Start」を表示。
let startLabel = SKLabelNode(fontNamed: "Copperplate")
startLabel.text = "戻る"
startLabel.fontSize = 50
startLabel.position = CGPoint(x: self.frame.midX, y: -400)
startLabel.name = "StartBack"
// 1位の表示使う
let label1 = SKLabelNode(fontNamed: "Copperplate")
label1.fontSize = 50
label1.position = CGPoint(x: self.frame.midX, y: 400)
label1.name = "one"
// 2位の表示使う
let label2 = SKLabelNode(fontNamed: "Copperplate")
label2.fontSize = 50
label2.position = CGPoint(x: self.frame.midX, y: 300)
label2.name = "second"
// 3位の表示使う
let label3 = SKLabelNode(fontNamed: "Copperplate")
label3.fontSize = 50
label3.position = CGPoint(x: self.frame.midX, y: 200)
label3.name = "third"
// 4位の表示使う
let label4 = SKLabelNode(fontNamed: "Copperplate")
label4.fontSize = 50
label4.position = CGPoint(x: self.frame.midX, y: 100)
label4.name = "four"
// 5位の表示使う
let label5 = SKLabelNode(fontNamed: "Copperplate")
label5.fontSize = 50
label5.position = CGPoint(x: self.frame.midX, y: 0)
label5.name = "five"
//firebase
ref = Database.database().reference()
//データが欲しい childAdded
ref.child("data").observe(.value , with: { (snapshot: DataSnapshot) in
//JSON形式でもらいたい オートIDから
let getjson = JSON(snapshot.value as? [String : AnyObject] ?? [:])
//データが0件の場合何もしない
if getjson.count == 0 { return }
//firebaseのデータベースにアクセス。大きさ順に並べる
for (key, val) in getjson.dictionaryValue {
if(getjson[key]["number"].stringValue.i! >= self.number1){
print("ranking1ok")
self.number5 = self.number4
self.number4 = self.number3
self.number3 = self.number2
self.number2 = self.number1
self.number1 = getjson[key]["number"].stringValue.i!
print(self.number1,"self.number1")
}
else if( getjson[key]["number"].stringValue.i! < self.number1 && getjson[key]["number"].stringValue.i! >= self.number2){
self.number5 = self.number4
self.number4 = self.number3
self.number3 = self.number2
self.number2 = getjson[key]["number"].stringValue.i!
}
else if(getjson[key]["number"].stringValue.i! < self.number2 && getjson[key]["number"].stringValue.i! >= self.number3){
self.number5 = self.number4
self.number4 = self.number3
self.number3 = getjson[key]["number"].stringValue.i!
}
else if(getjson[key]["number"].stringValue.i! < self.number3 && getjson[key]["number"].stringValue.i! >= self.number4){
self.number5 = self.number4
self.number4 = getjson[key]["number"].stringValue.i!
}
else if(getjson[key]["number"].stringValue.i! < self.number4 && getjson[key]["number"].stringValue.i! >= self.number5){
self.number5 = getjson[key]["number"].stringValue.i!
}
}
})
//ソート後textに代入
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
label1.text = "1位" + " " + String(self.number1)
print(String(self.number1),"String(self.number1)")
label2.text = "2位" + " " + String(self.number2)
label3.text = "3位" + " " + String(self.number3)
label4.text = "4位" + " " + String(self.number4)
label5.text = "5位" + " " + String(self.number5)
//labelをadd
self.addChild(label1)
self.addChild(label2)
self.addChild(label3)
self.addChild(label4)
self.addChild(label5)
self.addChild(startLabel)
}
}
// 「Start」ラベルをタップしたら、GameSceneへ遷移させる。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var touchedNode = SKNode()
print("TouchBeganOk")
//押したnodeをfor文の中で特定する
for touch in touches {
let location = touch.location(in: self)
touchedNode = self.atPoint(location)
}
if (touchedNode.name != nil) {
if touchedNode.name == "StartBack" {
let newScene = GameScene(fileNamed: "StartGameScene")
newScene?.scaleMode = SKSceneScaleMode.aspectFill
self.view!.presentScene(newScene)
}
}
}
}
| 32.819767 | 136 | 0.517272 |
8acf420e1e8660bf1feb682ed77b77c0f037fa2e | 4,790 | //
// PitchTests.swift
// MusicNotationCore
//
// Created by Rob Hudson on 7/29/16.
// Copyright © 2016 Kyle Sherman. All rights reserved.
//
import MusicNotationCoreMac
import XCTest
class PitchTests: XCTestCase {
func testPitch1() {
let pitch = SpelledPitch(noteLetter: .c, octave: .octave3)
XCTAssertTrue(pitch.debugDescription == "c3")
}
func testPitch2() {
let pitch = SpelledPitch(noteLetter: .g, accidental: .sharp, octave: .octave6)
XCTAssertTrue(pitch.debugDescription == "g♯6")
}
func testPitch3() {
let pitch = SpelledPitch(noteLetter: .e, accidental: .flat, octave: .octave2)
XCTAssertTrue(pitch.debugDescription == "e♭2")
}
func testPitch4() {
let pitch = SpelledPitch(noteLetter: .a, accidental: .natural, octave: .octave4)
XCTAssertTrue(pitch.debugDescription == "a4")
}
func testPitch5() {
let pitch = SpelledPitch(noteLetter: .b, accidental: .doubleSharp, octave: .octave5)
XCTAssertTrue(pitch.debugDescription == "b𝄪5")
}
func testPitch6() {
let pitch = SpelledPitch(noteLetter: .f, accidental: .doubleFlat, octave: .octave7)
XCTAssertTrue(pitch.debugDescription == "f𝄫7")
}
// MARK: - ==
// MARK: Failures
func testNotEqual() {
let pitch1 = SpelledPitch(noteLetter: .b, accidental: .flat, octave: .octave5)
let pitch2 = SpelledPitch(noteLetter: .b, accidental: .flat, octave: .octave4)
XCTAssertNotEqual(pitch1, pitch2)
}
// MARK: Successes
func testEqual() {
let pitch1 = SpelledPitch(noteLetter: .d, accidental: .sharp, octave: .octave1)
let pitch2 = SpelledPitch(noteLetter: .d, accidental: .sharp, octave: .octave1)
XCTAssertEqual(pitch1, pitch2)
}
// MARK: - MIDI numbers
// MARK: Successes
func testRidiculouslyLowNote() {
let pitch = SpelledPitch(noteLetter: .c, accidental: .natural, octave: .octaveNegative1)
XCTAssertEqual(pitch.midiNoteNumber, 0)
}
func testLowNote() {
let pitch = SpelledPitch(noteLetter: .f, accidental: .sharp, octave: .octave1)
XCTAssertEqual(pitch.midiNoteNumber, 30)
}
func testMidRangeNote() {
let pitch = SpelledPitch(noteLetter: .d, octave: .octave4)
XCTAssertEqual(pitch.midiNoteNumber, 62)
}
func testHighNote() {
let pitch = SpelledPitch(noteLetter: .c, accidental: .flat, octave: .octave8)
XCTAssertEqual(pitch.midiNoteNumber, 107)
}
// MARK: - isEnharmonic(with:)
// MARK: Failures
func testDifferentAccidentals() {
let pitch1 = SpelledPitch(noteLetter: .d, accidental: .flat, octave: .octave1)
let pitch2 = SpelledPitch(noteLetter: .d, accidental: .sharp, octave: .octave1)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertFalse(pitch1.isEnharmonic(with: pitch2))
}
func testSamePitchDifferentOctaves() {
let pitch1 = SpelledPitch(noteLetter: .e, accidental: .natural, octave: .octave5)
let pitch2 = SpelledPitch(noteLetter: .e, accidental: .natural, octave: .octave6)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertFalse(pitch1.isEnharmonic(with: pitch2))
}
func testEnharmonicPitchDifferentOctaves() {
let pitch1 = SpelledPitch(noteLetter: .f, accidental: .doubleSharp, octave: .octave2)
let pitch2 = SpelledPitch(noteLetter: .g, accidental: .natural, octave: .octave5)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertFalse(pitch1.isEnharmonic(with: pitch2))
}
// MARK: Successes
func testSamePitchIsEnharmonic() {
let pitch1 = SpelledPitch(noteLetter: .g, accidental: .natural, octave: .octave6)
let pitch2 = SpelledPitch(noteLetter: .g, accidental: .natural, octave: .octave6)
XCTAssertEqual(pitch1, pitch2)
XCTAssertTrue(pitch1.isEnharmonic(with: pitch2))
// Transitive property
XCTAssertTrue(pitch2.isEnharmonic(with: pitch1))
}
func testEnharmonicNotEquatable() {
let pitch1 = SpelledPitch(noteLetter: .a, accidental: .flat, octave: .octave3)
let pitch2 = SpelledPitch(noteLetter: .g, accidental: .sharp, octave: .octave3)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertTrue(pitch1.isEnharmonic(with: pitch2))
}
func testNaturalAndFlat() {
let pitch1 = SpelledPitch(noteLetter: .e, accidental: .natural, octave: .octave4)
let pitch2 = SpelledPitch(noteLetter: .f, accidental: .flat, octave: .octave4)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertTrue(pitch1.isEnharmonic(with: pitch2))
}
func testDoubleFlat() {
let pitch1 = SpelledPitch(noteLetter: .b, accidental: .doubleFlat, octave: .octave2)
let pitch2 = SpelledPitch(noteLetter: .a, octave: .octave2)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertTrue(pitch1.isEnharmonic(with: pitch2))
}
func testDifferentOctaveNumbers() {
let pitch1 = SpelledPitch(noteLetter: .b, accidental: .sharp, octave: .octave6)
let pitch2 = SpelledPitch(noteLetter: .c, accidental: .natural, octave: .octave7)
XCTAssertNotEqual(pitch1, pitch2)
XCTAssertTrue(pitch1.isEnharmonic(with: pitch2))
}
}
| 29.386503 | 90 | 0.73048 |
465a8bc6c7fb8f014e883b802cb4010cc1495c41 | 6,541 | import ComposableArchitecture
import Foundation
import ReactiveSwift
import SwiftUI
private let readMe = """
This screen demonstrates how one can share system-wide dependencies across many features with \
very little work. The idea is to create a `SystemEnvironment` generic type that wraps an \
environment, and then implement dynamic member lookup so that you can seamlessly use the \
dependencies in both environments.
Then, throughout your application you can wrap your environments in the `SystemEnvironment` \
to get instant access to all of the shared dependencies. Some good candidates for dependencies \
to share are things like date initializers, schedulers (especially `DispatchQueue.main`), `UUID` \
initializers, and any other dependency in your application that you want every reducer to have \
access to.
"""
struct MultipleDependenciesState: Equatable {
var alert: AlertState<MultipleDependenciesAction>?
var dateString: String?
var fetchedNumberString: String?
var isFetchInFlight = false
var uuidString: String?
}
enum MultipleDependenciesAction: Equatable {
case alertButtonTapped
case alertDelayReceived
case alertDismissed
case dateButtonTapped
case fetchNumberButtonTapped
case fetchNumberResponse(Int)
case uuidButtonTapped
}
struct MultipleDependenciesEnvironment {
var fetchNumber: () -> Effect<Int, Never>
}
let multipleDependenciesReducer = Reducer<
MultipleDependenciesState,
MultipleDependenciesAction,
SystemEnvironment<MultipleDependenciesEnvironment>
> { state, action, environment in
switch action {
case .alertButtonTapped:
return Effect(value: .alertDelayReceived)
.delay(1, on: environment.mainQueue)
case .alertDelayReceived:
state.alert = .init(title: .init("Here's an alert after a delay!"))
return .none
case .alertDismissed:
state.alert = nil
return .none
case .dateButtonTapped:
state.dateString = "\(environment.date())"
return .none
case .fetchNumberButtonTapped:
state.isFetchInFlight = true
return environment.fetchNumber()
.map(MultipleDependenciesAction.fetchNumberResponse)
case let .fetchNumberResponse(number):
state.isFetchInFlight = false
state.fetchedNumberString = "\(number)"
return .none
case .uuidButtonTapped:
state.uuidString = "\(environment.uuid())"
return .none
}
}
struct MultipleDependenciesView: View {
let store: Store<MultipleDependenciesState, MultipleDependenciesAction>
var body: some View {
WithViewStore(self.store) { viewStore in
Form {
Section(
header: Text(template: readMe, .caption)
) {
EmptyView()
}
Section(
header: Text(
template: """
The actions below make use of the dependencies in the `SystemEnvironment`.
""", .caption)
) {
HStack {
Button("Date") { viewStore.send(.dateButtonTapped) }
viewStore.dateString.map(Text.init)
}
HStack {
Button("UUID") { viewStore.send(.uuidButtonTapped) }
viewStore.uuidString.map(Text.init)
}
Button("Delayed Alert") { viewStore.send(.alertButtonTapped) }
.alert(self.store.scope(state: \.alert), dismiss: .alertDismissed)
}
Section(
header: Text(
template: """
The actions below make use of the custom environment for this screen, which holds a \
dependency for fetching a random number.
""", .caption)
) {
HStack {
Button("Fetch Number") { viewStore.send(.fetchNumberButtonTapped) }
viewStore.fetchedNumberString.map(Text.init)
Spacer()
if viewStore.isFetchInFlight {
ProgressView()
}
}
}
}
.buttonStyle(.borderless)
}
.navigationBarTitle("System Environment")
}
}
struct MultipleDependenciesView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
MultipleDependenciesView(
store: Store(
initialState: .init(),
reducer: multipleDependenciesReducer,
environment: .live(
environment: MultipleDependenciesEnvironment(
fetchNumber: {
Effect(value: Int.random(in: 1...1_000))
.delay(1, on: QueueScheduler.main)
}
)
)
)
)
}
}
}
@dynamicMemberLookup
struct SystemEnvironment<Environment> {
var date: () -> Date
var environment: Environment
var mainQueue: DateScheduler
var uuid: () -> UUID
subscript<Dependency>(
dynamicMember keyPath: WritableKeyPath<Environment, Dependency>
) -> Dependency {
get { self.environment[keyPath: keyPath] }
set { self.environment[keyPath: keyPath] = newValue }
}
/// Creates a live system environment with the wrapped environment provided.
///
/// - Parameter environment: An environment to be wrapped in the system environment.
/// - Returns: A new system environment.
static func live(environment: Environment) -> Self {
Self(
date: Date.init,
environment: environment,
mainQueue: QueueScheduler.main,
uuid: UUID.init
)
}
/// Transforms the underlying wrapped environment.
func map<NewEnvironment>(
_ transform: @escaping (Environment) -> NewEnvironment
) -> SystemEnvironment<NewEnvironment> {
.init(
date: self.date,
environment: transform(self.environment),
mainQueue: self.mainQueue,
uuid: self.uuid
)
}
}
#if DEBUG
import XCTestDynamicOverlay
extension SystemEnvironment {
static func failing(
date: @escaping () -> Date = {
XCTFail("date dependency is unimplemented.")
return Date()
},
environment: Environment,
mainQueue: DateScheduler = FailingScheduler(),
uuid: @escaping () -> UUID = {
XCTFail("UUID dependency is unimplemented.")
return UUID()
}
) -> Self {
Self(
date: date,
environment: environment,
mainQueue: mainQueue,
uuid: uuid
)
}
}
#endif
extension UUID {
/// A deterministic, auto-incrementing "UUID" generator for testing.
static var incrementing: () -> UUID {
var uuid = 0
return {
defer { uuid += 1 }
return UUID(uuidString: "00000000-0000-0000-0000-\(String(format: "%012x", uuid))")!
}
}
}
| 27.952991 | 100 | 0.652194 |
e81cfdd4c0e6490241427c91f65380da4c485a64 | 2,559 | //
// AmuseMenuView.swift
// DYZB
//
// Created by zhangzhifu on 2017/3/18.
// Copyright © 2017年 seemygo. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
// MARK: 定义属性
var groups : [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
// MARK: 控件属性
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
// MARK: 从xib中加载出来
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil {
return 0
}
let pageNum = (groups!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1. 取出cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
// 2. 给cell设置数据
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell : AmuseMenuViewCell, indexPath : IndexPath) {
// 1. 取出起始位置和终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
// 2. 判断越界问题
if endIndex > groups!.count - 1 {
endIndex = groups!.count - 1
}
// 3. 取出数据,并且赋值给cell
cell.groups = Array(groups![startIndex...endIndex])
}
}
extension AmuseMenuView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| 28.433333 | 125 | 0.640875 |
08f6e0f0277c15026a65dd8849a823dccb3a2818 | 5,609 | //
// Parsing.swift
// AudioStreamer
//
// Created by Syed Haris Ali on 1/6/18.
// Copyright © 2018 Ausome Apps LLC. All rights reserved.
//
import Foundation
import AVFoundation
/// The `Parsing` protocol represents a generic parser that can be used for converting binary data into audio packets.
public protocol Parsing: AnyObject {
// MARK: - Properties
/// The data format of the audio. This describes the sample rate, frames per packet, bytes per packet, etc. Previously we'd use an `AudioStreamBasicDescription`.
var dataFormat: AVAudioFormat? { get }
/// The total duration of the audio. For certain formats such as AAC or live streams this may be a guess or only equal to as many packets as have been processed.
var duration: TimeInterval? { get }
/// A `Bool` indicating whether all the audio packets have been parsed relative to the total packet count. This is optional where the default implementation will check if the total packets parsed (i.e. the count of `packets` property) is equal to the `totalPacketCount` property
var isParsingComplete: Bool { get }
/// An array of duples, each index presenting a parsed audio packet. For compressed formats each packet of data should contain a `AudioStreamPacketDescription`, which describes the start offset and length of the audio data)
var packets: [(Data, AudioStreamPacketDescription?)] { get }
/// The total number of frames (expressed in the data format)
var totalFrameCount: AVAudioFrameCount? { get }
/// The total packet count (expressed in the data format)
var totalPacketCount: AVAudioPacketCount? { get }
// MARK: - Methods
/// Given some data the parser should attempt to convert it into to audio packets.
///
/// - Parameter data: A `Data` instance representing some binary data corresponding to an audio stream.
func parse(data: Data) throws
/// Given a time this method will attempt to provide the corresponding audio frame representing that position.
///
/// - Parameter time: A `TimeInterval` representing the time
/// - Returns: An optional `AVAudioFramePosition` representing the frame's position relative to the time provided. If the `dataFormat`, total frame count, or duration is unknown then this will return nil.
func frameOffset(forTime time: TimeInterval) -> AVAudioFramePosition?
/// Given a frame this method will attempt to provide the corresponding audio packet representing that position.
///
/// - Parameter frame: An `AVAudioFrameCount` representing the desired frame
/// - Returns: An optional `AVAudioPacketCount` representing the packet the frame belongs to. If the `dataFormat` is unknown (not enough data has been provided) then this will return nil.
func packetOffset(forFrame frame: AVAudioFramePosition) -> AVAudioPacketCount?
/// Given a frame this method will attempt to provide the corresponding time relative to the duration representing that position.
///
/// - Parameter frame: An `AVAudioFrameCount` representing the desired frame
/// - Returns: An optional `TimeInterval` representing the time relative to the frame. If the `dataFormat`, total frame count, or duration is unknown then this will return nil.
func timeOffset(forFrame frame: AVAudioFrameCount) -> TimeInterval?
}
// Usually these methods are gonna be calculated using the same way everytime so here are the default implementations that should work 99% of the time relative to the properties defined.
extension Parsing {
public var duration: TimeInterval? {
guard let sampleRate = dataFormat?.sampleRate else {
return nil
}
guard let totalFrameCount = totalFrameCount else {
return nil
}
return TimeInterval(totalFrameCount) / TimeInterval(sampleRate)
}
public var totalFrameCount: AVAudioFrameCount? {
guard let framesPerPacket = dataFormat?.streamDescription.pointee.mFramesPerPacket else {
return nil
}
guard let totalPacketCount = totalPacketCount else {
return nil
}
return AVAudioFrameCount(totalPacketCount) * AVAudioFrameCount(framesPerPacket)
}
public var isParsingComplete: Bool {
guard let totalPacketCount = totalPacketCount else {
return false
}
return packets.count == totalPacketCount
}
public func frameOffset(forTime time: TimeInterval) -> AVAudioFramePosition? {
guard let _ = dataFormat?.streamDescription.pointee,
let frameCount = totalFrameCount,
let duration = duration else {
return nil
}
let ratio = time / duration
return AVAudioFramePosition(Double(frameCount) * ratio)
}
public func packetOffset(forFrame frame: AVAudioFramePosition) -> AVAudioPacketCount? {
guard let framesPerPacket = dataFormat?.streamDescription.pointee.mFramesPerPacket else {
return nil
}
return AVAudioPacketCount(frame) / AVAudioPacketCount(framesPerPacket)
}
public func timeOffset(forFrame frame: AVAudioFrameCount) -> TimeInterval? {
guard let _ = dataFormat?.streamDescription.pointee,
let frameCount = totalFrameCount,
let duration = duration else {
return nil
}
return TimeInterval(frame) / TimeInterval(frameCount) * duration
}
}
| 44.165354 | 282 | 0.689249 |
23e064ce5c8001a68e8b5bc51542b5b5bbca7b6c | 2,848 | //
// UndoAvailableAlertController.swift
// NetNewsWire
//
// Created by Phil Viso on 9/29/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
import UIKit
protocol MarkAsReadAlertControllerSourceType {}
extension CGRect: MarkAsReadAlertControllerSourceType {}
extension UIView: MarkAsReadAlertControllerSourceType {}
extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {}
struct MarkAsReadAlertController {
static func confirm<T>(_ controller: UIViewController?,
coordinator: SceneCoordinator?,
confirmTitle: String,
sourceType: T,
cancelCompletion: (() -> Void)? = nil,
completion: @escaping () -> Void) where T: MarkAsReadAlertControllerSourceType {
guard let controller = controller, let coordinator = coordinator else {
completion()
return
}
if AppDefaults.confirmMarkAllAsRead {
let alertController = MarkAsReadAlertController.alert(coordinator: coordinator, confirmTitle: confirmTitle, cancelCompletion: cancelCompletion, sourceType: sourceType) { _ in
completion()
}
controller.present(alertController, animated: true)
} else {
completion()
}
}
private static func alert<T>(coordinator: SceneCoordinator,
confirmTitle: String,
cancelCompletion: (() -> Void)?,
sourceType: T,
completion: @escaping (UIAlertAction) -> Void) -> UIAlertController where T: MarkAsReadAlertControllerSourceType {
let title = NSLocalizedString("Mark As Read", comment: "Mark As Read")
let message = NSLocalizedString("You can turn this confirmation off in settings.",
comment: "You can turn this confirmation off in settings.")
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let settingsTitle = NSLocalizedString("Open Settings", comment: "Open Settings")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { _ in
cancelCompletion?()
}
let settingsAction = UIAlertAction(title: settingsTitle, style: .default) { _ in
coordinator.showSettings(scrollToArticlesSection: true)
}
let markAction = UIAlertAction(title: confirmTitle, style: .default, handler: completion)
alertController.addAction(markAction)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
if let barButtonItem = sourceType as? UIBarButtonItem {
alertController.popoverPresentationController?.barButtonItem = barButtonItem
}
if let rect = sourceType as? CGRect {
alertController.popoverPresentationController?.sourceRect = rect
}
if let view = sourceType as? UIView {
alertController.popoverPresentationController?.sourceView = view
}
return alertController
}
}
| 33.904762 | 177 | 0.741222 |
e47b4200814bc3827477e7852628849c543f694f | 1,027 | //
// ViewController.swift
// Lesson01
//
// Created by Igor on 22.10.2019.
// Copyright © 2019 IgorLab. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func gameButton(_ sender: Any) {
}
@IBAction func scoresButton(_ sender: Any) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "startGameSegue":
guard let destination = segue.destination as? GameViewController else { return }
destination.delegate = self
default:
break
}
}
}
extension ViewController: GameViewControllerDelegate {
func didFinishGame(withScore score: GameSession) {
print(score.rightAnswer)
Game.shared.gameSession = score
Game.shared.addResult()
Game.shared.clearGameSession()
}
}
| 23.340909 | 92 | 0.634859 |
d9d2c6f166332247119b8b2c596c8ed418ab0e91 | 1,752 | import Foundation
import azureSwiftRuntime
public protocol ServiceGetPublishingUser {
var headerParameters: [String: String] { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (UserProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.Service {
// GetPublishingUser gets publishing user
internal class GetPublishingUserCommand : BaseCommand, ServiceGetPublishingUser {
public var apiVersion = "2016-03-01"
public override init() {
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/providers/Microsoft.Web/publishingUsers/web"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(UserData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (UserProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: UserData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 38.086957 | 87 | 0.605594 |
28d86c617c5e6bba448863eb30f56fec9becc3ea | 12,353 | //
// Chunk.swift
//
//
// Created by Wang Wei on 2021/10/05.
//
import Foundation
import zlib
// A general chunk interface defines the minimal meaningful data block in APNG.
protocol Chunk {
static var name: [Character] { get }
func verifyCRC(payload: Data, checksum: Data) throws
init(data: Data) throws
}
// The chunks which may contain actual image data, such as IDAT or fdAT chunk.
protocol DataChunk: Chunk {
var dataPresentation: ImageDataPresentation { get }
}
extension DataChunk {
// Load the actual chunk data from the data chunk. If the data is already loaded and stored as `.data`, just return
// it. Otherwise, use the given `reader` to read it from a data block or file.
func loadData(with reader: Reader) throws -> Data {
switch dataPresentation {
case .data(let chunkData):
return chunkData
case .position(let offset, let length):
try reader.seek(toOffset: offset)
guard let chunkData = try reader.read(upToCount: length) else {
throw APNGKitError.decoderError(.corruptedData(atOffset: offset))
}
return chunkData
}
}
}
extension Chunk {
static var nameBytes: [UInt8] { name.map { $0.asciiValue! } }
static var nameString: String { String(name) }
func verifyCRC(payload: Data, checksum: Data) throws {
let calculated = Self.generateCRC(payload: payload.bytes)
guard calculated == checksum.bytes else {
throw APNGKitError.decoderError(.invalidChecksum)
}
}
static func generateCRC(payload: [Byte]) -> [Byte] {
var data = Self.nameBytes + payload
return UInt32(
crc32(uLong(0), &data, uInt(data.count))
).bigEndianBytes
}
}
/*
The IHDR chunk must appear FIRST. It contains:
Width: 4 bytes
Height: 4 bytes
Bit depth: 1 byte
Color type: 1 byte
Compression method: 1 byte
Filter method: 1 byte
Interlace method: 1 byte
*/
struct IHDR: Chunk {
enum ColorType: Byte {
case greyscale = 0
case trueColor = 2
case indexedColor = 3
case greyscaleWithAlpha = 4
case trueColorWithAlpha = 6
var componentsPerPixel: Int {
switch self {
case .greyscale: return 1
case .trueColor: return 3
case .indexedColor: return 1
case .greyscaleWithAlpha: return 2
case .trueColorWithAlpha: return 4
}
}
}
static let name: [Character] = ["I", "H", "D", "R"]
static let expectedPayloadLength = 13
private(set) var width: Int
private(set) var height: Int
let bitDepth: Byte
let colorType: ColorType
let compression: Byte
let filterMethod: Byte
let interlaceMethod: Byte
init(data: Data) throws {
guard data.count == IHDR.expectedPayloadLength else {
throw APNGKitError.decoderError(.wrongChunkData(name: Self.nameString, data: data))
}
width = data[0...3].intValue
height = data[4...7].intValue
bitDepth = data[8]
guard let c = ColorType(rawValue: data[9]) else {
throw APNGKitError.decoderError(.wrongChunkData(name: Self.nameString, data: data))
}
colorType = c
compression = data[10]
filterMethod = data[11]
interlaceMethod = data[12]
}
/// Returns a new `IHDR` chunk with `width` and `height` updated.
func updated(width: Int, height: Int) -> IHDR {
var result = self
result.width = width
result.height = height
return result
}
func encode() throws -> Data {
var data = Data(capacity: 4 /* length bytes */ + IHDR.name.count + IHDR.expectedPayloadLength + 4 /* crc bytes */)
data.append(IHDR.expectedPayloadLength.fourBytesData)
data.append(contentsOf: Self.nameBytes)
var payload = Data(capacity: IHDR.expectedPayloadLength)
payload.append(width.fourBytesData)
payload.append(height.fourBytesData)
payload.append(bitDepth)
payload.append(colorType.rawValue)
payload.append(compression)
payload.append(filterMethod)
payload.append(interlaceMethod)
data.append(payload)
data.append(contentsOf: Self.generateCRC(payload: payload.bytes))
return data
}
}
/*
The `acTL` chunk is an ancillary chunk as defined in the PNG Specification. It must appear before the first `IDAT`
chunk within a valid PNG stream.
The `acTL` chunk contains:
byte
0 num_frames (unsigned int) Number of frames
4 num_plays (unsigned int) Number of times to loop this APNG. 0 indicates infinite looping.
*/
struct acTL: Chunk {
static let name: [Character] = ["a", "c", "T", "L"]
let numberOfFrames: Int
let numberOfPlays: Int
init(data: Data) throws {
guard data.count == 8 else {
throw APNGKitError.decoderError(.wrongChunkData(name: Self.nameString, data: data))
}
self.numberOfFrames = data[0...3].intValue
self.numberOfPlays = data[4...7].intValue
}
}
struct IDAT: DataChunk {
static let name: [Character] = ["I", "D", "A", "T"]
let dataPresentation: ImageDataPresentation
init(data: Data) {
self.dataPresentation = .data(data)
}
init(offset: UInt64, length: Int) {
self.dataPresentation = .position(offset: offset, length: length)
}
static func encode(data: Data) -> Data {
data.count.fourBytesData + Self.nameBytes + data + Self.generateCRC(payload: data.bytes)
}
}
enum ImageDataPresentation {
case data(Data)
case position(offset: UInt64, length: Int)
}
/**
The `fcTL` chunk is an ancillary chunk as defined in the PNG Specification. It must appear before the `IDAT` or
`fdAT` chunks of the frame to which it applies.
byte
0 sequence_number (unsigned int) Sequence number of the animation chunk, starting from 0
4 width (unsigned int) Width of the following frame
8 height (unsigned int) Height of the following frame
12 x_offset (unsigned int) X position at which to render the following frame
16 y_offset (unsigned int) Y position at which to render the following frame
20 delay_num (unsigned short) Frame delay fraction numerator
22 delay_den (unsigned short) Frame delay fraction denominator
24 dispose_op (byte) Type of frame area disposal to be done after rendering this frame
25 blend_op (byte) Type of frame area rendering for this frame
*/
public struct fcTL: Chunk {
/**
`dispose_op` specifies how the output buffer should be changed at the end of the delay
(before rendering the next frame).
value
0 APNG_DISPOSE_OP_NONE
1 APNG_DISPOSE_OP_BACKGROUND
2 APNG_DISPOSE_OP_PREVIOUS
*/
public enum DisposeOp: Byte {
case none = 0
case background = 1
case previous = 2
}
/**
`blend_op` specifies whether the frame is to be alpha blended into the current output buffer
content, or whether it should completely replace its region in the output buffer.
value
0 APNG_BLEND_OP_SOURCE
1 APNG_BLEND_OP_OVER
*/
public enum BlendOp: Byte {
case source = 0
case over = 1
}
static let name: [Character] = ["f", "c", "T", "L"]
/// The `fcTL` and `fdAT` chunks have a 4 byte sequence number. Both chunk types share the sequence. The purpose of
/// this number is to detect (and optionally correct) sequence errors in an Animated PNG, since the PNG specification
/// does not impose ordering restrictions on ancillary chunks.
///
/// The first `fcTL` chunk must contain sequence number 0, and the sequence numbers in the remaining `fcTL` and `fdAT`
/// chunks must be in order, with no gaps or duplicates.
public let sequenceNumber: Int
/// Width of the frame by pixel.
public let width: Int
/// Height of the frame by pixel.
public let height: Int
/// X offset of the frame on the canvas by pixel. From left edge.
public let xOffset: Int
/// Y offset of the frame on the canvas by pixel. From top edge.
public let yOffset: Int
// The `delay_num` and `delay_den` parameters together specify a fraction indicating the time to display the current
// frame, in seconds. If the denominator is 0, it is to be treated as if it were 100 (that is, `delay_num` then
// specifies 1/100ths of a second). If the the value of the numerator is 0 the decoder should render the next frame
// as quickly as possible, though viewers may impose a reasonable lower bound.
/// Numerator part of the frame delay. If 0, this frame should be skipped if possible and the next frame should be
/// rendered as quickly as possible.
public let delayNumerator: Int
/// Denominator part of the frame delay. If 0, use 100.
public let delayDenominator: Int
/// Specifies how the output buffer should be changed at the end of the delay.
public let disposeOp: DisposeOp
/// Specifies whether the frame is to be alpha blended into the current output buffer
/// content, or whether it should completely replace its region in the output buffer.
public let blendOp: BlendOp
init(data: Data) throws {
guard data.count == 26 else {
throw APNGKitError.decoderError(.wrongChunkData(name: Self.nameString, data: data))
}
self.sequenceNumber = data[0...3].intValue
self.width = data[4...7].intValue
self.height = data[8...11].intValue
self.xOffset = data[12...15].intValue
self.yOffset = data[16...19].intValue
self.delayNumerator = data[20...21].intValue
self.delayDenominator = data[22...23].intValue
self.disposeOp = DisposeOp(rawValue: data[24]) ?? .background
self.blendOp = BlendOp(rawValue: data[25]) ?? .source
}
/// Duration of this frame, by seconds.
public var duration: TimeInterval {
if delayDenominator == 0 {
return TimeInterval(delayNumerator) / 100
} else {
return TimeInterval(delayNumerator) / TimeInterval(delayDenominator)
}
}
}
/*
The `fdAT` chunk has the same purpose as an `IDAT` chunk. It has the same structure as an `IDAT` chunk, except
preceded by a sequence number.
byte
0 sequence_number (unsigned int) Sequence number of the animation chunk, starting from 0
4 frame_data X bytes Frame data for this frame
*/
struct fdAT: DataChunk {
static let name: [Character] = ["f", "d", "A", "T"]
let sequenceNumber: Int?
let dataPresentation: ImageDataPresentation
init(data: Data) throws {
guard data.count >= 4 else {
throw APNGKitError.decoderError(.wrongChunkData(name: Self.nameString, data: data))
}
self.sequenceNumber = data[0...3].intValue
self.dataPresentation = .data(data[4...])
}
init(sequenceNumber: Data, offset: UInt64, length: Int) {
self.sequenceNumber = sequenceNumber.intValue
self.dataPresentation = .position(offset: offset, length: length)
}
}
// The IEND chunk must appear LAST. It marks the end of the PNG datastream.
struct IEND: Chunk {
init(data: Data) throws {
// The chunk's data field is empty.
guard data.isEmpty else {
throw APNGKitError.decoderError(.wrongChunkData(name: Self.nameString, data: data))
}
}
static let name: [Character] = ["I", "E", "N", "D"]
// `IEND` is fixed so it is a shortcut to prevent CRC calculation.
func verifyCRC(chunkData: Data, checksum: Data) -> Bool {
guard chunkData.isEmpty else { return false }
// IEND has length of 0 and should always have the same checksum.
return checksum.bytes == [0xAE, 0x42, 0x60, 0x82]
}
}
| 35.09375 | 122 | 0.630292 |
117be8fd593aff643c4bfe1c1c40c0bd6b7dafe9 | 10,843 | //
// WasherController.swift
// ExpressWash
//
// Created by Joel Groomer on 5/14/20.
// Copyright © 2020 Bobby Keffury. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
class WasherController {
static let shared = WasherController()
// MARK: - Local store methods
func updateWasher(_ washer: Washer,
with rep: WasherRepresentation,
context: NSManagedObjectContext = CoreDataStack.shared.mainContext,
completion: @escaping (Error?) -> Void = { _ -> Void in }) {
washer.aboutMe = rep.aboutMe
washer.workStatus = rep.workStatus
washer.currentLocationLat = rep.currentLocationLat ?? kCLLocationCoordinate2DInvalid.latitude
washer.currentLocationLon = rep.currentLocationLon ?? kCLLocationCoordinate2DInvalid.longitude
washer.rateSmall = rep.rateSmall ?? rep.rateMedium
washer.rateMedium = rep.rateMedium
washer.rateLarge = rep.rateLarge ?? rep.rateMedium
washer.washerId = Int32(rep.washerId)
washer.washerRating = rep.washerRating ?? 0.0
washer.washerRatingTotal = Int16(rep.washerRatingTotal)
// if the user is already the same, don't bother hunting it down
// and updating it for no reason
if washer.user?.userId != Int32(rep.userId) {
// if not, grab the user from Core Data
if let newUser = UserController.shared.findUser(byID: rep.userId,
context: context) {
context.perform {
washer.user = newUser
do {
try CoreDataStack.shared.save(context: context)
completion(nil)
return
} catch {
print("Unable to save updated washer: \(error)")
context.reset()
completion(error)
return
}
}
} else {
// if the user isn't already in Core Data, fetch it from the server
UserController.shared.fetchUserByID(uid: rep.userId,
context: context) { (user, error) in
if let error = error {
print("Unable to fetch user to update washer: \(error)")
completion(error)
return
}
guard let user = user else {
print("No user (id \(rep.userId)) returned for washer (id \(rep.washerId))")
completion(NSError(domain: "update washer", code: NODATAERROR, userInfo: nil))
return
}
context.perform {
washer.user = user
do {
try CoreDataStack.shared.save(context: context)
completion(nil)
return
} catch {
print("Unable to save updated washer: \(error)")
context.reset()
completion(error)
return
}
}
}
}
}
}
func deleteWasherLocally(washer: Washer,
context: NSManagedObjectContext = CoreDataStack.shared.mainContext,
completion: @escaping (Error?) -> Void = { _ in }) {
context.perform {
do {
context.delete(washer)
try CoreDataStack.shared.save(context: context)
} catch {
print("Could not save after deleting: \(error)")
context.reset()
completion(error)
return
}
}
completion(nil)
}
func findWasher(byID washerID: Int, context: NSManagedObjectContext = CoreDataStack.shared.mainContext) -> Washer? {
var foundWasher: Washer?
let objcUID = NSNumber(value: washerID)
let fetchrequest: NSFetchRequest<Washer> = Washer.fetchRequest()
fetchrequest.predicate = NSPredicate(format: "washerId == %@", objcUID)
do {
let matchedWashers = try context.fetch(fetchrequest)
if matchedWashers.count == 1 {
foundWasher = matchedWashers[0]
} else {
foundWasher = nil
}
return foundWasher
} catch {
print("Error when searching core data for washerID \(washerID): \(error)")
return nil
}
}
func findWasher(byID washerID: Int32,
context: NSManagedObjectContext = CoreDataStack.shared.mainContext) -> Washer? {
findWasher(byID: Int(washerID), context: context)
}
}
extension WasherController {
// MARK: - Server methods
func put(washerRep: WasherRepresentation, completion: @escaping (Error?) -> Void = { _ in }) {
let requestURL = BASEURL
.appendingPathComponent(ENDPOINTS.washer.rawValue)
.appendingPathComponent("\(washerRep.washerId)")
var request = URLRequest(url: requestURL)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(UserController.shared.bearerToken, forHTTPHeaderField: "Authorization")
let encoder = JSONEncoder()
do {
request.httpBody = try encoder.encode(washerRep)
} catch {
print("Error encoding washerRep: \(error)")
completion(error)
}
SESSION.dataTask(with: request) { (_, _, error) in
if let error = error {
print("Error sending washer to server: \(error)")
completion(error)
return
}
completion(nil)
}.resume()
}
func put(washer: Washer, completion: @escaping (Error?) -> Void = { _ in }) {
put(washerRep: washer.representation, completion: completion)
}
func rate(washer: Washer, rating: Int, completion: @escaping (Error?) -> Void = { _ in }) {
let requestURL = BASEURL
.appendingPathComponent(ENDPOINTS.washerRating.rawValue)
.appendingPathComponent(washer.stringID)
var request = URLRequest(url: requestURL)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(UserController.shared.bearerToken, forHTTPHeaderField: "Authorization")
let newRating = WasherRating(washerRating: rating)
let encoder = JSONEncoder()
do {
request.httpBody = try encoder.encode(newRating)
} catch {
print("Error encoding washer rating: \(error)")
completion(error)
return
}
SESSION.dataTask(with: request) { (data, response, error) in
if let error = error {
completion(error)
return
}
if let response = response as? HTTPURLResponse {
if response.statusCode != 200 && response.statusCode != 201 && response.statusCode != 202 {
print("Error rating washer: \(response.statusCode)")
completion(NSError(domain: "rate washer", code: response.statusCode, userInfo: nil))
return
}
}
guard let data = data else {
print("No data after rating washer")
completion(NSError(domain: "rate washer", code: NODATAERROR, userInfo: nil))
return
}
let decoder = JSONDecoder()
do {
let updatedWasherRep = try decoder.decode(WasherRepresentation.self, from: data)
self.updateWasher(washer, with: updatedWasherRep) { _ in }
} catch {
print("Error decoding washer after rating: \(error)")
completion(error)
return
}
completion(nil)
}.resume()
}
func getWashersInCity(_ city: String, completion: @escaping ([Washer]?, Error?) -> Void) {
let baseURL = BASEURL.appendingPathComponent(ENDPOINTS.washersInCity.rawValue).appendingPathComponent(city)
var request = URLRequest(url: baseURL)
request.httpMethod = "GET"
request.setValue(UserController.shared.bearerToken, forHTTPHeaderField: "Authorization")
SESSION.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error getting washers: \(error)")
completion(nil, error)
return
}
if let response = response as? HTTPURLResponse {
print("\(response.statusCode)")
if response.statusCode != 200 && response.statusCode != 201 && response.statusCode != 202 {
completion(nil, NSError(domain: "Getting Washers in City",
code: response.statusCode,
userInfo: nil))
return
}
}
guard let data = data else {
completion(nil, NSError(domain: "Getting Washers in City", code: NODATAERROR, userInfo: nil))
return
}
let decoder = JSONDecoder()
do {
let washerReps = try decoder.decode([WasherRepresentation].self, from: data)
var washers: [Washer] = []
for wash in washerReps {
var washer = self.findWasher(byID: wash.washerId)
if washer == nil {
washer = Washer(representation: wash)
}
UserController.shared.fetchUserByID(uid: wash.userId) { (user, error) in
if let error = error {
print("Error fetching a washer-user: \(error)")
return
}
if let user = user {
washer?.user = user
}
}
washers.append(washer!)
}
completion(washers, nil)
} catch {
print("Error getting washers in city: \(error)")
return
}
}.resume()
}
struct WasherRating: Encodable {
var washerRating: Int
}
}
| 38.725 | 120 | 0.518491 |
cc7347df9156b62745ae7c722e62ee909ae1d98e | 2,183 | //
// AppDelegate.swift
// PayloadCardReader
//
// Created by Ian Halpern on 06/03/2021.
// Copyright (c) 2021 Ian Halpern. All rights reserved.
//
import UIKit
@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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.446809 | 285 | 0.754924 |
8775d427f4d57675f4ce5310ce1e51fdf1b00184 | 711 | //
// Localizable+UIKit.swift
// Localizable
//
// Created by Mario Iannotta on 20/02/2020.
// Copyright © 2020 Mario. All rights reserved.
//
import UIKit
extension UIButton: Localizable {
var localizedState: UIControl.State {
state
}
public func setLocalizedString(_ string: String, for state: UIControl.State) {
setTitle(string, for: state)
}
}
extension UILabel: Localizable {
public func setLocalizedString(_ string: String, for state: UIControl.State) {
text = string
}
}
extension UITextField: Localizable {
public func setLocalizedString(_ string: String, for state: UIControl.State) {
placeholder = string
}
}
| 20.314286 | 82 | 0.661041 |
79efd5a2eb0ce20b693146b712a0502f99ee0568 | 6,800 | //
// MemeEditorViewController.swift
// MemeMe v0.1
//
// Created by Raditya on 6/13/17.
// Copyright © 2017 Raditya. All rights reserved.
//
import UIKit
class MemeEditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var imagePicked: UIImageView!
@IBOutlet weak var topField: UITextField!
@IBOutlet weak var bottomField: UITextField!
@IBOutlet weak var btnCamera: UIBarButtonItem!
@IBOutlet weak var btnAction: UIBarButtonItem!
@IBOutlet weak var btnCancel: UIBarButtonItem!
@IBOutlet weak var tbBottom: UIToolbar!
@IBOutlet weak var tbTop: UINavigationBar!
var editingMeme : Meme!
var editingIndex : Int = -1
let memeAttributes : [String:Any] = [
NSStrokeColorAttributeName : UIColor.black,
NSForegroundColorAttributeName : UIColor.white,
NSFontAttributeName : UIFont(name: "Impact", size: 40)!,
NSStrokeWidthAttributeName: -2
]
func enableNavButton(enable:Bool){
btnAction.isEnabled = enable
}
func prepareTextfield(textField: UITextField){
textField.defaultTextAttributes = memeAttributes
textField.textAlignment = .center
textField.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
prepareTextfield(textField: bottomField)
prepareTextfield(textField: topField)
enableNavButton(enable: false)
}
func showPicker( sourceType: UIImagePickerControllerSourceType) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
present(imagePicker, animated: true, completion: nil)
}
@IBAction func pickAnImage(_ sender: Any) {
switch (sender as! UIBarButtonItem).tag {
case 1:
showPicker(sourceType: .photoLibrary)
break
case 2:
showPicker(sourceType: .camera)
break
default:
break
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imagePicked.image = image
enableNavButton(enable: true)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
@IBAction func textDidBegin(_ sender: Any) {
(sender as! UITextField).text = ""
}
func addMyObserver(selector aSelector : Selector,aName name : NSNotification.Name){
NotificationCenter.default.addObserver(self, selector: aSelector, name: name, object: nil)
}
func removeMyObserver(aName name:NSNotification.Name){
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
//View will appear and disappear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
btnCamera.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
addMyObserver( selector: #selector(keyboardWillShow(_:)), aName: .UIKeyboardWillShow)
addMyObserver( selector: #selector(keyboardWillHide(_:)), aName: .UIKeyboardWillHide)
if editingMeme != nil {
topField.text = editingMeme.topText
bottomField.text = editingMeme.bottomText
imagePicked.image = editingMeme.originalImage
enableNavButton(enable: true)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeMyObserver(aName: .UIKeyboardWillShow)
removeMyObserver(aName: .UIKeyboardWillHide)
}
func keyboardWillHide(_ notification:Notification){
view.frame.origin.y = 0
}
func keyboardWillShow(_ notification:Notification){
if(bottomField.isFirstResponder) {
view.frame.origin.y = -getKeyboardHeight(notification)
}else
//added for iPhone SE
if (topField.isFirstResponder) {
view.frame.origin.y = -40
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func hideNavAndToolbar(hide: Bool){
tbTop.isHidden = hide
tbBottom.isHidden = hide
}
func generateMeme() -> UIImage {
hideNavAndToolbar(hide: true)
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
hideNavAndToolbar(hide: false)
return memedImage
}
@IBAction func actionClicked(_ sender: Any) {
let img = generateMeme()
if editingMeme == nil {
let img = generateMeme()
let activity = UIActivityViewController(activityItems: [img], applicationActivities: nil)
activity.completionWithItemsHandler = { (activityType:UIActivityType?, completed:Bool, returnedItems: [Any]? , error: Error? ) -> Void in
if completed {
self.save()
self.dismiss(animated: true, completion: nil)
}
}
self.present(activity, animated: true, completion: nil)
}else{
editingMeme.meme = img
editingMeme.topText = topField.text!
editingMeme.bottomText = bottomField.text!
replaceMeme(at: editingIndex, meme: editingMeme)
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func cancelClicked(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func save(){
let meme = Meme(topText: topField.text!, bottomText: bottomField.text!, originalImage: imagePicked.image!, meme: generateMeme())
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
appDelegate.meme.append(meme)
}
}
| 31.481481 | 149 | 0.630588 |
Subsets and Splits