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
|
---|---|---|---|---|---|
48e17750aed0b5343027cc19e1970c9a1a279cad | 1,433 | //: ## 3D Panner
//: ###
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
let panner = AK3DPanner(player)
AudioKit.output = panner
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("3D Panner")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: processingPlaygroundFiles))
addSubview(AKPropertySlider(
property: "X",
value: panner.x, minimum: -10, maximum: 10,
color: AKColor.redColor()
) { sliderValue in
panner.x = sliderValue
})
addSubview(AKPropertySlider(
property: "Y",
value: panner.y, minimum: -10, maximum: 10,
color: AKColor.greenColor()
) { sliderValue in
panner.y = sliderValue
})
addSubview(AKPropertySlider(
property: "Z",
value: panner.z, minimum: -10, maximum: 10,
color: AKColor.cyanColor()
) { sliderValue in
panner.z = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| 25.589286 | 70 | 0.60014 |
118d3fa0080f22431d3e2dae2342c095e3a26413 | 524 | //
// DQStatusPictureInfo.swift
// SinaWeibo
//
// Created by admin on 2016/9/27.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//
import UIKit
class DQStatusPictureInfo: NSObject {
var thumbnail_pic: String? {
didSet{
bmiddle_pic = thumbnail_pic?.replacingOccurrences(of: "thumbnail", with: "bmiddle")
wap360_pic = thumbnail_pic?.replacingOccurrences(of: "thumbnail", with: "wap360")
}
}
var bmiddle_pic: String?
var wap360_pic: String?
}
| 20.96 | 92 | 0.645038 |
ebdfd16e5e5a48eff90aa707ac7f876c43d7407a | 1,016 | //
// GameInterfaceController.swift
// watchOS Extension
//
// Created by Rigoberto Sáenz Imbacuán on 9/21/17.
// Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved.
//
import WatchKit
import SceneKit
class GameInterfaceController: WKInterfaceController {
@IBOutlet var sceneInterface: WKInterfaceSCNScene!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Set up the interface
sceneInterface.showsStatistics = true
sceneInterface.preferredFramesPerSecond = 30
sceneInterface.isPlaying = true
// Set up the Scene
sceneInterface.scene = GameManager.getScene()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| 26.736842 | 90 | 0.685039 |
b9597ff3d8c853127716c1385d1d4caa96c74e76 | 8,453 | //
// WebViewController.swift
// flutter_macos_webview
//
// Created by vanya elizarov on 22.11.2020.
//
import Cocoa
import FlutterMacOS
import WebKit
class WebViewController: NSViewController {
enum PresentationStyle: Int {
case modal = 0
case sheet = 1
}
static let closeNotification = Notification.Name("WebViewCloseNotification")
private let webview: WKWebView
private let frame: CGRect
private let channel: FlutterMethodChannel
private let presentationStyle: PresentationStyle
private let modalTitle: String!
private let sheetCloseButtonTitle: String
var javascriptEnabled: Bool {
set { webview.configuration.preferences.javaScriptEnabled = newValue }
get { webview.configuration.preferences.javaScriptEnabled }
}
var userAgent: String? {
set {
if let userAgent = newValue {
webview.customUserAgent = userAgent //" Custom Agent"
} else {
webview.customUserAgent = nil
}
}
get { webview.customUserAgent }
}
required init(
channel: FlutterMethodChannel,
frame: NSRect,
presentationStyle: PresentationStyle,
modalTitle: String,
sheetCloseButtonTitle: String
) {
self.channel = channel
self.frame = frame
self.presentationStyle = presentationStyle
self.modalTitle = modalTitle
self.sheetCloseButtonTitle = sheetCloseButtonTitle
webview = WKWebView()
super.init(nibName: nil, bundle: nil)
webview.navigationDelegate = self
webview.uiDelegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func clearCookies() {
let cookieStore = webview.configuration.websiteDataStore.httpCookieStore
cookieStore.getAllCookies {
cookies in
for cookie in cookies {
cookieStore.delete(cookie)
}
}
}
func loadUrl(url: URL) {
let req = URLRequest(url: url)
webview.load(req)
}
@objc private func closeSheet() {
self.view.window?.close()
}
private func setupViews() {
webview.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webview)
var constraints: [NSLayoutConstraint] = [
webview.topAnchor.constraint(equalTo: view.topAnchor),
webview.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webview.trailingAnchor.constraint(equalTo: view.trailingAnchor)
]
if (presentationStyle == .sheet) {
let bottomBarHeight: CGFloat = 44.0
constraints.append(
webview.heightAnchor.constraint(equalTo: view.heightAnchor, constant: -bottomBarHeight)
)
let bottomBar = NSView()
bottomBar.wantsLayer = true
bottomBar.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor
bottomBar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bottomBar)
constraints.append(contentsOf: [
bottomBar.topAnchor.constraint(equalTo: webview.bottomAnchor),
bottomBar.bottomAnchor.constraint(equalTo: view.bottomAnchor),
bottomBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
bottomBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
bottomBar.heightAnchor.constraint(equalToConstant: bottomBarHeight),
])
let closeButton = NSButton()
closeButton.isBordered = false
closeButton.title = sheetCloseButtonTitle
closeButton.font = NSFont.systemFont(ofSize: 14.0)
closeButton.contentTintColor = .systemBlue
closeButton.bezelStyle = .rounded
closeButton.setButtonType(.momentaryChange)
closeButton.sizeToFit()
closeButton.target = self
closeButton.action = #selector(self.closeSheet)
closeButton.translatesAutoresizingMaskIntoConstraints = false
bottomBar.addSubview(closeButton)
constraints.append(contentsOf: [
closeButton.trailingAnchor.constraint(equalTo: bottomBar.trailingAnchor),
closeButton.centerYAnchor.constraint(equalTo: bottomBar.centerYAnchor),
closeButton.widthAnchor.constraint(equalToConstant: closeButton.frame.width + 20.0),
closeButton.heightAnchor.constraint(equalTo: bottomBar.heightAnchor)
])
} else {
title = modalTitle
constraints.append(webview.heightAnchor.constraint(equalTo: view.heightAnchor))
}
constraints.forEach { (c) in
c.isActive = true
}
}
override func loadView() {
view = NSView(frame: frame)
view.translatesAutoresizingMaskIntoConstraints = false
setupViews()
}
override func viewDidAppear() {
view.window?.delegate = self
}
}
extension WebViewController: NSWindowDelegate {
func windowWillClose(_ notification: Notification) {
NotificationCenter.default.post(name: WebViewController.closeNotification, object: nil)
}
}
extension WebViewController: WKUIDelegate {
public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let isMainFrame = navigationAction.targetFrame?.isMainFrame else { return nil }
if !isMainFrame {
webView.load(navigationAction.request)
}
return nil
}
}
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
guard let url = webView.url?.absoluteString else { return }
channel.invokeMethod("onPageStarted", arguments: [ "url": url ])
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let url = webView.url?.absoluteString else { return }
channel.invokeMethod("onPageFinished", arguments: [ "url": url ])
}
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
let error = NSError(
domain: WKError.errorDomain,
code: WKError.webContentProcessTerminated.rawValue,
userInfo: nil
)
onWebResourceError(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
onWebResourceError(error as NSError)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
onWebResourceError(error as NSError)
}
static func errorCodeToString(code: Int) -> String? {
switch code {
case WKError.unknown.rawValue:
return "unknown";
case WKError.webContentProcessTerminated.rawValue:
return "webContentProcessTerminated";
case WKError.webViewInvalidated.rawValue:
return "webViewInvalidated";
case WKError.javaScriptExceptionOccurred.rawValue:
return "javaScriptExceptionOccurred";
case WKError.javaScriptResultTypeIsUnsupported.rawValue:
return "javaScriptResultTypeIsUnsupported";
default:
return nil;
}
}
func onWebResourceError(_ error: NSError) {
channel.invokeMethod("onWebResourceError", arguments: [
"errorCode": error.code,
"domain": error.domain,
"description": error.description,
"errorType": WebViewController.errorCodeToString(code: error.code) as Any
])
}
}
extension NSImage {
func tint(color: NSColor) -> NSImage {
let image = self.copy() as! NSImage
image.lockFocus()
color.set()
let imageRect = NSRect(origin: NSZeroPoint, size: image.size)
imageRect.fill(using: .sourceAtop)
image.unlockFocus()
return image
}
}
| 33.947791 | 194 | 0.633976 |
ff133072263e4ef5b60bb7cefac6f15763efeaf2 | 9,871 | /// Copyright (c) 2018-19 Nicolas Christe
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
import Foundation
/// A future value
public class Future<Success, Failure: Error> {
/// Result, when future is completed
private var result: Result<Success, Failure>?
/// List of waiters
private var awaiters = [(DispatchQueue?, (Result<Success, Failure>) -> Void)]()
/// lock
private let lockQueue = DispatchQueue(label: "MoreFoundation.Future")
/// Block to call to cancel the function generating the Future
fileprivate var cancelBlock: (() -> Void)?
/// Parent future, when chained with `then`
fileprivate var parentCancel: (() -> Void)?
/// True if future as been cancelled
public private(set) var cancelled = false
/// Call completion block when the Future has completed
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - completionBlock: completion block
/// - result: completed Future result
public func await(on queue: DispatchQueue? = nil,
completionBlock: @escaping (_ result: Result<Success, Failure>) -> Void) {
lockQueue.sync {
awaiters.append((queue, completionBlock))
}
if let result = result {
report(result)
}
}
/// Call completion block when the Future has completed successfully
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - completionBlock: completion block
/// - result: completed Future result
@discardableResult
public func done(on queue: DispatchQueue? = nil,
completionBlock: @escaping (Success) -> Void) -> Future<Success, Failure> {
await(on: queue) { result in
if case let .success(value) = result {
completionBlock(value)
}
}
return self
}
/// Call completion block when the Future has completed with an error
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - completionBlock: completion block
/// - result: completed Future error
@discardableResult
public func `catch`(on queue: DispatchQueue? = nil,
completionBlock: @escaping (Failure) -> Void) -> Future<Success, Failure> {
await(on: queue) { result in
if case let .failure(error) = result {
completionBlock(error)
}
}
return self
}
/// Call completion block when the Future has completed
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - completionBlock: completion block
public func finally(on queue: DispatchQueue? = nil, completionBlock: @escaping () -> Void) {
await(on: queue) { _ in
completionBlock()
}
}
/// Dispatch the future on a specific queue.
///
/// - Parameter queue: queue to dispatch on
/// - Returns: a new future that will complete on the given queue
public func dispatch(on queue: DispatchQueue) -> Future<Success, Failure> {
let promise = Promise<Success, Failure>()
await(on: queue) { result in
promise.complete(with: result)
}
return promise
}
/// Cancel the Future
/// Mark the future as cancelled. The underlaying asynchronous task may or may not be cancelled, and the
/// future will still be completed or rejected.
public func cancel() {
cancelled = true
if result == nil {
cancelBlock?()
}
parentCancel?()
}
/// Call a new async function when the future has completed successfully
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - errorMapper: block converting failure `F` to `Failure`
/// - block: block to call when the future has completed
/// - Returns: new Future
public func then<U, F: Error>(on queue: DispatchQueue? = nil,
errorMapper: @escaping (Failure) -> F,
_ block: @escaping (_ promise: Promise<U, F>, _ value: Success) -> Void)
-> Future<U, F> {
let promise = Promise<U, F>()
promise.parentCancel = cancel
await(on: queue) { result in
switch result {
case .success(let value):
block(promise, value)
case .failure(let error):
promise.reject(with: errorMapper(error))
}
}
return promise
}
/// Call a new async function when the future has completed successfully.
///
/// Special case when the new future has the same `Failure` type than the current one
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - block: block to call when the future has completed
/// - Returns: new Future
public func then<U>(on queue: DispatchQueue? = nil,
_ block: @escaping (_ promise: Promise<U, Failure>, _ value: Success) -> Void)
-> Future<U, Failure> {
return then(errorMapper: { $0 }, block)
}
/// Transform the future result when the futuree has completed successfully.
///
/// - Parameters:
/// - queue: queue to call the completion block on. If nil the completion block may be called on any queue,
/// including caller queue if the future did already complete.
/// - transform: closure to transform successful result to U
/// - Returns: new Future
public func map<U>(on queue: DispatchQueue? = nil, transform: @escaping (Success) -> U) -> Future<U, Failure> {
return then(on: queue) { promise, value in
promise.fulfill(with: transform(value))
}
}
/// Complete the future
///
/// - Parameter value: result
fileprivate func complete(with value: Result<Success, Failure>) {
if result == nil {
result = value
report(value)
}
}
/// Notify waiters the future has completed
///
/// - Parameter result: future result
private func report(_ result: Result<Success, Failure>) {
var awaiters = [(DispatchQueue?, (Result<Success, Failure>) -> Void)]()
lockQueue.sync {
awaiters = self.awaiters
self.awaiters.removeAll()
}
awaiters.forEach { queue, completionBlock in
if let queue = queue {
queue.async { completionBlock(result) }
} else {
completionBlock(result)
}
}
}
}
/// A promise value
public class Promise<Success, Failure: Error>: Future<Success, Failure> {
override public init() {
}
/// Fulfill the promise with a value
///
/// - Parameter value: promise value
public func fulfill(with value: Success) {
complete(with: .success(value))
}
/// Reject the promise with an error
///
/// - Parameter error: promise error
public func reject(with error: Failure) {
complete(with: .failure(error))
}
/// Register the bloc to call when the future is cancelled
/// It's up to the implementation to cancel the underlaying asynchronous task, and if cancelled, to complete or
/// reject the promise.
///
/// - Parameter cancelBlock: bloc to call when the future is cancelled
public func registerCancel(_ cancelBlock: @escaping () -> Void) {
self.cancelBlock = cancelBlock
}
}
/// Helper to call an async block
///
/// - Parameters:
/// - block: async block
/// - promise: promise passed to the async block
/// - Returns: future
public func async<Success, Failure: Error>(block: (_ promise: Promise<Success, Failure>) -> Void)
-> Future<Success, Failure> {
let promise = Promise<Success, Failure>()
block(promise)
return promise
}
| 39.484 | 115 | 0.615743 |
db28aaa84f07e39c3bd974d6d8a1fb304d746334 | 2,442 | //
// InvisibleFormatter.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2018-04-01.
//
// ---------------------------------------------------------------------------
//
// © 2018 1024jp
//
// 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
//
// https://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 Cocoa
final class InvisibleFormatter: Formatter {
// MARK: Properties
var invisibles: [Invisible] = [.newLine, .tab, .fullwidthSpace]
// MARK: -
// MARK: Formatter Function
/// convert to plain string
override func string(for obj: Any?) -> String? {
return obj as? String
}
/// make invisible characters visible
override func attributedString(for obj: Any, withDefaultAttributes attrs: [NSAttributedString.Key: Any]? = nil) -> NSAttributedString? {
guard let string = self.string(for: obj) else { return nil }
let attributedString = NSMutableAttributedString(string: string, attributes: attrs)
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.tertiaryLabelColor]
for (index, codeUnit) in string.utf16.enumerated() {
guard
let invisible = Invisible(codeUnit: codeUnit),
self.invisibles.contains(invisible)
else { continue }
let range = NSRange(location: index, length: 1)
attributedString.replaceCharacters(in: range, with: NSAttributedString(string: invisible.usedSymbol, attributes: attributes))
}
return attributedString
}
/// format backwards
override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
obj?.pointee = string as AnyObject
return true
}
}
| 31.714286 | 188 | 0.624898 |
e59eecffd4c48deace19358c4dd36e1f319db925 | 2,309 | import Flutter
import UIKit
import Ed25519
public class SwiftEd25519LibPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "ed25519_lib", binaryMessenger: registrar.messenger())
let instance = SwiftEd25519LibPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "Ed25519ExtractPublicKey":
guard let arguments = call.arguments as? [String:FlutterStandardTypedData],
let message:FlutterStandardTypedData = arguments["message"],
let sig:FlutterStandardTypedData = arguments["sig"]
else {
result("Wrong arguments")
return
}
result(Ed25519.Ed25519ExtractPublicKey(message.data,sig.data))
case "Ed25519Sign2":
guard let arguments = call.arguments as? [String:FlutterStandardTypedData],
let privateKey:FlutterStandardTypedData = arguments["privateKey"],
let message:FlutterStandardTypedData = arguments["message"]
else {
result("Wrong arguments")
return
}
result(Ed25519.Ed25519Sign2(privateKey.data,message.data))
case "Ed25519Verify2":
guard let arguments = call.arguments as? [String:FlutterStandardTypedData],
let publicKey:FlutterStandardTypedData = arguments["publicKey"],
let message:FlutterStandardTypedData = arguments["message"],
let sig:FlutterStandardTypedData = arguments["sig"]
else {
result("Wrong arguments")
return
}
result(Ed25519.Ed25519Verify2(publicKey.data,message.data,sig.data))
case "Ed25519NewDerivedKeyFromSeed":
guard let arguments = call.arguments as? [String:FlutterStandardTypedData],
let seed:FlutterStandardTypedData = arguments["seed"],
let index:FlutterStandardTypedData = arguments["index"],
let salt:FlutterStandardTypedData = arguments["salt"]
else {
result("Wrong arguments")
return
}
result(Ed25519.Ed25519NewDerivedKeyFromSeed(seed.data,index.data,salt.data))
default:
result("err")
}
}
} | 37.241935 | 99 | 0.682113 |
1a7617d253a6002089ff3b2c598c14b476f0eaa3 | 594 | //
// BestMatchHeaderCell.swift
// Yelp
//
// Created by Truong Tran on 6/23/17.
// Copyright © 2017 CoderSchool. All rights reserved.
//
import UIKit
class BestMatchHeaderCell: UITableViewCell {
@IBOutlet weak var imgBestMatchHeader: UIImageView!
@IBOutlet weak var bestMatchTitle: 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 | 65 | 0.685185 |
4ab85eb02eeab038c8f44c852bc311b731e7718c | 752 | import XCTest
import AsyncOperations
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.931034 | 111 | 0.603723 |
e802479d4c637b1e285c483178a03fb7ce0928f3 | 37,989 | import Logging
import PostgresNIO
import XCTest
import NIOTestUtils
final class PostgresNIOTests: XCTestCase {
private var group: EventLoopGroup!
private var eventLoop: EventLoop { self.group.next() }
override func setUpWithError() throws {
try super.setUpWithError()
XCTAssertTrue(isLoggingConfigured)
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
}
override func tearDownWithError() throws {
try self.group?.syncShutdownGracefully()
self.group = nil
try super.tearDownWithError()
}
// MARK: Tests
func testConnectAndClose() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
try conn.close().wait()
}
func testSimpleQueryVersion() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.simpleQuery("SELECT version()").wait()
XCTAssertEqual(rows.count, 1)
let version = rows[0].column("version")?.string
XCTAssertEqual(version?.contains("PostgreSQL"), true)
}
func testQueryVersion() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("SELECT version()", .init()).wait()
XCTAssertEqual(rows.count, 1)
let version = rows[0].column("version")?.string
XCTAssertEqual(version?.contains("PostgreSQL"), true)
}
func testQuerySelectParameter() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("SELECT $1::TEXT as foo", ["hello"]).wait()
XCTAssertEqual(rows.count, 1)
let version = rows[0].column("foo")?.string
XCTAssertEqual(version, "hello")
}
func testSQLError() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
XCTAssertThrowsError(_ = try conn.simpleQuery("SELECT &").wait()) { error in
guard let postgresError = try? XCTUnwrap(error as? PostgresError) else { return }
XCTAssertEqual(postgresError.code, .syntaxError)
}
}
func testNotificationsEmptyPayload() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
var receivedNotifications: [PostgresMessage.NotificationResponse] = []
conn.addListener(channel: "example") { context, notification in
receivedNotifications.append(notification)
}
_ = try conn.simpleQuery("LISTEN example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
// Notifications are asynchronous, so we should run at least one more query to make sure we'll have received the notification response by then
_ = try conn.simpleQuery("SELECT 1").wait()
XCTAssertEqual(receivedNotifications.count, 1)
XCTAssertEqual(receivedNotifications[0].channel, "example")
XCTAssertEqual(receivedNotifications[0].payload, "")
}
func testNotificationsNonEmptyPayload() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
var receivedNotifications: [PostgresMessage.NotificationResponse] = []
conn.addListener(channel: "example") { context, notification in
receivedNotifications.append(notification)
}
_ = try conn.simpleQuery("LISTEN example").wait()
_ = try conn.simpleQuery("NOTIFY example, 'Notification payload example'").wait()
// Notifications are asynchronous, so we should run at least one more query to make sure we'll have received the notification response by then
_ = try conn.simpleQuery("SELECT 1").wait()
XCTAssertEqual(receivedNotifications.count, 1)
XCTAssertEqual(receivedNotifications[0].channel, "example")
XCTAssertEqual(receivedNotifications[0].payload, "Notification payload example")
}
func testNotificationsRemoveHandlerWithinHandler() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
var receivedNotifications = 0
conn.addListener(channel: "example") { context, notification in
receivedNotifications += 1
context.stop()
}
_ = try conn.simpleQuery("LISTEN example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("SELECT 1").wait()
XCTAssertEqual(receivedNotifications, 1)
}
func testNotificationsRemoveHandlerOutsideHandler() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
var receivedNotifications = 0
let context = conn.addListener(channel: "example") { context, notification in
receivedNotifications += 1
}
_ = try conn.simpleQuery("LISTEN example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("SELECT 1").wait()
context.stop()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("SELECT 1").wait()
XCTAssertEqual(receivedNotifications, 1)
}
func testNotificationsMultipleRegisteredHandlers() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
var receivedNotifications1 = 0
conn.addListener(channel: "example") { context, notification in
receivedNotifications1 += 1
}
var receivedNotifications2 = 0
conn.addListener(channel: "example") { context, notification in
receivedNotifications2 += 1
}
_ = try conn.simpleQuery("LISTEN example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("SELECT 1").wait()
XCTAssertEqual(receivedNotifications1, 1)
XCTAssertEqual(receivedNotifications2, 1)
}
func testNotificationsMultipleRegisteredHandlersRemoval() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
var receivedNotifications1 = 0
conn.addListener(channel: "example") { context, notification in
receivedNotifications1 += 1
context.stop()
}
var receivedNotifications2 = 0
conn.addListener(channel: "example") { context, notification in
receivedNotifications2 += 1
}
_ = try conn.simpleQuery("LISTEN example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("NOTIFY example").wait()
_ = try conn.simpleQuery("SELECT 1").wait()
XCTAssertEqual(receivedNotifications1, 1)
XCTAssertEqual(receivedNotifications2, 2)
}
func testNotificationHandlerFiltersOnChannel() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
conn.addListener(channel: "desired") { context, notification in
XCTFail("Received notification on channel that handler was not registered for")
}
_ = try conn.simpleQuery("LISTEN undesired").wait()
_ = try conn.simpleQuery("NOTIFY undesired").wait()
_ = try conn.simpleQuery("SELECT 1").wait()
}
func testSelectTypes() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let results = try conn.simpleQuery("SELECT * FROM pg_type").wait()
XCTAssert(results.count >= 350, "Results count not large enough: \(results.count)")
}
func testSelectType() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let results = try conn.simpleQuery("SELECT * FROM pg_type WHERE typname = 'float8'").wait()
// [
// "typreceive": "float8recv",
// "typelem": "0",
// "typarray": "1022",
// "typalign": "d",
// "typanalyze": "-",
// "typtypmod": "-1",
// "typname": "float8",
// "typnamespace": "11",
// "typdefault": "<null>",
// "typdefaultbin": "<null>",
// "typcollation": "0",
// "typispreferred": "t",
// "typrelid": "0",
// "typbyval": "t",
// "typnotnull": "f",
// "typinput": "float8in",
// "typlen": "8",
// "typcategory": "N",
// "typowner": "10",
// "typtype": "b",
// "typdelim": ",",
// "typndims": "0",
// "typbasetype": "0",
// "typacl": "<null>",
// "typisdefined": "t",
// "typmodout": "-",
// "typmodin": "-",
// "typsend": "float8send",
// "typstorage": "p",
// "typoutput": "float8out"
// ]
switch results.count {
case 1:
XCTAssertEqual(results[0].column("typname")?.string, "float8")
XCTAssertEqual(results[0].column("typnamespace")?.int, 11)
XCTAssertEqual(results[0].column("typowner")?.int, 10)
XCTAssertEqual(results[0].column("typlen")?.int, 8)
default: XCTFail("Should be exactly one result, but got \(results.count)")
}
}
func testIntegers() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
struct Integers: Decodable {
let smallint: Int16
let smallint_min: Int16
let smallint_max: Int16
let int: Int32
let int_min: Int32
let int_max: Int32
let bigint: Int64
let bigint_min: Int64
let bigint_max: Int64
}
let results = try conn.query("""
SELECT
1::SMALLINT as smallint,
-32767::SMALLINT as smallint_min,
32767::SMALLINT as smallint_max,
1::INT as int,
-2147483647::INT as int_min,
2147483647::INT as int_max,
1::BIGINT as bigint,
-9223372036854775807::BIGINT as bigint_min,
9223372036854775807::BIGINT as bigint_max
""").wait()
switch results.count {
case 1:
XCTAssertEqual(results[0].column("smallint")?.int16, 1)
XCTAssertEqual(results[0].column("smallint_min")?.int16, -32_767)
XCTAssertEqual(results[0].column("smallint_max")?.int16, 32_767)
XCTAssertEqual(results[0].column("int")?.int32, 1)
XCTAssertEqual(results[0].column("int_min")?.int32, -2_147_483_647)
XCTAssertEqual(results[0].column("int_max")?.int32, 2_147_483_647)
XCTAssertEqual(results[0].column("bigint")?.int64, 1)
XCTAssertEqual(results[0].column("bigint_min")?.int64, -9_223_372_036_854_775_807)
XCTAssertEqual(results[0].column("bigint_max")?.int64, 9_223_372_036_854_775_807)
default: XCTFail("Should be exactly one result, but got \(results.count)")
}
}
func testPi() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
struct Pi: Decodable {
let text: String
let numeric_string: String
let numeric_decimal: Decimal
let double: Double
let float: Float
}
let results = try conn.query("""
SELECT
pi()::TEXT as text,
pi()::NUMERIC as numeric_string,
pi()::NUMERIC as numeric_decimal,
pi()::FLOAT8 as double,
pi()::FLOAT4 as float
""").wait()
switch results.count {
case 1:
//print(results[0])
XCTAssertEqual(results[0].column("text")?.string?.hasPrefix("3.14159265"), true)
XCTAssertEqual(results[0].column("numeric_string")?.string?.hasPrefix("3.14159265"), true)
XCTAssertTrue(results[0].column("numeric_decimal")?.decimal?.isLess(than: 3.14159265358980) ?? false)
XCTAssertFalse(results[0].column("numeric_decimal")?.decimal?.isLess(than: 3.14159265358978) ?? true)
XCTAssertTrue(results[0].column("double")?.double?.description.hasPrefix("3.141592") ?? false)
XCTAssertTrue(results[0].column("float")?.float?.description.hasPrefix("3.141592") ?? false)
default: XCTFail("Should be exactly one result, but got \(results.count)")
}
}
func testUUID() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
struct Model: Decodable {
let id: UUID
let string: String
}
let results = try conn.query("""
SELECT
'123e4567-e89b-12d3-a456-426655440000'::UUID as id,
'123e4567-e89b-12d3-a456-426655440000'::UUID as string
""").wait()
switch results.count {
case 1:
//print(results[0])
XCTAssertEqual(results[0].column("id")?.uuid, UUID(uuidString: "123E4567-E89B-12D3-A456-426655440000"))
XCTAssertEqual(UUID(uuidString: results[0].column("id")?.string ?? ""), UUID(uuidString: "123E4567-E89B-12D3-A456-426655440000"))
default: XCTFail("Should be exactly one result, but got \(results.count)")
}
}
func testDates() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
struct Dates: Decodable {
var date: Date
var timestamp: Date
var timestamptz: Date
}
let results = try conn.query("""
SELECT
'2016-01-18 01:02:03 +0042'::DATE as date,
'2016-01-18 01:02:03 +0042'::TIMESTAMP as timestamp,
'2016-01-18 01:02:03 +0042'::TIMESTAMPTZ as timestamptz
""").wait()
switch results.count {
case 1:
//print(results[0])
XCTAssertEqual(results[0].column("date")?.date?.description, "2016-01-18 00:00:00 +0000")
XCTAssertEqual(results[0].column("timestamp")?.date?.description, "2016-01-18 01:02:03 +0000")
XCTAssertEqual(results[0].column("timestamptz")?.date?.description, "2016-01-18 00:20:03 +0000")
default: XCTFail("Should be exactly one result, but got \(results.count)")
}
}
/// https://github.com/vapor/nio-postgres/issues/20
func testBindInteger() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
_ = try conn.simpleQuery("drop table if exists person;").wait()
_ = try conn.simpleQuery("create table person(id serial primary key, first_name text, last_name text);").wait()
defer { _ = try! conn.simpleQuery("drop table person;").wait() }
let id = PostgresData(int32: 5)
_ = try conn.query("SELECT id, first_name, last_name FROM person WHERE id = $1", [id]).wait()
}
// https://github.com/vapor/nio-postgres/issues/21
func testAverageLengthNumeric() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("select avg(length('foo')) as average_length").wait()
let length = try XCTUnwrap(rows[0].column("average_length")?.double)
XCTAssertEqual(length, 3.0)
}
func testNumericParsing() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
'1234.5678'::numeric as a,
'-123.456'::numeric as b,
'123456.789123'::numeric as c,
'3.14159265358979'::numeric as d,
'10000'::numeric as e,
'0.00001'::numeric as f,
'100000000'::numeric as g,
'0.000000001'::numeric as h,
'100000000000'::numeric as i,
'0.000000000001'::numeric as j,
'123000000000'::numeric as k,
'0.000000000123'::numeric as l,
'0.5'::numeric as m
""").wait()
XCTAssertEqual(rows[0].column("a")?.string, "1234.5678")
XCTAssertEqual(rows[0].column("b")?.string, "-123.456")
XCTAssertEqual(rows[0].column("c")?.string, "123456.789123")
XCTAssertEqual(rows[0].column("d")?.string, "3.14159265358979")
XCTAssertEqual(rows[0].column("e")?.string, "10000")
XCTAssertEqual(rows[0].column("f")?.string, "0.00001")
XCTAssertEqual(rows[0].column("g")?.string, "100000000")
XCTAssertEqual(rows[0].column("h")?.string, "0.000000001")
XCTAssertEqual(rows[0].column("k")?.string, "123000000000")
XCTAssertEqual(rows[0].column("l")?.string, "0.000000000123")
XCTAssertEqual(rows[0].column("m")?.string, "0.5")
}
func testSingleNumericParsing() throws {
// this seemingly duped test is useful for debugging numeric parsing
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let numeric = "790226039477542363.6032384900176272473"
let rows = try conn.query("""
select
'\(numeric)'::numeric as n
""").wait()
XCTAssertEqual(rows[0].column("n")?.string, numeric)
}
func testRandomlyGeneratedNumericParsing() throws {
// this test takes a long time to run
try XCTSkipUnless(Self.shouldRunLongRunningTests)
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
for _ in 0..<1_000_000 {
let integer = UInt.random(in: UInt.min..<UInt.max)
let fraction = UInt.random(in: UInt.min..<UInt.max)
let number = "\(integer).\(fraction)"
.trimmingCharacters(in: CharacterSet(["0"]))
let rows = try conn.query("""
select
'\(number)'::numeric as n
""").wait()
XCTAssertEqual(rows[0].column("n")?.string, number)
}
}
func testNumericSerialization() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let a = PostgresNumeric(string: "123456.789123")!
let b = PostgresNumeric(string: "-123456.789123")!
let c = PostgresNumeric(string: "3.14159265358979")!
let rows = try conn.query("""
select
$1::numeric::text as a,
$2::numeric::text as b,
$3::numeric::text as c
""", [
.init(numeric: a),
.init(numeric: b),
.init(numeric: c)
]).wait()
XCTAssertEqual(rows[0].column("a")?.string, "123456.789123")
XCTAssertEqual(rows[0].column("b")?.string, "-123456.789123")
XCTAssertEqual(rows[0].column("c")?.string, "3.14159265358979")
}
func testMoney() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
'0'::money as a,
'0.05'::money as b,
'0.23'::money as c,
'3.14'::money as d,
'12345678.90'::money as e
""").wait()
XCTAssertEqual(rows[0].column("a")?.string, "0.00")
XCTAssertEqual(rows[0].column("b")?.string, "0.05")
XCTAssertEqual(rows[0].column("c")?.string, "0.23")
XCTAssertEqual(rows[0].column("d")?.string, "3.14")
XCTAssertEqual(rows[0].column("e")?.string, "12345678.90")
}
func testIntegerArrayParse() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
'{1,2,3}'::int[] as array
""").wait()
XCTAssertEqual(rows[0].column("array")?.array(of: Int.self), [1, 2, 3])
}
func testEmptyIntegerArrayParse() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
'{}'::int[] as array
""").wait()
XCTAssertEqual(rows[0].column("array")?.array(of: Int.self), [])
}
func testNullIntegerArrayParse() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
null::int[] as array
""").wait()
XCTAssertEqual(rows[0].column("array")?.array(of: Int.self), nil)
}
func testIntegerArraySerialize() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
$1::int8[] as array
""", [
PostgresData(array: [1, 2, 3])
]).wait()
XCTAssertEqual(rows[0].column("array")?.array(of: Int.self), [1, 2, 3])
}
func testEmptyIntegerArraySerialize() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
$1::int8[] as array
""", [
PostgresData(array: [] as [Int])
]).wait()
XCTAssertEqual(rows[0].column("array")?.array(of: Int.self), [])
}
func testBoolSerialize() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
do {
let rows = try conn.query("select $1::bool as bool", [true]).wait()
XCTAssertEqual(rows[0].column("bool")?.bool, true)
}
do {
let rows = try conn.query("select $1::bool as bool", [false]).wait()
XCTAssertEqual(rows[0].column("bool")?.bool, false)
}
do {
let rows = try conn.simpleQuery("select true::bool as bool").wait()
XCTAssertEqual(rows[0].column("bool")?.bool, true)
}
do {
let rows = try conn.simpleQuery("select false::bool as bool").wait()
XCTAssertEqual(rows[0].column("bool")?.bool, false)
}
}
func testBytesSerialize() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("select $1::bytea as bytes", [
PostgresData(bytes: [1, 2, 3])
]).wait()
XCTAssertEqual(rows[0].column("bytes")?.bytes, [1, 2, 3])
}
func testJSONBSerialize() throws {
struct Object: Codable {
let foo: Int
let bar: Int
}
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
do {
let postgresData = try PostgresData(jsonb: Object(foo: 1, bar: 2))
let rows = try conn.query("select $1::jsonb as jsonb", [postgresData]).wait()
let object = try rows[0].column("jsonb")?.jsonb(as: Object.self)
XCTAssertEqual(object?.foo, 1)
XCTAssertEqual(object?.bar, 2)
}
do {
let rows = try conn.query("select jsonb_build_object('foo',1,'bar',2) as jsonb").wait()
let object = try rows[0].column("jsonb")?.jsonb(as: Object.self)
XCTAssertEqual(object?.foo, 1)
XCTAssertEqual(object?.bar, 2)
}
}
func testJSONBConvertible() throws {
struct Object: PostgresJSONBCodable {
let foo: Int
let bar: Int
}
XCTAssertEqual(Object.postgresDataType, .jsonb)
let postgresData = Object(foo: 1, bar: 2).postgresData
XCTAssertEqual(postgresData?.type, .jsonb)
let object = Object(postgresData: postgresData!)
XCTAssertEqual(object?.foo, 1)
XCTAssertEqual(object?.bar, 2)
}
func testRemoteTLSServer() throws {
// postgres://uymgphwj:[email protected]:5432/uymgphwj
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer { try! elg.syncShutdownGracefully() }
let conn = try PostgresConnection.connect(
to: SocketAddress.makeAddressResolvingHost("elmer.db.elephantsql.com", port: 5432),
tlsConfiguration: .forClient(certificateVerification: .none),
serverHostname: "elmer.db.elephantsql.com",
on: elg.next()
).wait()
try! conn.authenticate(
username: "uymgphwj",
database: "uymgphwj",
password: "7_tHbREdRwkqAdu4KoIS7hQnNxr8J1LA"
).wait()
defer { try? conn.close().wait() }
let rows = try conn.simpleQuery("SELECT version()").wait()
XCTAssertEqual(rows.count, 1)
let version = rows[0].column("version")?.string
XCTAssertEqual(version?.contains("PostgreSQL"), true)
}
func testInvalidPassword() throws {
let conn = try PostgresConnection.testUnauthenticated(on: eventLoop).wait()
defer { try? conn.close().wait() }
let auth = conn.authenticate(username: "invalid", database: "invalid", password: "bad")
XCTAssertThrowsError(_ = try auth.wait()) { error in
guard let postgresError = try? XCTUnwrap(error as? PostgresError) else { return }
XCTAssertEqual(postgresError.code, .invalidPassword)
}
}
func testColumnsInJoin() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let dateInTable1 = Date(timeIntervalSince1970: 1234)
let dateInTable2 = Date(timeIntervalSince1970: 5678)
_ = try conn.simpleQuery("DROP TABLE IF EXISTS \"table1\"").wait()
_ = try conn.simpleQuery("""
CREATE TABLE table1 (
"id" int8 NOT NULL,
"table2_id" int8,
"intValue" int8,
"stringValue" text,
"dateValue" timestamptz,
PRIMARY KEY ("id")
);
""").wait()
defer { _ = try! conn.simpleQuery("DROP TABLE \"table1\"").wait() }
_ = try conn.simpleQuery("DROP TABLE IF EXISTS \"table2\"").wait()
_ = try conn.simpleQuery("""
CREATE TABLE table2 (
"id" int8 NOT NULL,
"intValue" int8,
"stringValue" text,
"dateValue" timestamptz,
PRIMARY KEY ("id")
);
""").wait()
defer { _ = try! conn.simpleQuery("DROP TABLE \"table2\"").wait() }
_ = try conn.simpleQuery("INSERT INTO table1 VALUES (12, 34, 56, 'stringInTable1', to_timestamp(1234))").wait()
_ = try conn.simpleQuery("INSERT INTO table2 VALUES (34, 78, 'stringInTable2', to_timestamp(5678))").wait()
let row = try conn.query("""
SELECT
"table1"."id" as "t1_id",
"table1"."intValue" as "t1_intValue",
"table1"."dateValue" as "t1_dateValue",
"table1"."stringValue" as "t1_stringValue",
"table2"."id" as "t2_id",
"table2"."intValue" as "t2_intValue",
"table2"."dateValue" as "t2_dateValue",
"table2"."stringValue" as "t2_stringValue",
*
FROM table1 INNER JOIN table2 ON table1.table2_id = table2.id
""").wait().first!
XCTAssertEqual(12, row.column("t1_id")?.int)
XCTAssertEqual(34, row.column("table2_id")?.int)
XCTAssertEqual(56, row.column("t1_intValue")?.int)
XCTAssertEqual("stringInTable1", row.column("t1_stringValue")?.string)
XCTAssertEqual(dateInTable1, row.column("t1_dateValue")?.date)
XCTAssertEqual(34, row.column("t2_id")?.int)
XCTAssertEqual(78, row.column("t2_intValue")?.int)
XCTAssertEqual("stringInTable2", row.column("t2_stringValue")?.string, "stringInTable2")
XCTAssertEqual(dateInTable2, row.column("t2_dateValue")?.date)
}
func testStringArrays() throws {
let query = """
SELECT
$1::uuid as "id",
$2::bigint as "revision",
$3::timestamp as "updated_at",
$4::timestamp as "created_at",
$5::text as "name",
$6::text[] as "countries",
$7::text[] as "languages",
$8::text[] as "currencies"
"""
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query(query, [
PostgresData(uuid: UUID(uuidString: "D2710E16-EB07-4FD6-A87E-B1BE41C9BD3D")!),
PostgresData(int: Int(0)),
PostgresData(date: Date(timeIntervalSince1970: 0)),
PostgresData(date: Date(timeIntervalSince1970: 0)),
PostgresData(string: "Foo"),
PostgresData(array: ["US"]),
PostgresData(array: ["en"]),
PostgresData(array: ["USD", "DKK"]),
]).wait()
XCTAssertEqual(rows[0].column("countries")?.array(of: String.self), ["US"])
XCTAssertEqual(rows[0].column("languages")?.array(of: String.self), ["en"])
XCTAssertEqual(rows[0].column("currencies")?.array(of: String.self), ["USD", "DKK"])
}
func testBindDate() throws {
// https://github.com/vapor/postgres-nio/issues/53
let date = Date(timeIntervalSince1970: 1571425782)
let query = """
SELECT $1::json as "date"
"""
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
XCTAssertThrowsError(_ = try conn.query(query, [.init(date: date)]).wait()) { error in
guard let postgresError = try? XCTUnwrap(error as? PostgresError) else { return }
guard case let .server(serverError) = postgresError else {
XCTFail("Expected a .serverError but got \(postgresError)")
return
}
XCTAssertEqual(serverError.fields[.routine], "transformTypeCast")
}
}
func testBindCharString() throws {
// https://github.com/vapor/postgres-nio/issues/53
let query = """
SELECT $1::char as "char"
"""
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query(query, [.init(string: "f")]).wait()
XCTAssertEqual(rows[0].column("char")?.string, "f")
}
func testBindCharUInt8() throws {
// https://github.com/vapor/postgres-nio/issues/53
let query = """
SELECT $1::char as "char"
"""
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query(query, [.init(uint8: 42)]).wait()
XCTAssertEqual(rows[0].column("char")?.string, "*")
}
func testDoubleArraySerialization() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let doubles: [Double] = [3.14, 42]
let rows = try conn.query("""
select
$1::double precision[] as doubles
""", [
.init(array: doubles)
]).wait()
XCTAssertEqual(rows[0].column("doubles")?.array(of: Double.self), doubles)
}
// https://github.com/vapor/postgres-nio/issues/42
func testUInt8Serialization() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
$1::"char" as int
""", [
.init(uint8: 5)
]).wait()
XCTAssertEqual(rows[0].column("int")?.uint8, 5)
}
func testMessageDecoder() throws {
let sample: [UInt8] = [
0x52, // R - authentication
0x00, 0x00, 0x00, 0x0C, // length = 12
0x00, 0x00, 0x00, 0x05, // md5
0x01, 0x02, 0x03, 0x04, // salt
0x4B, // B - backend key data
0x00, 0x00, 0x00, 0x0C, // length = 12
0x05, 0x05, 0x05, 0x05, // process id
0x01, 0x01, 0x01, 0x01, // secret key
]
var input = ByteBufferAllocator().buffer(capacity: 0)
input.writeBytes(sample)
let output: [PostgresMessage] = [
PostgresMessage(identifier: .authentication, bytes: [
0x00, 0x00, 0x00, 0x05,
0x01, 0x02, 0x03, 0x04,
]),
PostgresMessage(identifier: .backendKeyData, bytes: [
0x05, 0x05, 0x05, 0x05,
0x01, 0x01, 0x01, 0x01,
])
]
try XCTUnwrap(ByteToMessageDecoderVerifier.verifyDecoder(
inputOutputPairs: [(input, output)],
decoderFactory: {
PostgresMessageDecoder()
}
))
}
func testPreparedQuery() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let prepared = try conn.prepare(query: "SELECT 1 as one;").wait()
let rows = try prepared.execute().wait()
XCTAssertEqual(rows.count, 1)
let value = rows[0].column("one")
XCTAssertEqual(value?.int, 1)
}
func testPrepareQueryClosure() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let x = conn.prepare(query: "SELECT $1::text as foo;", handler: { query in
let a = query.execute(["a"])
let b = query.execute(["b"])
let c = query.execute(["c"])
return EventLoopFuture.whenAllSucceed([a, b, c], on: conn.eventLoop)
})
let rows = try x.wait()
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0][0].column("foo")?.string, "a")
XCTAssertEqual(rows[1][0].column("foo")?.string, "b")
XCTAssertEqual(rows[2][0].column("foo")?.string, "c")
}
// https://github.com/vapor/postgres-nio/issues/71
func testChar1Serialization() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let rows = try conn.query("""
select
'5'::char(1) as one,
'5'::char(2) as two
""").wait()
XCTAssertEqual(rows[0].column("one")?.uint8, 53)
XCTAssertEqual(rows[0].column("one")?.uint16, 53)
XCTAssertEqual(rows[0].column("one")?.string, "5")
XCTAssertEqual(rows[0].column("two")?.uint8, nil)
XCTAssertEqual(rows[0].column("two")?.uint16, nil)
XCTAssertEqual(rows[0].column("two")?.string, "5 ")
}
func testUserDefinedType() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
_ = try conn.query("DROP TYPE IF EXISTS foo").wait()
_ = try conn.query("CREATE TYPE foo AS ENUM ('bar', 'qux')").wait()
defer {
_ = try! conn.query("DROP TYPE foo").wait()
}
let res = try conn.query("SELECT 'qux'::foo as foo").wait()
XCTAssertEqual(res[0].column("foo")?.string, "qux")
}
func testNullBind() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let res = try conn.query("SELECT $1::text as foo", [String?.none.postgresData!]).wait()
XCTAssertEqual(res[0].column("foo")?.string, nil)
}
func testUpdateMetadata() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
_ = try conn.simpleQuery("DROP TABLE IF EXISTS test_table").wait()
_ = try conn.simpleQuery("CREATE TABLE test_table(pk int PRIMARY KEY)").wait()
_ = try conn.simpleQuery("INSERT INTO test_table VALUES(1)").wait()
try conn.query("DELETE FROM test_table", onMetadata: { metadata in
XCTAssertEqual(metadata.command, "DELETE")
XCTAssertEqual(metadata.oid, nil)
XCTAssertEqual(metadata.rows, 1)
}, onRow: { _ in }).wait()
let rows = try conn.query("DELETE FROM test_table").wait()
XCTAssertEqual(rows.metadata.command, "DELETE")
XCTAssertEqual(rows.metadata.oid, nil)
XCTAssertEqual(rows.metadata.rows, 0)
}
func testTooManyBinds() throws {
let conn = try PostgresConnection.test(on: eventLoop).wait()
defer { try! conn.close().wait() }
let binds = [PostgresData].init(repeating: .null, count: Int(Int16.max) + 1)
do {
_ = try conn.query("SELECT version()", binds).wait()
XCTFail("Should have failed")
} catch PostgresError.connectionClosed { }
}
}
let isLoggingConfigured: Bool = {
LoggingSystem.bootstrap { label in
var handler = StreamLogHandler.standardOutput(label: label)
handler.logLevel = .debug
return handler
}
return true
}()
| 40.980583 | 150 | 0.576246 |
ccf8f8c7434b421f2d441192081e2c6ccd12f0ef | 2,695 | //
// util.swift
// minimind
//
// Created by Phan Quoc Huy on 6/2/17.
// Copyright © 2017 Phan Quoc Huy. All rights reserved.
//
import Foundation
extension Character {
var asciiValue: UInt32? {
return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
}
}
public func pow<T: ScalarType>(_ val: T, _ e: Int) -> T {
switch e {
case 0:
return T.one
case 1:
return val
case 2: return val * val
case 3: return val * val * val
case 4: return val * val * val * val
default:
return T.zero
}
}
public func ascii(_ c: String) -> Int8 {
let keys = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
let vals: [Int8] = Array(65..<91) + Array(97..<123)
return vals[keys.index(of: c)!] // Int8(D[c]!)
}
public func len<T>(_ arr: [T]) -> Int {
return arr.count
}
public func len<T>(_ mat: Matrix<T>) -> Int {
return mat.rows
}
//MARK: checking matrix and array
public func checkMatrices<T>(_ lhs: Matrix<T>, _ rhs: Matrix<T>, _ mode: String) {
let (lr, lc) = lhs.shape
let (rr, rc) = rhs.shape
switch mode {
case "rows=cols":
assert(lhs.columns == rhs.rows)
case "rows=rows":
assert(lhs.rows == rhs.rows)
case "cols=cols":
assert(lhs.columns == rhs.columns)
case "same":
assert(lhs.shape == rhs.shape)
case "transpose":
assert(lr == rc && lc == rr)
default:
fatalError("unrecognized check mode")
}
}
public func checkMatrices<T>(_ mats: [Matrix<T>], _ mode: String ) {
if len(mats) == 0{
return
}
let (r, c) = mats[0].shape
switch mode {
case "sameRows":
assert(all( (0..<mats.count).map{ mats[$0].rows == r } ), "matrices's rows are not euqal")
case "same":
assert(all( (0..<mats.count).map{ (mats[$0].rows == r) && (mats[$0].columns == c) } ), "matrices's shapes are not euqal")
case "sameColumns":
assert(all( (0..<mats.count).map{ mats[$0].columns == c } ), "matrices's columns are not euqal")
default:
fatalError("unrecognized check mode")
}
}
public func checkArray<T>(_ arr1: [T], _ arr2: [T], _ mode: String = "sameCount") {
switch mode {
case "sameCount":
assert(arr1.count == arr2.count, "arrays must have the same count")
default:
fatalError("unrecognized check mode")
}
}
| 27.783505 | 133 | 0.518738 |
0e0bd08acee9d5d1b80bce439b7a7ff633bba2fa | 1,309 | //
// Copyright © 2019 Frollo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct APIPayAnyoneRequest: Codable {
enum CodingKeys: String, CodingKey {
case accountHolder = "account_holder"
case accountNumber = "account_number"
case amount
case bsb
case description
case paymentDate = "payment_date"
case reference
case sourceAccountID = "source_account_id"
case overrideMethod = "override_method"
}
let accountHolder: String
let accountNumber: String
let amount: String
let bsb: String
let description: String?
let paymentDate: String?
let reference: String?
let sourceAccountID: Int64
let overrideMethod: String?
}
| 30.44186 | 76 | 0.692895 |
acef4fb21b6fa2ee3bc8cf440ca53e18134031b0 | 13,761 | //
// SwiftOCRTraining.swift
// SwiftOCR
//
// Created by Nicolas Camenisch on 19.04.16.
// Copyright © 2016 Nicolas Camenisch. All rights reserved.
//
import GPUImage
open class SwiftOCRTraining {
fileprivate let ocrInstance = SwiftOCR()
//Training Variables
fileprivate let trainingImageNames = ["TrainingBackground_1.png", "TrainingBackground_2.png", "TrainingBackground_3.png", "TrainingBackground_4.png"]
open var trainingFontNames = ["Arial Narrow", "Arial Narrow Bold"]
public init() {}
/**
Generates a training set for the neural network and uses that for training the neural network.
*/
open func trainWithCharSet(_ shouldContinue: @escaping (Float) -> Bool = {_ in return true}) {
let numberOfTrainImages = 500
let numberOfTestImages = 100
let errorThreshold:Float = 2
let trainData = generateRealisticCharSet(numberOfTrainImages/4)
let testData = generateRealisticCharSet(numberOfTestImages/4)
let trainInputs = trainData.map({return $0.0})
let trainAnswers = trainData.map({return $0.1})
let testInputs = testData.map({return $0.0})
let testAnswers = testData.map({return $0.1})
do {
_ = try globalNetwork.train(inputs: trainInputs, answers: trainAnswers, testInputs: testInputs, testAnswers: testAnswers, errorThreshold: errorThreshold, shouldContinue: {error in shouldContinue(error)})
saveOCR()
} catch {
print(error)
}
}
/**
Generates realistic images OCR and converts them to a float array.
- Parameter size: The number of images to generate. This does **not** correspond to the the count of elements in the array that gets returned.
- Returns: An array containing the input and answers for the neural network.
*/
fileprivate func generateRealisticCharSet(_ size: Int) -> [([Float],[Float])] {
var trainingSet = [([Float],[Float])]()
let randomCode: () -> String = {
let randomCharacter: () -> String = {
let charArray = Array(recognizableCharacters)
let randomDouble = Double(arc4random())/(Double(UINT32_MAX) + 1)
let randomIndex = Int(floor(randomDouble * Double(charArray.count)))
return String(charArray[randomIndex])
}
var code = ""
for _ in 0..<6 {
code += randomCharacter()
}
return code
}
let randomFloat: (CGFloat) -> CGFloat = { modi in
return (0 - modi) + CGFloat(arc4random()) / CGFloat(UINT32_MAX) * (modi * 2)
}
//Font
let randomFontName: () -> String = {
let randomDouble = Double(arc4random())/(Double(UINT32_MAX) + 1)
let randomIndex = Int(floor(randomDouble * Double(self.trainingFontNames.count)))
return self.trainingFontNames[randomIndex]
}
let randomFont: () -> OCRFont = {
return OCRFont(name: randomFontName(), size: 45 + randomFloat(5))!
}
let randomFontAttributes: () -> [NSAttributedString.Key: Any] = {
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = NSTextAlignment.center
return [.font: randomFont(),
.kern: CGFloat(8) as NSObject,
.foregroundColor: OCRColor(red: 27/255 + randomFloat(0.2), green: 16/255 + randomFloat(0.2), blue: 16/255 + randomFloat(0.2), alpha: 80/100 + randomFloat(0.2)),
.paragraphStyle: paragraphStyle]
}
//Image
let randomImageName: () -> String = {
let randomDouble = Double(arc4random())/(Double(UINT32_MAX) + 1)
let randomIndex = Int(floor(randomDouble * Double(self.trainingImageNames.count)))
return self.trainingImageNames[randomIndex]
}
let randomImage: () -> OCRImage = {
#if os(iOS)
return OCRImage(named: randomImageName(), in: Bundle(for: SwiftOCR.self), compatibleWith: nil)!.copy() as! OCRImage
#else
return OCRImage(byReferencing: Bundle(for: SwiftOCR.self).url(forResource: randomImageName(), withExtension: nil, subdirectory: nil, localization: nil)!).copy() as! OCRImage
#endif
}
#if os(iOS)
let customImage: (String) -> OCRImage = { code in
let randomImg = randomImage()
UIGraphicsBeginImageContext(randomImg.size)
randomImg.draw(in: CGRect(origin: CGPoint.zero, size: randomImg.size))
NSString(string: code).draw(in: CGRect(origin: CGPoint(x: 0 + randomFloat(5), y: -15.5 + randomFloat(5)), size: randomImg.size), withAttributes: randomFontAttributes())
let customImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return customImage!
}
#else
let customImage: (String) -> OCRImage = { code in
let randomImg = randomImage()
randomImg.lockFocus()
randomImg.draw(in: CGRect(origin: CGPoint.zero, size: randomImg.size))
NSString(string: code).draw(in: CGRect(origin: CGPoint(x: 0 + randomFloat(5), y: -15.5 + randomFloat(5)), size: randomImg.size), withAttributes: randomFontAttributes())
randomImg.unlockFocus()
return randomImg
}
#endif
for _ in 0..<size {
let code = randomCode()
let currentCustomImage = customImage(code)
//Distort Image
let transformImage = GPUImagePicture(image: currentCustomImage)
let transformFilter = GPUImageTransformFilter()
var affineTransform = CGAffineTransform()
affineTransform.a = 1.05 + ( CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.1 )
affineTransform.b = 0 + (0.01 - CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.02)
affineTransform.c = 0 + (0.03 - CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.06)
affineTransform.d = 1.05 + ( CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.1 )
transformFilter.affineTransform = affineTransform
transformImage?.addTarget(transformFilter)
transformFilter.useNextFrameForImageCapture()
transformImage?.processImage()
var transformedImage:OCRImage? = transformFilter.imageFromCurrentFramebuffer(with: .up)
while transformedImage == nil || transformedImage?.size == CGSize.zero {
transformFilter.useNextFrameForImageCapture()
transformImage?.processImage()
transformedImage = transformFilter.imageFromCurrentFramebuffer(with: .up)
}
let distortedImage = ocrInstance.preprocessImageForOCR(transformedImage!)
//Generate Training set
let blobs = ocrInstance.extractBlobs(distortedImage)
if blobs.count == 6 {
for blobIndex in 0..<blobs.count {
let blob = blobs[blobIndex]
let imageData = ocrInstance.convertImageToFloatArray(blob.0)
var imageAnswer = [Float](repeating: 0, count: recognizableCharacters.count)
if let index = Array(recognizableCharacters).firstIndex(of: Array(code)[blobIndex]) {
imageAnswer[index] = 1
}
trainingSet.append((imageData,imageAnswer))
}
}
}
return trainingSet
}
/**
Converts images to a float array for training.
- Parameter images: The number of images to generate. This does **not** correspond to the the count of elements in the array that gets returned.
- Parameter withNumberOfDistortions: How many distorted images should get generated from each input image.
- Returns: An array containing the input and answers for the neural network.
*/
fileprivate func generateCharSetFromImages(_ images: [(image: OCRImage, characters: [Character])], withNumberOfDistortions distortions: Int) -> [([Float],[Float])] {
var trainingSet = [([Float],[Float])]()
let randomFloat: (CGFloat) -> CGFloat = { modi in
return (0 - modi) + CGFloat(arc4random()) / CGFloat(UINT32_MAX) * (modi * 2)
}
for (image, characters) in images {
var imagesToExtractBlobsFrom = [OCRImage]()
//Original
imagesToExtractBlobsFrom.append(ocrInstance.preprocessImageForOCR(image))
//Distortions
for _ in 0..<distortions {
let transformImage = GPUImagePicture(image: image)
let transformFilter = GPUImageTransformFilter()
var affineTransform = CGAffineTransform()
affineTransform.a = 1.05 + ( CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.1 )
affineTransform.b = 0 + (0.01 - CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.02)
affineTransform.c = 0 + (0.03 - CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.06)
affineTransform.d = 1.05 + ( CGFloat(arc4random())/CGFloat(UINT32_MAX) * 0.1 )
affineTransform.a = 1.05 + (randomFloat(0.05) + 0.05)
affineTransform.b = 0 + (randomFloat(0.01))
affineTransform.c = 0 + (randomFloat(0.03))
affineTransform.d = 1.05 + (randomFloat(0.1) + 0.05)
transformFilter.affineTransform = affineTransform
transformImage?.addTarget(transformFilter)
transformFilter.useNextFrameForImageCapture()
transformImage?.processImage()
var transformedImage:OCRImage? = transformFilter.imageFromCurrentFramebuffer(with: .up)
while transformedImage == nil || transformedImage?.size == CGSize.zero {
transformFilter.useNextFrameForImageCapture()
transformImage?.processImage()
transformedImage = transformFilter.imageFromCurrentFramebuffer(with: .up)
}
let distortedImage = ocrInstance.preprocessImageForOCR(transformedImage!)
imagesToExtractBlobsFrom.append(distortedImage)
}
//Convert to data
for preprocessedImage in imagesToExtractBlobsFrom {
let blobs = ocrInstance.extractBlobs(preprocessedImage)
if blobs.count == characters.count {
for (blobIndex, blob) in blobs.enumerated() {
let imageData = ocrInstance.convertImageToFloatArray(blob.0)
var imageAnswer = [Float](repeating: 0, count: recognizableCharacters.count)
if let index = Array(recognizableCharacters).firstIndex(of: characters[blobIndex]) {
imageAnswer[index] = 1
}
trainingSet.append((imageData,imageAnswer))
}
}
}
}
trainingSet.shuffle()
return trainingSet
}
/**
Saves the neural network to a file.
*/
open func saveOCR() {
//Set this path to the location of your OCR-Network file.
let path = NSString(string:"~/Desktop/OCR-Network").expandingTildeInPath
globalNetwork.writeToFile(URL(string: "file://\(path)")!)
}
/**
Use this method to test the neural network.
*/
open func testOCR(_ completionHandler: (Double) -> Void) {
let testData = generateRealisticCharSet(recognizableCharacters.count)
var correctCount = 0
var totalCount = 0
for i in testData {
totalCount += 1
do {
let networkResult = try globalNetwork.update(inputs: i.0)
let input = Array(recognizableCharacters)[i.1.firstIndex(of: 1)!]
let recognized = Array(recognizableCharacters)[networkResult.firstIndex(of: networkResult.max() ?? 0) ?? 0]
print(input, recognized)
if input == recognized {
correctCount += 1
}
} catch {
}
}
completionHandler(Double(correctCount) / Double(totalCount))
}
}
| 40.473529 | 215 | 0.544365 |
1134d6cfcf93353a3a53bbb07e50991bce0ab988 | 1,887 | //
// StudentRankViewController.swift
// DemoGroupProject
//
// Created By:
// Noah Ortega 5454548 & Komasquin Lopez 5959569
import UIKit
import CoreData
class StudentRankViewController: UITableViewController{
let model = ChampsModel.sharedInstance
let data = PersistenceManager.sharedInstance
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsSelection = false
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "LeaderBoard")
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: "rank", ascending: true)
]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: data.context, sectionNameKeyPath: nil, cacheName: nil)
}
func reloadData() {
do {
try fetchedResultsController.performFetch()
} catch {
print("coredata: couldnt fetch events")
}
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "rank") //, forIndexPath: indexPath
let rank = fetchedResultsController.object(at: indexPath) as! LeaderBoard
cell?.textLabel?.text = "\(rank.rank). \(rank.name)"
cell?.detailTextLabel?.text = "\(rank.school)"
return cell!
}
}
| 32.534483 | 166 | 0.675146 |
2101bd2993494c712acf4c2bdb807033551fcf04 | 1,427 | //
// AppDelegate.swift
// NumbersConverter
//
// Created by Macbook Pro 15 on 3/31/20.
// Copyright © 2020 SamuelFolledo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.552632 | 179 | 0.749124 |
bf4dda531c7aa4fdfec3fe9703e42f35eab2b27f | 245 | //
// Data+Extension.swift
// SecureKit
//
// Created by Tolga Taner on 20.01.2022.
//
import Foundation
extension Data {
var bytes: Array<UInt8> { Array(self) }
func toHexString() -> String { bytes.toHexString() }
}
| 14.411765 | 56 | 0.608163 |
87782ed3787c878aa21a37eba11d101a9d7d3b1e | 403 | //
// EmojiCounterView.swift
// FruitCounter
//
// Created by Ken Krzeminski on 7/17/20.
// Copyright © 2020 Ken Krzeminski. All rights reserved.
//
import SwiftUI
struct EmojiCounterView: View {
let emoji: String
let count: Int
let font: Font
var body: some View {
VStack {
Text(emoji).font(font)
Text("\(count)").font(font)
}
}
}
| 17.521739 | 57 | 0.583127 |
646909e5349842ee63ba8070b561773440d04bee | 167 | //
// DateObject.swift
// Spottie
//
// Created by Lee Jun Kit on 22/5/21.
//
struct DateObject: Codable {
var year: Int
var month: Int
var day: Int
}
| 12.846154 | 38 | 0.598802 |
8f255cdd3699f4eee22018c574cd18418282aabf | 6,918 | // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import CoreGraphics
import MaterialComponents.MaterialColorScheme
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialAppBar_ColorThemer
import MaterialComponents.MaterialAppBar_TypographyThemer
import MaterialComponents.MaterialTabs
import MaterialComponents.MaterialTypographyScheme
import MaterialComponents.MaterialFlexibleHeader_CanAlwaysExpandToMaximumHeight
// An example that demonstrates the behavior of an App Bar with Tabs and manually swapped tab view
// controllers. This example is distinct from a typical tab bar view controller in that it does not
// make use of a horizontally-paging scroll view. This example also makes use of the
// canAlwaysExpandToMaximumHeight API to allow the header to maintain its expanded state when
// swapping between tabs.
class AppBarManualTabsExample: UIViewController {
lazy var appBarViewController: MDCAppBarViewController = self.makeAppBar()
var colorScheme = MDCSemanticColorScheme()
var typographyScheme = MDCTypographyScheme()
fileprivate let firstTab = SimpleTableViewController()
fileprivate let secondTab = SimpleTableViewController()
private var currentTab: SimpleTableViewController? = nil
lazy var tabBar: MDCTabBar = {
let tabBar = MDCTabBar()
tabBar.items = [
UITabBarItem(title: "First", image: nil, tag:0),
UITabBarItem(title: "Second", image: nil, tag:1)
]
tabBar.delegate = self
return tabBar
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.title = "Tab Bar Example"
self.firstTab.title = "First"
self.secondTab.title = "Second"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
MDCAppBarColorThemer.applyColorScheme(colorScheme, to: appBarViewController)
MDCAppBarTypographyThemer.applyTypographyScheme(typographyScheme, to: appBarViewController)
// Need to update the status bar style after applying the theme.
setNeedsStatusBarAppearanceUpdate()
view.backgroundColor = colorScheme.backgroundColor
view.addSubview(appBarViewController.view)
appBarViewController.didMove(toParentViewController: self)
switchToTab(firstTab)
}
fileprivate func switchToTab(_ tab: SimpleTableViewController) {
appBarViewController.headerView.trackingScrollWillChange(toScroll: tab.tableView)
if let currentTab = currentTab {
currentTab.headerView = nil
currentTab.willMove(toParentViewController: nil)
currentTab.view.removeFromSuperview()
currentTab.removeFromParentViewController()
}
if let tabView = tab.view {
tabView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tabView.frame = view.bounds
}
view.addSubview(tab.tableView)
view.sendSubview(toBack: tab.tableView)
tab.didMove(toParentViewController: self)
tab.headerView = appBarViewController.headerView
appBarViewController.headerView.trackingScrollView = tab.tableView
currentTab = tab
}
@objc func changeAlignmentDidTouch(sender: UIButton) {
firstTab.title = "First"
switchToTab(firstTab)
}
@objc func changeAppearance(fromSender sender: UIButton) {
secondTab.title = "Second"
switchToTab(secondTab)
}
// MARK: Private
private func makeAppBar() -> MDCAppBarViewController {
let appBarViewController = MDCAppBarViewController()
addChildViewController(appBarViewController)
// Give the tab bar enough height to accomodate all possible item appearances.
appBarViewController.headerView.minMaxHeightIncludesSafeArea = false
appBarViewController.inferTopSafeAreaInsetFromViewController = true
appBarViewController.headerView.canAlwaysExpandToMaximumHeight = true
appBarViewController.headerView.sharedWithManyScrollViews = true
appBarViewController.headerView.minimumHeight = 56
appBarViewController.headerView.maximumHeight = 128
appBarViewController.headerStackView.bottomBar = tabBar
return appBarViewController
}
override var childViewControllerForStatusBarStyle: UIViewController? {
return appBarViewController
}
}
extension AppBarManualTabsExample: MDCTabBarDelegate {
func tabBar(_ tabBar: MDCTabBar, didSelect item: UITabBarItem) {
if item.tag == 0 {
switchToTab(firstTab)
} else {
switchToTab(secondTab)
}
}
}
extension AppBarManualTabsExample {
class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["App Bar", "Manual tabs"],
"primaryDemo": false,
"presentable": true,
]
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
private class SimpleTableViewController: UITableViewController {
var headerView: MDCFlexibleHeaderView?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel!.text = "\(title!): Row \(indexPath.item)"
return cell
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
headerView?.trackingScrollDidScroll()
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
headerView?.trackingScrollDidEndDecelerating()
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
headerView?.trackingScrollWillEndDragging(withVelocity: velocity, targetContentOffset: targetContentOffset)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
headerView?.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
| 33.100478 | 155 | 0.765684 |
1ef1b7a13bdb636b96937b6f3bcbc5110914b82f | 384 | //
// MZWorkerDeleteLabel.swift
// Muzzley-iOS
//
// Created by Jorge Mendes on 18/12/15.
// Copyright © 2015 Muzzley. All rights reserved.
//
import UIKit
class MZWorkerDeleteLabel: UILabel {
internal var parentModel: MZBaseWorkerDeviceViewModel?
internal var model: MZBaseWorkerItemViewModel?
internal var indexPath: IndexPath?
internal var position: Int?
}
| 20.210526 | 58 | 0.734375 |
563bdec27cb5c66ec7e9b66f762821b5f3f68292 | 14,774 | // RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
enum List<T> {
case Nil
// rdar://21927124
// CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(<type>T</type>, <type>List</type>)
indirect case Cons(T, List)
}
// CHECK: <kw>struct</kw> S {
struct S {
// CHECK: <kw>var</kw> x : <type>Int</type>
var x : Int
// CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type>
var y : Int.Int
// CHECK: <kw>var</kw> a, b : <type>Int</type>
var a, b : Int
}
enum EnumWithDerivedEquatableConformance : Int {
// CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} {
case CaseA
// CHECK-NEXT: <kw>case</kw> CaseA
case CaseB, CaseC
// CHECK-NEXT: <kw>case</kw> CaseB, CaseC
case CaseD = 30, CaseE
// CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE
}
// CHECK-NEXT: }
// CHECK: <kw>class</kw> MyCls {
class MyCls {
// CHECK: <kw>var</kw> www : <type>Int</type>
var www : Int
// CHECK: <kw>func</kw> foo(x: <type>Int</type>) {}
func foo(x: Int) {}
// CHECK: <kw>var</kw> aaa : <type>Int</type> {
var aaa : Int {
// CHECK: <kw>get</kw> {}
get {}
// CHECK: <kw>set</kw> {}
set {}
}
// CHECK: <kw>var</kw> bbb : <type>Int</type> {
var bbb : Int {
// CHECK: <kw>set</kw> {
set {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
}
// CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> {
subscript (i : Int, j : Int) -> Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> i + j
return i + j
}
// CHECK: <kw>set</kw>(v) {
set(v) {
// CHECK: v + i - j
v + i - j
}
}
// CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {}
func multi(_ name: Int, otherpart x: Int) {}
}
// CHECK-LABEL: <kw>class</kw> Attributes {
class Attributes {
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type>
@IBOutlet var v0: Int
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> v1: <type>String</type>
@IBOutlet @IBOutlet var v1: String
// CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v2: <type>String</type>
@objc @IBOutlet var v2: String
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> v3: <type>String</type>
@IBOutlet @objc var v3: String
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {}
@available(*, unavailable) func f1() {}
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {}
@available(*, unavailable) @IBAction func f2() {}
// CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {}
@IBAction @available(*, unavailable) func f3() {}
// CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {}
mutating func func_mutating_1() {}
// CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {}
nonmutating func func_mutating_2() {}
}
func stringLikeLiterals() {
// CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str>
var us1: UnicodeScalar = "a"
// CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str>
var us2: UnicodeScalar = "ы"
// CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str>
var ch1: Character = "a"
// CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str>
var ch2: Character = "あ"
// CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str>
var s1 = "abc абвгд あいうえお"
}
// CHECK: <kw>var</kw> globComp : <type>Int</type>
var globComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
}
// CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> {
func foo(n: Float) -> Int {
// CHECK: <kw>var</kw> fnComp : <type>Int</type>
var fnComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> a: <type>Int</type>
// CHECK: <kw>return</kw> <int>0</int>
var a: Int
return 0
}
}
// CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}()
var q = MyCls()
// CHECK: <kw>var</kw> ee = <str>"yoo"</str>;
var ee = "yoo";
// CHECK: <kw>return</kw> <int>100009</int>
return 100009
}
// CHECK: <kw>protocol</kw> Prot
protocol Prot {
// CHECK: <kw>typealias</kw> Blarg
typealias Blarg
// CHECK: <kw>func</kw> protMeth(x: <type>Int</type>)
func protMeth(x: Int)
// CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> }
var protocolProperty1: Int { get }
// CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> }
var protocolProperty2: Int { get set }
}
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}}
infix operator *-* : FunnyPrecedence
// CHECK: <kw>precedencegroup</kw> FunnyPrecedence
// CHECK-NEXT: <kw>associativity</kw>: <kw>left</kw>{{$}}
// CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence
precedencegroup FunnyPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
// CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence
infix operator *-+* : FunnyPrecedence
// CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-+*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}}
infix operator *--*
// CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *--*(l: Int, r: Int) -> Int { return l }
// CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {}
protocol Prot2 : Prot {}
// CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {}
class SubCls : MyCls, Prot {}
// CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}}
func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {}
func f(x: Int) -> Int {
// CHECK: <str>#"This is a raw string"#</str>
#"This is a raw string"#
// CHECK: <str>##"This is also a raw string"##</str>
##"This is also a raw string"##
// CHECK: <str>###"This is an unterminated raw string"</str>
###"This is an unterminated raw string"
// CHECK: <str>#"""This is a multiline raw string"""#</str>
#"""This is a multiline raw string"""#
// CHECK: <str>#"This is an </str>\#<anchor>(</anchor>interpolated<anchor>)</anchor><str> raw string"#</str>
#"This is an \#(interpolated) raw string"#
// CHECK: <str>#"This is a raw string with an invalid \##() interpolation"#</str>
#"This is a raw string with an invalid \##() interpolation"#
// CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str>
"This is string \(genFn({(a:Int -> Int) in a})) interpolation"
// CHECK: <str>"This is unterminated</str>
"This is unterminated
// CHECK: <str>"This is unterminated with ignored \(interpolation) in it</str>
"This is unterminated with ignored \(interpolation) in it
// CHECK: <str>"This is terminated with invalid \(interpolation" + "in it"</str>
"This is terminated with invalid \(interpolation" + "in it"
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline string.
// CHECK-NEXT: """</str>
"""
This is a multiline string.
"""
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline</str>\<anchor>(</anchor> <str>"interpolated"</str> <anchor>)</anchor><str>string
// CHECK-NEXT: </str>\<anchor>(</anchor>
// CHECK-NEXT: <str>"""
// CHECK-NEXT: inner
// CHECK-NEXT: """</str>
// CHECK-NEXT: <anchor>)</anchor><str>
// CHECK-NEXT: """</str>
"""
This is a multiline\( "interpolated" )string
\(
"""
inner
"""
)
"""
// CHECK: <str>"</str>\<anchor>(</anchor><int>1</int><anchor>)</anchor>\<anchor>(</anchor><int>1</int><anchor>)</anchor><str>"</str>
"\(1)\(1)"
}
// CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) {
func bar(x: Int) -> (Int, Float) {
// CHECK: foo({{(<type>)?}}Float{{(</type>)?}}())
foo(Float())
}
class GenC<T1,T2> {}
func test() {
// CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>()
var x = GenC<Int, Float>()
}
// CHECK: <kw>typealias</kw> MyInt = <type>Int</type>
typealias MyInt = Int
func test2(x: Int) {
// CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str>
"\(x)"
}
// CHECK: <kw>class</kw> Observers {
class Observers {
// CHECK: <kw>var</kw> p1 : <type>Int</type> {
var p1 : Int {
// CHECK: <kw>willSet</kw>(newValue) {}
willSet(newValue) {}
// CHECK: <kw>didSet</kw> {}
didSet {}
}
// CHECK: <kw>var</kw> p2 : <type>Int</type> {
var p2 : Int {
// CHECK: <kw>didSet</kw> {}
didSet {}
// CHECK: <kw>willSet</kw> {}
willSet {}
}
}
// CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) {
func test3(o: AnyObject) {
// CHECK: <kw>_</kw> = o <kw>is</kw> <type>MyCls</type> ? o <kw>as</kw> <type>MyCls</type> : o <kw>as</kw>! <type>MyCls</type> <kw>as</kw> <type>MyCls</type> + <int>1</int>
_ = o is MyCls ? o as MyCls : o as! MyCls as MyCls + 1
}
// CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> {
class MySubClass : MyCls {
// CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {}
override func foo(x: Int) {}
// CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {}
convenience init(a: Int) {}
}
// CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> }
var g1 = { (x: Int) -> Int in return 0 }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ {
infix operator ~~ {}
// CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ {
prefix operator *~~ {}
// CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* {
postfix operator ~~* {}
func test_defer() {
defer {
// CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int>
let x : Int = 0
}
}
func test6<T : Prot>(x: T) {}
// CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}}
// CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {}
func <#test1#> () {}
func funcTakingFor(for internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {}
func funcTakingIn(in internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {}
_ = 123
// CHECK: <int>123</int>
_ = -123
// CHECK: <int>-123</int>
_ = -1
// CHECK: <int>-1</int>
_ = -0x123
// CHECK: <int>-0x123</int>
_ = -3.1e-5
// CHECK: <float>-3.1e-5</float>
"--\"\(x) --"
// CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str>
func keywordAsLabel1(in: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {}
func keywordAsLabel2(for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {}
func keywordAsLabel3(if: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel4(_: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {}
func keywordAsLabel5(_: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel6(if func: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel6(if func: <type>Int</type>) {}
func foo1() {
// CHECK: <kw>func</kw> foo1() {
keywordAsLabel1(in: 1)
// CHECK: keywordAsLabel1(in: <int>1</int>)
keywordAsLabel2(for: 1)
// CHECK: keywordAsLabel2(for: <int>1</int>)
keywordAsLabel3(if: 1, for: 2)
// CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>)
keywordAsLabel5(1, for: 2)
// CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>)
_ = (if: 0, for: 2)
// CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>)
_ = (_: 0, _: 2)
// CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>)
}
func foo2(O1 : Int?, O2: Int?, O3: Int?) {
guard let _ = O1, var _ = O2, let _ = O3 else { }
// CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { }
if let _ = O1, var _ = O2, let _ = O3 {}
// CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {}
}
func keywordInCaseAndLocalArgLabel(_ for: Int, for in: Int, class _: Int) {
// CHECK: <kw>func</kw> keywordInCaseAndLocalArgLabel(<kw>_</kw> for: <type>Int</type>, for in: <type>Int</type>, class <kw>_</kw>: <type>Int</type>) {
switch(`for`, `in`) {
case (let x, let y):
// CHECK: <kw>case</kw> (<kw>let</kw> x, <kw>let</kw> y):
print(x, y)
@unknown default:
// CHECK: <attr-id>@unknown</attr-id> <kw>default</kw>:
()
}
}
// CHECK: <kw>class</kw> Ownership {
class Ownership {
// CHECK: <attr-builtin>weak</attr-builtin> <kw>var</kw> w
weak var w
// CHECK: <attr-builtin>unowned</attr-builtin> <kw>var</kw> u
unowned var u
// CHECK: <attr-builtin>unowned(unsafe)</attr-builtin> <kw>var</kw> uu
unowned(unsafe) var uu
}
// CHECK: <kw>let</kw> closure = { [<attr-builtin>weak</attr-builtin> x=bindtox, <attr-builtin>unowned</attr-builtin> y=bindtoy, <attr-builtin>unowned(unsafe)</attr-builtin> z=bindtoz] <kw>in</kw> }
let closure = { [weak x=bindtox, unowned y=bindtoy, unowned(unsafe) z=bindtoz] in }
protocol FakeClassRestrictedProtocol : `class` {}
// CHECK: <kw>protocol</kw> FakeClassRestrictedProtocol : <type>`class`</type> {}
// FIXME: rdar://42801404: OLD and NEW should be the same '<type>`class`</type>'.
// CHECK: <kw>func</kw> foo() -> <kw>some</kw> <type>P</type> {}
func foo() -> some P {}
// CHECK: <kw>func</kw> foo() -> <kw>some</kw> <type>P</type> & <type>Q</type> {}
func foo() -> some P & Q {}
| 34.680751 | 198 | 0.584811 |
908ddbbed3d080bb199cecb7e34844ef6cb406bb | 1,445 | //
// ViewController.swift
// DemoApp
//
// Created by kris on 7/31/16.
// Copyright © 2016 kris. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect = CGRectMake(32, 80, 256, 256)
let imageView = UIImageView(frame: rect)
let image = UIImage(named: "poke")
imageView.image = image
imageView.userInteractionEnabled = true
self.view.addSubview(imageView)
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(_:)))
imageView.addGestureRecognizer(gesture)
}
func longPress(gesture: UILongPressGestureRecognizer) {
if (gesture.state == UIGestureRecognizerState.Began) {
let alertView = UIAlertController(title: "Info", message: "long press", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: .Default) { (action) in
}
alertView.addAction(okAction)
self.presentViewController(alertView, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 30.104167 | 129 | 0.644291 |
f56b0bf6a0497075c8ea019b60c2a01819c04237 | 4,439 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import RealmSwift
import XCTest
class ObjectiveCSupportTests: TestCase {
func testSupport() {
let realm = try! Realm()
try! realm.write {
realm.add(SwiftObject())
return
}
let results = realm.objects(SwiftObject.self)
let rlmResults = ObjectiveCSupport.convert(object: results)
XCTAssert(rlmResults.isKind(of: RLMResults<AnyObject>.self))
XCTAssertEqual(rlmResults.count, 1)
XCTAssertEqual(unsafeBitCast(rlmResults.firstObject(), to: SwiftObject.self).intCol, 123)
let list = List<SwiftObject>()
list.append(SwiftObject())
let rlmArray = ObjectiveCSupport.convert(object: list)
XCTAssert(rlmArray.isKind(of: RLMArray<AnyObject>.self))
XCTAssertEqual(unsafeBitCast(rlmArray.firstObject(), to: SwiftObject.self).floatCol, 1.23)
XCTAssertEqual(rlmArray.count, 1)
let rlmRealm = ObjectiveCSupport.convert(object: realm)
XCTAssert(rlmRealm.isKind(of: RLMRealm.self))
XCTAssertEqual(rlmRealm.allObjects("SwiftObject").count, 1)
let sortDescriptor: RealmSwift.SortDescriptor = "property"
XCTAssertEqual(sortDescriptor.keyPath,
ObjectiveCSupport.convert(object: sortDescriptor).keyPath,
"SortDescriptor.keyPath must be equal to RLMSortDescriptor.keyPath")
XCTAssertEqual(sortDescriptor.ascending,
ObjectiveCSupport.convert(object: sortDescriptor).ascending,
"SortDescriptor.ascending must be equal to RLMSortDescriptor.ascending")
}
func testConfigurationSupport() {
let realm = try! Realm()
try! realm.write {
realm.add(SwiftObject())
}
XCTAssertEqual(realm.configuration.fileURL,
ObjectiveCSupport.convert(object: realm.configuration).fileURL,
"Configuration.fileURL must be equal to RLMConfiguration.fileURL")
XCTAssertEqual(realm.configuration.inMemoryIdentifier,
ObjectiveCSupport.convert(object: realm.configuration).inMemoryIdentifier,
"Configuration.inMemoryIdentifier must be equal to RLMConfiguration.inMemoryIdentifier")
#if !SWIFT_PACKAGE
XCTAssertEqual(realm.configuration.syncConfiguration?.realmURL,
ObjectiveCSupport.convert(object: realm.configuration).syncConfiguration?.realmURL,
"Configuration.syncConfiguration must be equal to RLMConfiguration.syncConfiguration")
#endif
XCTAssertEqual(realm.configuration.encryptionKey,
ObjectiveCSupport.convert(object: realm.configuration).encryptionKey,
"Configuration.encryptionKey must be equal to RLMConfiguration.encryptionKey")
XCTAssertEqual(realm.configuration.readOnly,
ObjectiveCSupport.convert(object: realm.configuration).readOnly,
"Configuration.readOnly must be equal to RLMConfiguration.readOnly")
XCTAssertEqual(realm.configuration.schemaVersion,
ObjectiveCSupport.convert(object: realm.configuration).schemaVersion,
"Configuration.schemaVersion must be equal to RLMConfiguration.schemaVersion")
XCTAssertEqual(realm.configuration.deleteRealmIfMigrationNeeded,
ObjectiveCSupport.convert(object: realm.configuration).deleteRealmIfMigrationNeeded,
"Configuration.deleteRealmIfMigrationNeeded must be equal to RLMConfiguration.deleteRealmIfMigrationNeeded")
}
}
| 44.838384 | 131 | 0.660509 |
62cf0dc05fdd9173f6781a101adbecad68e1f4e3 | 352 |
import java_swift
/// generated by: genswift.java 'java/lang|java/util|java/sql' 'Sources' '../java' ///
/// interface com.lumyk.swiftbindings.ProjectsBinding ///
public protocol ProjectsBinding: JavaProtocol {
}
open class ProjectsBindingForward: JNIObjectForward, ProjectsBinding {
private static var ProjectsBindingJNIClass: jclass?
}
| 18.526316 | 86 | 0.755682 |
f5ee1db5f282e35ea9fc4e557f2d0497a22ffe71 | 1,991 | //
// marvel_appUITests.swift
// marvel-appUITests
//
// Created by Ruben Marquez on 15/06/2021.
//
import XCTest
class marvel_appUITests: XCTestCase {
override func setUpWithError() throws {
// 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
// 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 tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
app.tables["marvelList_tableView"].children(matching: .cell).matching(identifier: "marvelList_tableViewCell").element(boundBy: 0).staticTexts["marvelList_cellLabel"].tap()
app.staticTexts["marvelDetail_title"].tap()
app.staticTexts["marvelDetail_description"].tap()
app.children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.tap()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 41.479167 | 275 | 0.684581 |
906f272bed9ff3b152c68a630afc158ce87185e0 | 12,281 | //
// CPCCalendarUnit.swift
// Copyright © 2018 Cleverpumpkin, Ltd. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: - Protocol declaration
/// Protocol containing common interface for CPCDay, CPCWeek, CPCMonth and CPCYear.
public protocol CPCCalendarUnitBase: CustomStringConvertible, CustomDebugStringConvertible, Strideable, Hashable, CPCDateInterval where Stride == Int {
/// Calendar of the calenar unit.
var calendar: Calendar { get }
/// Creates a new calendar unit that contains a given date in current time zone according to system calendar.
///
/// - Parameters:
/// - date: Date to perform calculations for.
init (containing date: Date);
/// Creates a new calendar unit that contains a given date according to system calendar.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - timeZone: Time zone to perform calculations in.
init (containing date: Date, timeZone: TimeZone);
/// Creates a new calendar unit that contains a given date in current time zone according to calendar with supplied identifier.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - calendarIdentifier: Identifier of calendar to perform calculations with.
init (containing date: Date, calendarIdentifier: Calendar.Identifier);
/// Creates a new calendar unit that contains a given date according to supplied calendar.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - calendar: Calendar to perform calculations with.
init (containing date: Date, calendar: Calendar);
/// Creates a new calendar unit that contains a given date according to calendar with supplied identifier.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - timeZone: Time zone to perform calculations in.
/// - calendarIdentifier: Identifier of calendar to perform calculations with.
init (containing date: Date, timeZone: TimeZone, calendarIdentifier: Calendar.Identifier);
/// Creates a new calendar unit that contains a given date according to supplied calendar and time zone.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - timeZone: Time zone to perform calculations in.
/// - calendar: Calendar to perform calculations with.
init (containing date: Date, timeZone: TimeZone, calendar: Calendar);
/// Creates a new calendar unit that contains a given date according to the calendar of another calendar unit.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - otherUnit: Calendar source.
init (containing date: Date, calendarOf otherUnit: CPCDay);
/// Creates a new calendar unit that contains a given date according to the calendar of another calendar unit.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - otherUnit: Calendar source.
init (containing date: Date, calendarOf otherUnit: CPCWeek);
/// Creates a new calendar unit that contains a given date according to the calendar of another calendar unit.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - otherUnit: Calendar source.
init (containing date: Date, calendarOf otherUnit: CPCMonth);
/// Creates a new calendar unit that contains a given date according to the calendar of another calendar unit.
///
/// - Parameters:
/// - date: Date to perform calculations for.
/// - otherUnit: Calendar source.
init (containing date: Date, calendarOf otherUnit: CPCYear);
}
/// Common protocol implementing most of CPCDay, CPCWeek, CPCMonth and CPCYear functionality.
internal protocol CPCCalendarUnit: CPCCalendarUnitBase {
/// Type serving as a storage for calendar unit info.
associatedtype BackingType where BackingType: CPCCalendarUnitBackingType;
/// Calendar unit that is represented by this model type.
static var representedUnit: Calendar.Component { get };
/// DateFormatter-compatible string to generate `description`s and `debugDescription`s.
static var descriptionDateFormatTemplate: String { get };
/// Calendar that is used to calculate unit's `start` an `end` dates and related units.
var calendar: Calendar { get };
/// Unit's calendar that is wrapped in `CalendarWrapper` object for performance reasons.
var calendarWrapper: CalendarWrapper { get };
/// "Raw" value of calendar unit, e.g. month and year values for `CPCMonth`.
var backingValue: BackingType { get };
/// Creates a new calendar unit.
///
/// - Parameters:
/// - value: Backing value representing calendar unit.
/// - calendar: Calendar to perform various calculations with.
init (backedBy value: BackingType, calendar: CalendarWrapper);
}
// MARK: - Default implementations
extension CPCCalendarUnitBase {
public init (containing date: Date, timeZone: TimeZone, calendar: Calendar) {
var calendar = calendar;
calendar.timeZone = timeZone;
self.init (containing: date, calendar: calendar);
}
public init (containing date: Date, timeZone: TimeZone) {
self.init (containing: date, timeZone: timeZone, calendar: .currentUsed);
}
public init (containing date: Date) {
self.init (containing: date, timeZone: .current);
}
public init (containing date: Date, timeZone: TimeZone, calendarIdentifier: Calendar.Identifier) {
var calendar = Calendar (identifier: calendarIdentifier);
calendar.locale = .currentUsed;
self.init (containing: date, timeZone: timeZone, calendar: calendar);
}
public init (containing date: Date, calendarIdentifier: Calendar.Identifier) {
self.init (containing: date, timeZone: .current, calendarIdentifier: calendarIdentifier);
}
}
extension CPCCalendarUnit {
internal typealias CalendarWrapper = CPCCalendarWrapper;
@inlinable
public var calendar: Calendar {
return self.calendarWrapper.calendar;
}
@inlinable
public var start: Date {
return self.backingValue.startDate (using: self.calendar);
}
@inlinable
public var end: Date {
return guarantee (self.calendar.date (byAdding: Self.representedUnit, value: 1, to: self.start));
}
public static func == (lhs: Self, rhs: Self) -> Bool {
return (lhs.calendarWrapper === rhs.calendarWrapper) && (lhs.backingValue == rhs.backingValue);
}
#if swift(>=4.2)
public func hash (into hasher: inout Hasher) {
hasher.combine (self.calendarWrapper);
hasher.combine (self.backingValue);
}
#else
public var hashValue: Int {
return self.backingValue.hashValue * 7 &+ self.calendarWrapper.hashValue * 11;
}
#endif
@usableFromInline
internal init (containing date: Date, calendar: CalendarWrapper) {
self.init (backedBy: BackingType (containing: date, calendar: calendar.calendar), calendar: calendar);
}
public init (containing date: Date, calendarOf otherUnit: CPCDay) {
self.init (containing: date, calendar: otherUnit.calendarWrapper);
}
public init (containing date: Date, calendarOf otherUnit: CPCWeek) {
self.init (containing: date, calendar: otherUnit.calendarWrapper);
}
public init (containing date: Date, calendarOf otherUnit: CPCMonth) {
self.init (containing: date, calendar: otherUnit.calendarWrapper);
}
public init (containing date: Date, calendarOf otherUnit: CPCYear) {
self.init (containing: date, calendar: otherUnit.calendarWrapper);
}
}
/// Test equivalence of units' calendars and abort if they differ.
///
/// - Parameters:
/// - first: First calendar unit.
/// - second: Second calendar unit.
/// - Returns: Calendar of both of supplied units.
internal func resultingCalendarForOperation <T, U> (for first: T, _ second: U) -> CPCCalendarWrapper where T: CPCCalendarUnit, U: CPCCalendarUnit {
let calendar = first.calendarWrapper;
guard second.calendarWrapper == calendar else {
fatalError ("[CrispyCalendar] Sanity check failure: cannot decide on resulting calendar for operation on \(T.self) and \(U.self) values: incompatible calendars \(calendar.calendar, second.calendar)");
}
return calendar;
}
// MARK: - Parent protocol conformances.
extension CPCCalendarUnit {
public func distance (to other: Self) -> Int {
if let cachedResult = self.cachedDistance (to: other) {
return cachedResult;
}
let calendar = resultingCalendarForOperation (for: self, other);
let result = self.backingValue.distance (to: other.backingValue, using: calendar.calendar);
self.cacheDistance (result, to: other);
return result;
}
public func advanced (by n: Int) -> Self {
if let cachedResult = self.cachedAdvancedUnit (by: n) {
return cachedResult;
}
let result = Self (backedBy: self.backingValue.advanced (by: n, using: self.calendar), calendar: self.calendarWrapper);
self.cacheUnitValue (result, advancedBy: n);
return result;
}
}
extension CPCCalendarUnit {
private var dateIntervalFormatter: DateIntervalFormatter {
return DateIntervalFormatter.calendarUnitIntervalFormatter (for: Self.self, calendar: self.calendarWrapper);
}
public var description: String {
return self.dateIntervalFormatter.string (from: self.start, to: self.start);
}
public var debugDescription: String {
let intervalFormatter = self.dateIntervalFormatter, calendar = self.calendar, calendarID = calendar.identifier, locale = calendar.locale ?? .currentUsed;
return "<\(Self.self): \(intervalFormatter.string (from: self.start, to: self.end)); backing: \(self.backingValue); calendar: \(locale.localizedString (for: calendarID) ?? "\(calendarID)"); locale: \(locale.identifier)>";
}
}
fileprivate extension DateIntervalFormatter {
private struct CacheKey: Hashable {
private let unitType: ObjectIdentifier;
private unowned let calendar: CPCCalendarWrapper;
#if swift(>=4.2)
public func hash (into hasher: inout Hasher) {
hasher.combine (self.unitType);
hasher.combine (self.calendar);
}
#else
public var hashValue: Int {
return self.unitType.hashValue ^ self.calendar.hashValue;
}
#endif
fileprivate static func == (lhs: CacheKey, rhs: CacheKey) -> Bool {
return (lhs.unitType == rhs.unitType) && (lhs.calendar === rhs.calendar);
}
fileprivate init <Unit> (for unitType: Unit.Type, calendar: CPCCalendarWrapper) where Unit: CPCCalendarUnit {
self.unitType = ObjectIdentifier (unitType);
self.calendar = calendar;
}
}
private static var calendarUnitIntervalFormatters = UnfairThreadsafeStorage ([CacheKey: DateIntervalFormatter] ());
fileprivate static func calendarUnitIntervalFormatter <Unit> (for unitType: Unit.Type, calendar: CPCCalendarWrapper) -> DateIntervalFormatter where Unit: CPCCalendarUnit {
let key = CacheKey (for: unitType, calendar: calendar);
return self.calendarUnitIntervalFormatters.withMutableStoredValue {
if let storedValue = $0 [key] {
return storedValue;
}
let formatter = DateIntervalFormatter ();
formatter.dateTemplate = Unit.descriptionDateFormatTemplate;
$0 [key] = formatter;
return formatter;
};
}
}
internal extension Locale {
internal static var currentUsed: Locale {
return Bundle.main.preferredLocalizations.first.map (Locale.init) ?? .current;
}
}
internal extension Calendar {
internal static var currentUsed: Calendar {
var result = Calendar.current;
result.locale = .currentUsed;
return result;
}
}
| 38.021672 | 223 | 0.735689 |
011b5cf003f78c99a6f4bf3f8d419575d488639b | 257 | //
// FBReactionAimationsApp.swift
// FBReactionAimations
//
// Created by recherst on 2021/9/20.
//
import SwiftUI
@main
struct FBReactionAimationsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 14.277778 | 37 | 0.614786 |
e55ce7018ebacff9220f40b48e9e32df96d389fc | 785 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "swampgen",
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "swampgen",
dependencies: []),
.testTarget(
name: "swampgenTests",
dependencies: ["swampgen"]),
]
)
| 34.130435 | 116 | 0.626752 |
90bdcb910f13c269a0d92a546add36c38570beb9 | 6,796 | // RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
@objc class Foo : NSObject {
// Bridging dictionary parameters
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
func bridge_Dictionary_param(_ dict: Dictionary<Foo, Foo>) {
// CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
// CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
// CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
// CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}F
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
}
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo'
// Bridging dictionary results
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
func bridge_Dictionary_result() -> Dictionary<Foo, Foo> {
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: [[DICT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF
// CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]]
// CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]]
// CHECK: destroy_value [[DICT]]
// CHECK: return [[NSDICT]] : $NSDictionary
}
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo'
var property: Dictionary<Foo, Foo> = [:]
// Property getter
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[GETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvg : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: [[DICT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF
// CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]]
// CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]]
// CHECK: destroy_value [[DICT]]
// CHECK: return [[NSDICT]] : $NSDictionary
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvgTo'
// Property setter
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvsTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
// CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
// CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
// CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
// CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvs : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vsTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
@objc var nonVerbatimProperty: Dictionary<String, Int> = [:]
}
func ==(x: Foo, y: Foo) -> Bool { }
| 72.297872 | 208 | 0.670689 |
f8794af04649b7671b43022b75a25f7d0fc3d062 | 1,658 | //
// AttrKey.swift
// AttrKit
//
// Created by HanGang on 2020/7/9.
// Copyright © 2020 NickMeepo. All rights reserved.
//
import Foundation
internal enum AttrKey {
case font
case changeFontSize
case addFontTraits
case removeFontTraits
case alignment
case lineBreakMode
case lineSpacing
case paragraphSpacing
case paragraphSpacingBefore
case firstLineHeadIndent
case headIndent
case tailIndent
case minimumLineHeight
case maximumLineHeight
case lineHeightMultiple
case hyphenationFactor
case baseWritingDirection
case allowsDefaultTighteningForTruncation
case defaultTabInterval
case addTabStop
case removeTabStop
case underline
case strikethrough
case foreground
case background
case stroke
case ligature
case kern
case expansion
case shadow
case textEffect
case obliqueness
case baseline
case link
case writingDirection
case glyphForm
case erased
case fixed
case fromHere
case style
#if os(macOS)
case cursor
case markedClauseSegment
case spellingState
case superScript
case textAlternatives
case toolTip
case tighteningFactorForTruncation
/// The name of a glyph info object.
/// The NSLayoutManager object assigns the glyph specified by this NSGlyphInfo object to the entire attribute range, provided that its contents match the specified base string, and that the specified glyph is available in the font specified by NSFontAttributeName.
// case glyphInfo
#endif
}
| 14.54386 | 268 | 0.698432 |
bbbfea23000f24a1b9c148c4be9c7b519be47215 | 5,584 | //
// MSLoginInputView.swift
// MushengLoginMoudle
//
// Created by dss on 2021/11/11.
//
import UIKit
enum LoginInputStyle {
case none
case phone
case code
case password
}
class MSLoginInputView: UIView, UITextFieldDelegate {
///承载
private var contentV: UIView!
///号码区域按钮
private var phoneAreaBtn: UIButton!
///验证码
private var codeBtn: UIButton!
///密码眼
private var secretBtn: UIButton!
///输入框
private var inputTF: UITextField!
///下划线
private var baseLine: UIView!
///默认文字
var inputText: String = "" {
didSet {
inputTF.text = inputText
}
}
///站位文字
var placeHoler: String = "" {
didSet {
inputTF.placeholder = placeHoler
}
}
init(frame: CGRect, style: LoginInputStyle = .none) {
super.init(frame: frame)
setupInterface(style: style)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupInterface(style: LoginInputStyle) {
contentV = UIView.init(frame: .zero)
contentV.backgroundColor = .clear
self.addSubview(contentV)
contentV.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
inputTF = UITextField.init(frame: .zero)
inputTF.placeholder = placeHoler
inputTF.backgroundColor = .yellow
inputTF.delegate = self
inputTF.setContentHuggingPriority(.defaultHigh, for: .horizontal)
inputTF.textColor = .darkGray
contentV.addSubview(inputTF)
inputTF.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(15)
make.bottom.equalToSuperview()
make.top.equalToSuperview().inset(5)
}
if style == .phone {
phoneAreaBtn = UIButton.init(type: .custom)
phoneAreaBtn.setTitle("+86", for: .normal)
phoneAreaBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
phoneAreaBtn.backgroundColor = .orange
phoneAreaBtn.setImage(UIImage.init(named: "login_icon_tel"), for: .normal)
phoneAreaBtn.semanticContentAttribute = .forceRightToLeft
phoneAreaBtn.contentHorizontalAlignment = .left
phoneAreaBtn.setContentHuggingPriority(.required, for: .horizontal)
phoneAreaBtn.addTarget(self, action: #selector(phoneAreaBtnClick(sender:)), for: .touchUpInside)
contentV.addSubview(phoneAreaBtn)
phoneAreaBtn.snp.makeConstraints { make in
make.left.equalToSuperview().inset(15)
make.centerY.height.equalTo(inputTF)
}
inputTF.snp.remakeConstraints { make in
make.left.equalTo(phoneAreaBtn.snp.right).offset(5)
make.right.equalToSuperview().inset(15)
make.bottom.equalToSuperview()
make.top.equalToSuperview().inset(5)
}
} else if style == .code {
codeBtn = UIButton.init(type: .custom)
codeBtn.setTitle("发送验证码", for: .normal)
codeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
codeBtn.backgroundColor = .orange
codeBtn.setContentHuggingPriority(.required, for: .horizontal)
codeBtn.addTarget(self, action: #selector(codeBtnClick(sender:)), for: .touchUpInside)
contentV.addSubview(codeBtn)
codeBtn.snp.makeConstraints { make in
make.right.equalToSuperview().inset(15)
make.centerY.equalTo(inputTF)
}
inputTF.snp.remakeConstraints { make in
make.left.equalToSuperview().inset(15)
make.right.equalTo(codeBtn.snp.left).offset(-5)
make.bottom.equalToSuperview()
make.top.equalToSuperview().inset(5)
}
} else if style == .password {
secretBtn = UIButton.init(type: .custom)
secretBtn.setTitle("眼睛", for: .normal)
secretBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
secretBtn.backgroundColor = .red
secretBtn.setContentHuggingPriority(.required, for: .horizontal)
secretBtn.addTarget(self, action: #selector(secretBtnClick(sender:)), for: .touchUpInside)
contentV.addSubview(secretBtn)
secretBtn.snp.makeConstraints { make in
make.right.equalToSuperview().inset(15)
make.centerY.equalTo(inputTF)
}
inputTF.snp.remakeConstraints { make in
make.left.equalToSuperview().inset(15)
make.right.equalTo(secretBtn.snp.left).offset(-5)
make.bottom.equalToSuperview()
make.top.equalToSuperview().inset(5)
}
}
baseLine = UIView.init(frame: .zero)
baseLine.backgroundColor = .lightGray
contentV.addSubview(baseLine)
baseLine.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(15)
make.bottom.equalToSuperview()
make.height.equalTo(0.5)
}
}
///手机号区域选择事件
@objc func phoneAreaBtnClick(sender: UIButton) {
}
///验证码发送事件
@objc func codeBtnClick(sender: UIButton) {
}
///密码显示事件
@objc func secretBtnClick(sender: UIButton) {
}
}
| 32.847059 | 108 | 0.584885 |
e46e52da8c099addd7792aec819d3a68a3b00def | 1,943 | //
// ProfileEditor.swift
// SwiftUI_Landmark_App
//
// Created by Ashwin Das on 12/02/20.
// Copyright © 2020 Ashwin Das. All rights reserved.
//
import SwiftUI
struct ProfileEditor: View {
@Binding var profile: Profile
var dateRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .year, value: -1, to: profile.goalDate)!
let max = Calendar.current.date(byAdding: .year, value: 1, to: profile.goalDate)!
return min...max
}
var body: some View {
List {
HStack {
Text("Username").bold()
Divider()
TextField("Username", text: $profile.username)
}
Toggle(isOn: $profile.prefersNotifications) {
Text("Enable Notifications")
}
VStack(alignment: .leading, spacing: 20) {
Text("Seasonal Photo").bold()
Picker("Seasonal Photo", selection: $profile.seasonalPhoto) {
ForEach(Profile.Season.allCases, id: \.self) { season in
Text(season.rawValue).tag(season)
}
}
.pickerStyle(SegmentedPickerStyle())
}
.padding(.top)
VStack(alignment: .leading, spacing: 20) {
Text("Goal Date").bold()
DatePicker(
"Goal Date",
selection: $profile.goalDate,
in: dateRange,
displayedComponents: .date)
}
.padding(.top)
}
}
}
struct ProfileEditor_Previews: PreviewProvider {
static var previews: some View {
ProfileEditor(profile:.constant(.default))
}
}
| 31.852459 | 90 | 0.469377 |
16e18e42d71c8fa7ddf3518c32ca236e2622c42a | 1,427 | //
// Created by Daniel Strobusch on 2019-05-11.
//
import XCTest
@testable import NdArray
// swiftlint:disable:next type_name
class basic_functionsTestsInt: XCTestCase {
func testAbs() {
// 0d
do {
let a = NdArray<Int>.zeros([])
XCTAssertEqual(abs(a).shape, [])
}
// 2d effective 0d
do {
let a = NdArray<Int>.zeros([1, 0])
XCTAssertEqual(abs(a).shape, [1, 0])
}
// 1d contiguous
do {
let a = NdArray<Int>.range(from: -3, to: 3)
XCTAssertEqual(abs(a).dataArray, a.dataArray.map(abs))
}
// 1d not aligned
do {
let a = NdArray<Int>.range(from: -3, to: 3)[..., 2]
XCTAssertEqual(abs(a).dataArray, [3, 1, 1])
}
// 2d C contiguous
do {
let a = NdArray<Int>.range(from: -3, to: 3).reshaped([2, 3], order: .C)
XCTAssertEqual(abs(a).dataArray, [3, 2, 1, 0, 1, 2])
}
// 2d F contiguous
do {
let a = NdArray<Int>.range(from: -3, to: 3).reshaped([2, 3], order: .F)
XCTAssertEqual(abs(a).dataArray, [3, 2, 1, 0, 1, 2])
}
// 2d not aligned
do {
let a = NdArray<Int>.range(from: -5, to: 4 * 3 - 5).reshaped([4, 3], order: .C)[1..., 2]
XCTAssertEqual(abs(a).dataArray, [2, 1, 0, 4, 5, 6])
}
}
}
| 29.122449 | 100 | 0.479327 |
01568e6d99a2d4b04d145b57abfde254e580c9b3 | 4,556 | //
// RESTControllerTests.swift
// RESTControllerTests
//
// Created by Vahid Ajimine on 09.02.18.
// Copyright © 2018 Vahid Ajimine. All rights reserved.
//
import XCTest
@testable import RESTController
class RESTControllerTests: 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 testGetRestCall() {
let testDelegate = TestDelegate()
let testRestController = RESTController(delegate: testDelegate)
testDelegate.asyncExpectation = expectation(description: "JSON call with jsonplaceholder post call 1 return")
testRestController.restCall(url: "https://jsonplaceholder.typicode.com/posts/1", method: HTTPMethod.get)
wait(for: [testDelegate.asyncExpectation!], timeout: 10)
if let error = testDelegate.errorString{
XCTFail("didNotReceiveAPIResults triggered with the following \(error)")
return
}
guard let result = testDelegate.results else {
XCTFail("Expected result to be successful")
return
}
XCTAssertTrue(result["title"] != nil, result.description)
}
func testPostRestCall() {
let testDelegate = TestDelegate()
let testRestController = RESTController(delegate: testDelegate)
testDelegate.asyncExpectation = expectation(description: "JSON call with jsonplaceholder post call 1 return")
testRestController.restCall(url: "http://ip.jsontest.com/")
waitForExpectations(timeout: 1, handler: { (testError) in
if let error = testError{
XCTFail("waitForExpectations errored with \(error)")
}
if let error = testDelegate.errorString{
XCTFail("didNotReceiveAPIResults triggered with the following \(error)")
return
}
guard let result = testDelegate.results else {
XCTFail("Result is empty for testPostRestCal")
return
}
XCTAssertTrue(result["ip"] != nil, result.description)
})
}
func testFailedRestCall(){
let testDelegate = TestDelegate()
let testRestController = RESTController(delegate: testDelegate)
testDelegate.asyncExpectation = expectation(description: "FlixBusTest")
testRestController.restCall(url: "http://bogus.url.com/notreal")
waitForExpectations(timeout: 10, handler: { (testError) in
if let error = testError{
XCTFail("waitForExpectations errored with \(error)")
}
if let error = testDelegate.results{
XCTFail("didReceiveAPIResults triggered with the following \(error.description)")
return
}
guard let correctResponse = testDelegate.errorString else {
XCTFail("Expected result to be successful")
return
}
XCTAssertTrue(correctResponse == "", correctResponse)
})
}
func testPerformanceExample() {
/*
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
// */
}
//MARK: - RESTControllerDelegate
class TestDelegate: RESTControllerDelegate{
var results:[String:AnyObject]?
var errorString:String?
var asyncExpectation: XCTestExpectation?
init() {
}
func didNotReceiveAPIResults(error: String, url: String) {
guard let expectation = asyncExpectation else {
XCTFail("Test Delegate didNotReceiveAPIResults not set up properly")
return
}
errorString = error
results = nil
expectation.fulfill()
}
func didReceiveAPIResults(results: [String : AnyObject], url: String) {
guard let expectation = asyncExpectation else {
XCTFail("Test Delegate didReceiveAPIResults not set up properly")
return
}
errorString = nil
self.results = results
expectation.fulfill()
}
}
}
| 35.59375 | 117 | 0.601405 |
0398e9a54be14f1739da0a1d30288ef6f6dfc89d | 8,766 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// Aisle.swift
// Tracker
//
import Foundation
/// Wrapper class for Visited aisle tracking
@objcMembers public class Aisle: ScreenInfo {
/// Aisle level1 label
public var level1: String?
/// Aisle level2 label
public var level2: String?
/// Aisle level3 label
public var level3: String?
/// Aisle level4 label
public var level4: String?
/// Aisle level5 label
public var level5: String?
/// Aisle level6 label
public var level6: String?
override init(tracker: Tracker) {
super.init(tracker: tracker)
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
public init(level1: String) {
super.init()
self.level1 = level1
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
public convenience init(level1: String, level2: String) {
self.init(level1: level1)
self.level2 = level2
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
public convenience init(level1: String, level2: String, level3: String) {
self.init(level1: level1, level2: level2)
self.level3 = level3
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - level4: level4 label
public convenience init(level1: String, level2: String, level3: String, level4: String) {
self.init(level1: level1, level2: level2, level3: level3)
self.level4 = level4
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - level4: level4 label
/// - level5: level5 label
public convenience init(level1: String, level2: String, level3: String, level4: String, level5: String) {
self.init(level1: level1, level2: level2, level3: level3, level4: level4)
self.level5 = level5
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - level4: level4 label
/// - level5: level5 label
/// - level6: level6 label
public convenience init(level1: String, level2: String, level3: String, level4: String, level5: String, level6: String) {
self.init(level1: level1, level2: level2, level3: level3, level4: level4, level5: level5)
self.level6 = level6
}
/// Set parameters in buffer
override func setParams() {
var value: String?
if let optLevel1 = level1 {
value = optLevel1
}
if let optLevel2 = level2 {
if(value == nil) {
value = optLevel2
} else {
value! += "::" + optLevel2
}
}
if let optLevel3 = level3 {
if(value == nil) {
value = optLevel3
} else {
value! += "::" + optLevel3
}
}
if let optLevel4 = level4 {
if(value == nil) {
value = optLevel4
} else {
value! += "::" + optLevel4
}
}
if let optLevel5 = level5 {
if(value == nil) {
value = optLevel5
} else {
value! += "::" + optLevel5
}
}
if let optLevel6 = level6 {
if(value == nil) {
value = optLevel6
} else {
value! += "::" + optLevel6
}
}
if(value != nil) {
let encodeOption = ParamOption()
encodeOption.encode = true
_ = tracker.setParam("aisl", value: value!, options: encodeOption)
}
}
}
/// Wrapper class to manage aisles instances
public class Aisles {
/// Tracker instance
var tracker: Tracker
/**
Aisle initializer
- parameter tracker: the tracker instance
- returns: Aisle instance
*/
init(tracker: Tracker) {
self.tracker = tracker;
}
/// Add tagging data for an aisle
///
/// - Parameter level1: level1 label
/// - Returns: Aisle instance
@objc public func add(level1: String) -> Aisle {
return _add(level1: level1, level2: nil, level3: nil, level4: nil, level5: nil, level6: nil)
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - Returns: Aisle instance
@objc public func add(level1: String, level2: String) -> Aisle {
return _add(level1: level1, level2: level2, level3: nil, level4: nil, level5: nil, level6: nil)
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - Returns: Aisle instance
@objc public func add(level1: String, level2: String, level3: String) -> Aisle {
return _add(level1: level1, level2: level2, level3: level3, level4: nil, level5: nil, level6: nil)
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - level4: level4 label
/// - Returns: Aisle instance
@objc public func add(level1: String, level2: String, level3: String, level4: String) -> Aisle {
return _add(level1: level1, level2: level2, level3: level3, level4: level4, level5: nil, level6: nil)
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - level4: level4 label
/// - level5: level5 label
/// - Returns: Aisle instance
@objc public func add(level1: String, level2: String, level3: String, level4: String, level5: String) -> Aisle {
return _add(level1: level1, level2: level2, level3: level3, level4: level4, level5: level5, level6: nil)
}
/// Add tagging data for an aisle
///
/// - Parameters:
/// - level1: level1 label
/// - level2: level2 label
/// - level3: level3 label
/// - level4: level4 label
/// - level5: level5 label
/// - level6: level6 label
/// - Returns: Aisle instance
@objc public func add(level1: String, level2: String, level3: String, level4: String, level5: String, level6: String) -> Aisle {
return _add(level1: level1, level2: level2, level3: level3, level4: level4, level5: level5, level6: level6)
}
private func _add(level1: String?, level2: String?, level3: String?, level4: String?, level5: String?, level6: String?) -> Aisle {
let aisle = Aisle(tracker: tracker)
aisle.level1 = level1
aisle.level2 = level2
aisle.level3 = level3
aisle.level4 = level4
aisle.level5 = level5
aisle.level6 = level6
tracker.businessObjects[aisle.id] = aisle
return aisle
}
}
| 31.307143 | 142 | 0.579512 |
f796a847e82bb845ca65025cf9d84b7538da4348 | 3,173 | //
// SettingsView.swift
// ThinkerFarmExample
//
// Created by Erkan SIRIN on 16.11.2019.
// Copyright © 2019 Erkan SIRIN. All rights reserved.
//
import UIKit
import ThinkerFarm.Swift
class SettingsView: UIViewController {
@IBOutlet weak var showBoxesSwitch: UISwitch!
@IBOutlet weak var showLabelBackgroundSwitch: UISwitch!
@IBOutlet weak var showLabelSwitch: UISwitch!
@IBOutlet weak var tresholdLabel: UILabel!
@IBOutlet weak var settingsLabel: UILabel!
@IBOutlet weak var sliderThreshold: UISlider!
@IBOutlet weak var videoFrameRateLabel: UILabel!
@IBOutlet weak var videoFramerateSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
self.sliderThreshold.value = ModelSettings.threshold
tresholdLabel.text = "Threshold Value : \(ModelSettings.threshold)"
showBoxesSwitch.setOn(ModelSettings.HideBox, animated: true)
showLabelBackgroundSwitch.setOn(ModelSettings.hideBoxBackground, animated: true)
showLabelSwitch.setOn(ModelSettings.hideClassLabels, animated: true)
self.videoFramerateSlider.value = Float(ModelSettings.videoAnalysisFrameRate)
if Int(ModelSettings.videoAnalysisFrameRate) > 5 {
videoFrameRateLabel.text = "Video analysis frame rate: \(ModelSettings.videoAnalysisFrameRate). Warning high memory impact"
}else {
videoFrameRateLabel.text = "Video analysis frame rate: \(ModelSettings.videoAnalysisFrameRate)"
}
}
@IBAction func backAction(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func switchValueChange(_ sender: UISwitch) {
if sender.tag == 1 {
if sender.isOn {
ModelSettings.hideClassLabels = true
}else{
ModelSettings.hideClassLabels = false
}
}
if sender.tag == 2 {
if sender.isOn {
ModelSettings.hideBoxBackground = true
}else{
ModelSettings.hideBoxBackground = false
}
}
if sender.tag == 3 {
if sender.isOn {
ModelSettings.HideBox = true
}else{
ModelSettings.HideBox = false
}
}
}
@IBAction func videoFrameValueChange(_ sender: UISlider) {
ModelSettings.videoAnalysisFrameRate = Int(sender.value)
if Int(sender.value) > 5 {
videoFrameRateLabel.text = "Video analysis frame rate: \(Int(sender.value)). Warning high memory impact"
}else {
videoFrameRateLabel.text = "Video analysis frame rate: \(Int(sender.value))"
}
}
@IBAction func thresholdValue(_ sender: UISlider) {
ModelSettings.threshold = Float(sender.value)
tresholdLabel.text = "Threshold Value : \(Float(sender.value))"
}
}
| 30.219048 | 135 | 0.589032 |
71cb514f1034a9bb47247c4fccb71afe0570bf69 | 782 | import MixboxFoundation
final class PhotoSaverCompletion: NSObject {
private let completion: (DataResult<(), ErrorString>) -> ()
init(completion: @escaping (DataResult<(), ErrorString>) -> ()) {
self.completion = completion
}
var target: AnyObject? {
return self
}
var action: Selector {
return #selector(PhotoSaverCompletion.image(_:didFinishSavingWithError:contextInfo:))
}
@objc(image:didFinishSavingWithError:contextInfo:)
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
completion(.error(ErrorString(error.localizedDescription)))
} else {
completion(.data(()))
}
}
}
| 28.962963 | 105 | 0.638107 |
89b6ca57266b15798959b21535bcfc0fe3fd94c6 | 14,194 | //
// GitRepositorySettingsTableViewController.swift
// pass
//
// Created by Mingshen Sun on 21/1/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import passKit
import SVProgressHUD
import UIKit
class GitRepositorySettingsTableViewController: UITableViewController, PasswordAlertPresenter {
// MARK: - View Outlet
@IBOutlet var gitURLTextField: UITextField!
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var branchNameTextField: UITextField!
@IBOutlet var authSSHKeyCell: UITableViewCell!
@IBOutlet var authPasswordCell: UITableViewCell!
@IBOutlet var gitURLCell: UITableViewCell!
// MARK: - Properties
private var sshLabel: UILabel?
private let passwordStore = PasswordStore.shared
private let keychain = AppKeychain.shared
private var gitCredential: GitCredential {
GitCredential.from(
authenticationMethod: Defaults.gitAuthenticationMethod,
userName: Defaults.gitUsername,
keyStore: keychain
)
}
private var gitAuthenticationMethod: GitAuthenticationMethod {
get { Defaults.gitAuthenticationMethod }
set {
Defaults.gitAuthenticationMethod = newValue
updateAuthenticationMethodCheckView(for: newValue)
}
}
private var gitUrl: URL {
get { Defaults.gitURL }
set { Defaults.gitURL = newValue }
}
private var gitBranchName: String {
get { Defaults.gitBranchName }
set { Defaults.gitBranchName = newValue }
}
private var gitUsername: String {
get { Defaults.gitUsername }
set { Defaults.gitUsername = newValue }
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
gitURLTextField.text = gitUrl.absoluteString
usernameTextField.text = gitUsername
branchNameTextField.text = gitBranchName
sshLabel = authSSHKeyCell.subviews[0].subviews[0] as? UILabel
authSSHKeyCell.accessoryType = .detailButton
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Grey out ssh option if ssh_key is not present.
sshLabel?.isEnabled = keychain.contains(key: SshKey.PRIVATE.getKeychainKey())
updateAuthenticationMethodCheckView(for: gitAuthenticationMethod)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
// MARK: - UITableViewController Override
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if cell == authSSHKeyCell {
showSSHKeyActionSheet()
} else if cell == gitURLCell {
showGitURLFormatHelp()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if cell == authPasswordCell {
gitAuthenticationMethod = .password
} else if cell == authSSHKeyCell {
if !keychain.contains(key: SshKey.PRIVATE.getKeychainKey()) {
Utils.alert(title: "CannotSelectSshKey".localize(), message: "PleaseSetupSshKeyFirst.".localize(), controller: self)
gitAuthenticationMethod = .password
} else {
gitAuthenticationMethod = .key
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
override func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
// MARK: - Segue Handlers
@IBAction
private func save(_: Any) {
guard let gitURLTextFieldText = gitURLTextField.text, let gitURL = URL(string: gitURLTextFieldText.trimmed) else {
Utils.alert(title: "CannotSave".localize(), message: "SetGitRepositoryUrl".localize(), controller: self)
return
}
guard let branchName = branchNameTextField.text, !branchName.trimmed.isEmpty else {
Utils.alert(title: "CannotSave".localize(), message: "SpecifyBranchName.".localize(), controller: self)
return
}
if let scheme = gitURL.scheme {
switch scheme {
case "http", "https", "ssh":
if gitURL.user == nil, usernameTextField.text == nil {
Utils.alert(title: "CannotSave".localize(), message: "CannotFindUsername.".localize(), controller: self)
return
}
if let urlUsername = gitURL.user, let textFieldUsername = usernameTextField.text, urlUsername != textFieldUsername.trimmed {
Utils.alert(title: "CannotSave".localize(), message: "CheckEnteredUsername.".localize(), controller: self)
return
}
case "file":
break
default:
Utils.alert(title: "CannotSave".localize(), message: "Protocol is not supported", controller: self)
return
}
}
gitUrl = gitURL
gitBranchName = branchName.trimmed
gitUsername = (gitURL.user ?? usernameTextField.text ?? "git").trimmed
if passwordStore.repositoryExists() {
let overwriteAlert: UIAlertController = {
let alert = UIAlertController(title: "Overwrite?".localize(), message: "OperationWillOverwriteData.".localize(), preferredStyle: .alert)
alert.addAction(
UIAlertAction(title: "Overwrite".localize(), style: .destructive) { _ in
self.cloneAndSegueIfSuccess()
}
)
alert.addAction(UIAlertAction.cancel())
return alert
}()
present(overwriteAlert, animated: true)
} else {
cloneAndSegueIfSuccess()
}
}
private func cloneAndSegueIfSuccess() {
// Remember git credential password/passphrase temporarily, ask whether users want this after a successful clone.
Defaults.isRememberGitCredentialPassphraseOn = true
DispatchQueue.global(qos: .userInitiated).async {
do {
let transferProgressBlock: (UnsafePointer<git_transfer_progress>, UnsafeMutablePointer<ObjCBool>) -> Void = { git_transfer_progress, _ in
let gitTransferProgress = git_transfer_progress.pointee
let progress = Float(gitTransferProgress.received_objects) / Float(gitTransferProgress.total_objects)
SVProgressHUD.showProgress(progress, status: "Cloning Remote Repository")
}
let checkoutProgressBlock: (String, UInt, UInt) -> Void = { _, completedSteps, totalSteps in
let progress = Float(completedSteps) / Float(totalSteps)
SVProgressHUD.showProgress(progress, status: "CheckingOutBranch".localize(self.gitBranchName))
}
let options = self.gitCredential.getCredentialOptions(passwordProvider: self.present)
try self.passwordStore.cloneRepository(
remoteRepoURL: self.gitUrl,
branchName: self.gitBranchName,
options: options,
transferProgressBlock: transferProgressBlock,
checkoutProgressBlock: checkoutProgressBlock
)
SVProgressHUD.dismiss {
let savePassphraseAlert: UIAlertController = {
let alert = UIAlertController(title: "Done".localize(), message: "WantToSaveGitCredential?".localize(), preferredStyle: .alert)
alert.addAction(
UIAlertAction(title: "No".localize(), style: .default) { _ in
Defaults.isRememberGitCredentialPassphraseOn = false
self.passwordStore.gitPassword = nil
self.passwordStore.gitSSHPrivateKeyPassphrase = nil
self.performSegue(withIdentifier: "saveGitServerSettingSegue", sender: self)
}
)
alert.addAction(
UIAlertAction(title: "Yes".localize(), style: .destructive) { _ in
Defaults.isRememberGitCredentialPassphraseOn = true
self.performSegue(withIdentifier: "saveGitServerSettingSegue", sender: self)
}
)
return alert
}()
DispatchQueue.main.async {
self.present(savePassphraseAlert, animated: true)
}
}
} catch {
SVProgressHUD.dismiss {
let error = error as NSError
var message = error.localizedDescription
if let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError {
message = "\(message)\n\("UnderlyingError".localize(underlyingError.localizedDescription))"
}
DispatchQueue.main.async {
Utils.alert(title: "Error".localize(), message: message, controller: self)
}
}
}
}
}
@IBAction
private func importSSHKey(segue: UIStoryboardSegue) {
guard let sourceController = segue.source as? KeyImporter, sourceController.isReadyToUse() else {
return
}
importSSHKey(using: sourceController)
}
private func importSSHKey(using keyImporter: KeyImporter) {
DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
do {
try keyImporter.importKeys()
DispatchQueue.main.async {
SVProgressHUD.showSuccess(withStatus: "Imported".localize())
SVProgressHUD.dismiss(withDelay: 1)
Defaults.gitSSHKeySource = type(of: keyImporter).keySource
self.gitAuthenticationMethod = .key
self.sshLabel?.isEnabled = true
}
} catch {
Utils.alert(title: "Error".localize(), message: error.localizedDescription, controller: self)
}
}
}
// MARK: - Helper Functions
private func showSSHKeyActionSheet() {
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
optionMenu.addAction(
UIAlertAction(title: SSHKeyUrlImportTableViewController.menuLabel, style: .default) { _ in
self.performSegue(withIdentifier: "setGitSSHKeyByURLSegue", sender: self)
}
)
optionMenu.addAction(
UIAlertAction(title: SSHKeyArmorImportTableViewController.menuLabel, style: .default) { _ in
self.performSegue(withIdentifier: "setGitSSHKeyByArmorSegue", sender: self)
}
)
optionMenu.addAction(
UIAlertAction(title: SSHKeyFileImportTableViewController.menuLabel, style: .default) { _ in
self.performSegue(withIdentifier: "setGitSSHKeyByFileSegue", sender: self)
}
)
if isReadyToUse() {
optionMenu.addAction(
UIAlertAction(title: "\(Self.menuLabel) (\("Import".localize()))", style: .default) { _ in
self.importSSHKey(using: self)
}
)
} else {
optionMenu.addAction(
UIAlertAction(title: "\(Self.menuLabel) (\("Tips".localize()))", style: .default) { _ in
let title = "Tips".localize()
let message = "SshCopyPrivateKeyToPass.".localize()
Utils.alert(title: title, message: message, controller: self)
}
)
}
if Defaults.gitSSHKeySource != nil {
optionMenu.addAction(
UIAlertAction(title: "RemoveSShKeys".localize(), style: .destructive) { _ in
self.passwordStore.removeGitSSHKeys()
Defaults.gitSSHKeySource = nil
self.sshLabel?.isEnabled = false
self.gitAuthenticationMethod = .password
}
)
}
optionMenu.addAction(UIAlertAction.cancel())
optionMenu.popoverPresentationController?.sourceView = authSSHKeyCell
optionMenu.popoverPresentationController?.sourceRect = authSSHKeyCell.bounds
present(optionMenu, animated: true)
}
private func updateAuthenticationMethodCheckView(for method: GitAuthenticationMethod) {
let passwordCheckView = authPasswordCell.viewWithTag(1001)
let sshKeyCheckView = authSSHKeyCell.viewWithTag(1001)
switch method {
case .password:
passwordCheckView?.isHidden = false
sshKeyCheckView?.isHidden = true
case .key:
passwordCheckView?.isHidden = true
sshKeyCheckView?.isHidden = false
}
}
private func showGitURLFormatHelp() {
let message = """
https://example.com[:port]/project.git
ssh://[user@]server[:port]/project.git
[user@]server:project.git (no scheme)
"""
Utils.alert(title: "Git URL Format", message: message, controller: self)
}
}
extension GitRepositorySettingsTableViewController: KeyImporter {
static let keySource = KeySource.itunes
static let label = "ITunesFileSharing".localize()
func isReadyToUse() -> Bool {
KeyFileManager.PrivateSsh.doesKeyFileExist()
}
func importKeys() throws {
try KeyFileManager.PrivateSsh.importKeyFromFileSharing()
}
}
| 40.904899 | 153 | 0.601029 |
5b7e2fee424e3a5881a77c708b14d6869bbb7e76 | 1,486 | //
// EditButtonTableViewCell.swift
// DBBBuilder-Swift
//
// Created by Dennis Birch on 3/1/16.
// Copyright © 2016 Dennis Birch. All rights reserved.
//
import UIKit
@objc protocol EditButtonTableViewHandler {
@objc func editButtonTapped(sender: EditButtonTableViewCell, event: UIEvent)
}
class EditButtonTableViewCell: UITableViewCell {
var editImage: UIImage?
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
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
}
func configureWithTitle(title: String, editImage: UIImage?, buttonHandler: EditButtonTableViewHandler) {
infoLabel.text = title
if let image = editImage {
editButton.addTarget(buttonHandler,
action: #selector(buttonHandler.editButtonTapped),
for: .touchDown)
editButton.setBackgroundImage(editImage, for: .normal)
widthConstraint.constant = image.size.width
heightConstraint.constant = image.size.height
} else {
widthConstraint.constant = 0
heightConstraint.constant = 0
editButton.setBackgroundImage(nil, for: .normal)
}
}
}
| 28.576923 | 105 | 0.710633 |
ebddd719b83641e25630ecf657935a427fe916b4 | 1,186 | //
// SSNewsHeadlinesUITests.swift
// SSNewsHeadlinesUITests
//
// Created by Suraj Shandil on 7/23/19.
// Copyright © 2019 Suraj Shandil. All rights reserved.
//
import XCTest
class SSNewsHeadlinesUITests: 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.
}
}
| 33.885714 | 182 | 0.696459 |
79dde3241ca1f71452ea547f86b5e8fc19bf4bc5 | 450 | import uHome
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UIViewController(nibName: nil, bundle: nil)
window?.makeKeyAndVisible()
return true
}
}
| 30 | 120 | 0.728889 |
6a2f615832476e09fb541e8b880281c47de53a44 | 25,983 | // SwiftyXML.swift
//
// Copyright (c) 2016 ChenYunGui (陈云贵)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum XMLSubscriptKey {
case index(Int) // such as: 1
case key(String) // such as: "childName"
case keyChain(KeyChain) // such as: "#childName.childName.@attributeName"
case attribute(String) // such as: "@attributeName"
}
public enum XMLError : Error {
case subscriptFailue(String)
case initFailue(String)
case wrongChain(String)
}
public enum XMLSubscriptResult {
case null(String) // means: null(error: String)
case xml(XML, String) // means: xml(xml: XML, path: String)
case array([XML], String) // means: xml(xmls: [XML], path: String)
case string(String, String) // means: string(value: String, path: String)
public subscript(index: Int) -> XMLSubscriptResult {
return self[XMLSubscriptKey.index(index)]
}
public subscript(key: String) -> XMLSubscriptResult {
if let subscripKey = getXMLSubscriptKey(from: key) {
return self[subscripKey]
} else {
return .null("wrong key chain format")
}
}
public subscript(key: XMLSubscriptKey) -> XMLSubscriptResult {
func subscriptResult(_ result: XMLSubscriptResult, byIndex index: Int) -> XMLSubscriptResult {
switch result {
case .null(_): return self
case .string(_, let path):
return .null(path + ": attribute can not subscript by index: \(index)")
case .xml(_, let path):
return .null(path + ": single xml can not subscript by index: \(index)")
case .array(let xmls, let path):
if xmls.indices.contains(index) {
return .xml(xmls[index], path + "[\(index)]")
} else {
return .null(path + ": index:\(index) out of bounds: \(xmls.indices)")
}
}
}
func subscriptResult(_ result: XMLSubscriptResult, byKey key: String) -> XMLSubscriptResult {
switch result {
case .null(_): return self
case .string(_, let path):
return .null(path + ": attribute can not subscript by key: \(key)")
case .xml(let xml, let path):
let array = xml.children.filter{ $0.name == key }
if !array.isEmpty {
return .array(array, path + "[\"\(key)\"]")
} else {
return .null(path + ": no such children named: \"\(key)\"")
}
case .array(let xmls, let path):
let result = XMLSubscriptResult.xml(xmls[0], path + "[0]")
return result[key]
}
}
func subscriptResult(_ result: XMLSubscriptResult, byAttribute attribute: String) -> XMLSubscriptResult {
switch result {
case .null(_): return self
case .string(_, let path):
return .null(path + ": attribute can not subscript by attribute: \(attribute)")
case .xml(let xml, let path):
if let attr = xml.attributes[attribute] {
return .string(attr, path + "[\"@\(attribute)\"]")
} else {
return .null(path + ": no such attribute named: \(attribute)")
}
case .array(let xmls, let path):
if let attr = xmls[0].attributes[attribute] {
return .string(attr, path + "[0][\"@\(attribute)\"]")
} else {
return .null(path + "[0][\"@\(attribute)\"]" + ": no such attribute named: \(attribute)")
}
}
}
switch key {
case .index(let index):
return subscriptResult(self, byIndex: index)
case .key(let key):
return subscriptResult(self, byKey: key)
case .keyChain(let keyChain):
var result: XMLSubscriptResult?
for (i, key) in keyChain.pathComponents.enumerated() {
if i == 0 {
switch key {
case .index(let index): result = subscriptResult(self, byIndex: index)
case .key(let key): result = subscriptResult(self, byKey: key)
default: fatalError("key chain components never contains other type XMLSubscriptionKey")
}
}
else {
switch key {
case .index(let index): result = subscriptResult(result!, byIndex: index)
case .key(let key): result = subscriptResult(result!, byKey: key)
default: fatalError("key chain components never contains other type XMLSubscriptionKey")
}
}
}
guard let subResult = result else { fatalError("unexception") }
if let attribute = keyChain.attribute {
return subscriptResult(subResult, byAttribute: attribute)
} else {
return subResult
}
case .attribute(let attribute):
return subscriptResult(self, byAttribute: attribute)
}
}
public var xml:XML? {
switch self {
case .null(_):
return nil
case .string(_, _):
return nil
case .xml(let xml, _): return xml
case .array(let xmls, _): return xmls[0]
}
}
public func getXML() throws -> XML {
switch self {
case .null(let error):
throw XMLError.subscriptFailue(error)
case .string(_, let path):
throw XMLError.subscriptFailue("can not get XML from attribute, from keyChain: \(path)")
case .xml(let xml, _): return xml
case .array(let xmls, _): return xmls[0]
}
}
public var xmlList:[XML]? {
switch self {
case .null(_):
return nil
case .string(_, _):
return nil
case .xml(let xml, _): return [xml]
case .array(let xmls, _): return xmls
}
}
public func getXMLList() throws -> [XML] {
switch self {
case .null(let error):
throw XMLError.subscriptFailue(error)
case .string(_, let path):
throw XMLError.subscriptFailue("can not get list from attribute, from keyChain: \(path)")
case .xml(let xml, _): return [xml]
case .array(let xmls, _): return xmls
}
}
public var error: String {
switch self {
case .null(let error):
return error
default: return ""
}
}
}
public struct KeyChain {
var pathComponents: [XMLSubscriptKey] = []
var attribute: String?
init?(string: String) {
guard !string.isEmpty else { return nil }
var string = string
if string.hasPrefix("#") {
let index = string.index(string.startIndex, offsetBy: 1)
string = String(string[index...])
}
let strings = string.components(separatedBy: ".").filter{ !$0.isEmpty }
for (i, str) in strings.enumerated() {
if str.hasPrefix("@") {
if i == strings.count - 1 {
let index = str.index(str.startIndex, offsetBy: 1)
self.attribute = String(str[index...])
} else {
return nil
}
} else {
if let v = UInt(str) {
self.pathComponents.append(.index(Int(v)))
} else {
self.pathComponents.append(.key(str))
}
}
}
}
}
open class XML {
public var name:String
public var attributes:[String: String] = [:]
public var value:String?
public internal(set) var children:[XML] = []
internal weak var parent:XML?
public init(name:String, attributes:[String:Any] = [:], value: Any? = nil) {
self.name = name
self.addAttributes(attributes)
if let value = value {
self.value = String(describing: value)
}
}
private convenience init(xml: XML) {
self.init(name: xml.name, attributes: xml.attributes, value: xml.value)
self.addChildren(xml.children)
self.parent = nil
}
public convenience init!(data: Data) {
do {
let parser = SimpleXMLParser(data: data)
try parser.parse()
if let xml = parser.root {
self.init(xml: xml)
} else {
fatalError("xml parser exception")
}
} catch {
print(error.localizedDescription)
return nil
}
}
public convenience init!(url: URL) {
do {
let data = try Data(contentsOf: url)
self.init(data: data)
} catch {
print(error.localizedDescription)
return nil
}
}
public convenience init(named name: String) {
guard let url = Bundle.main.resourceURL?.appendingPathComponent(name) else {
fatalError("can not get mainBundle URL")
}
self.init(url: url)
}
public convenience init(string: String, encoding: String.Encoding = .utf8) {
guard let data = string.data(using: encoding) else {
fatalError("string encoding failed")
}
self.init(data: data)
}
public subscript(index: Int) -> XMLSubscriptResult {
return self[XMLSubscriptKey.index(index)]
}
public subscript(key: String) -> XMLSubscriptResult {
if let subscripKey = getXMLSubscriptKey(from: key) {
return self[subscripKey]
} else {
return .null("wrong key chain format: \(key)")
}
}
public subscript(key: XMLSubscriptKey) -> XMLSubscriptResult {
switch key {
case .index(let index):
if self.children.indices.contains(index) {
return .xml(self.children[index], "[\(index)]")
} else {
let bounds = self.children.indices
return .null("index:\(index) out of bounds: \(bounds)")
}
case .key(let key):
let array = self.children.filter{ $0.name == key }
if !array.isEmpty {
return .array(array, "[\"\(key)\"]")
} else {
return .null("no such children named: \"\(key)\"")
}
case .keyChain(let keyChain):
var result: XMLSubscriptResult?
for (i, path) in keyChain.pathComponents.enumerated() {
if i == 0 {
result = self[path]
} else {
result = result![path]
}
}
guard let subResult = result else {
fatalError("")
}
if let attribute = keyChain.attribute {
return subResult[XMLSubscriptKey.attribute(attribute)]
} else {
return subResult
}
case .attribute(let attribute):
if let attr = self.attributes[attribute] {
return .string(attr, "[\(attribute)]")
} else {
return .null("no such attribute named: \"\(attribute)\"")
}
}
}
public func addAttribute(name:String, value:Any) {
self.attributes[name] = String(describing: value)
}
public func addAttributes(_ attributes:[String : Any]) {
for (key, value) in attributes {
self.addAttribute(name: key, value: value)
}
}
public func addChild(_ xml:XML) {
guard xml !== self else {
fatalError("can not add self to xml children list!")
}
children.append(xml)
xml.parent = self
}
public func addChildren(_ xmls: [XML]) {
xmls.forEach{ self.addChild($0) }
}
}
// MARK: - XMLSubscriptResult implements Sequence protocol
public class XMLSubscriptResultIterator : IteratorProtocol {
var xmls:[XML]
var index:Int = 0
public init(result: XMLSubscriptResult) {
self.xmls = result.xmlList ?? []
}
public func next() -> XML? {
if self.xmls.isEmpty { return nil }
if self.index >= self.xmls.endIndex { return nil }
defer { index += 1 }
return self.xmls[index]
}
}
extension XMLSubscriptResult : Sequence {
public typealias Iterator = XMLSubscriptResultIterator
public func makeIterator() -> XMLSubscriptResult.Iterator {
return XMLSubscriptResultIterator(result: self)
}
}
// MARK: - StringProvider protocol and extensions
public protocol StringProvider {
var string: String? { get }
}
extension XML : StringProvider {
public var string: String? {
return self.value
}
}
extension XMLSubscriptResult : StringProvider {
public var string: String? {
switch self {
case .null(_): return nil
case .string(let string, _): return string
case .xml(let xml, _): return xml.value
case .array(let xmls, _): return xmls[0].value
}
}
}
extension RawRepresentable {
static func initialize(rawValue: RawValue?) throws -> Self {
if let value = rawValue {
if let result = Self.init(rawValue: value) {
return result
} else {
throw XMLError.initFailue("[\(Self.self)] init failed with raw value: [\(value)]")
}
}
throw XMLError.initFailue("[\(Self.self)] init failed with nil value")
}
}
extension StringProvider {
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == String { return try? T.initialize(rawValue: self.string) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt8 { return try? T.initialize(rawValue: self.uInt8) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt16 { return try? T.initialize(rawValue: self.uInt16) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt32 { return try? T.initialize(rawValue: self.uInt32) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt64 { return try? T.initialize(rawValue: self.uInt64) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt { return try? T.initialize(rawValue: self.uInt) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int8 { return try? T.initialize(rawValue: self.int8) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int16 { return try? T.initialize(rawValue: self.int16) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int32 { return try? T.initialize(rawValue: self.int32) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int64 { return try? T.initialize(rawValue: self.int64) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int { return try? T.initialize(rawValue: self.int) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == String { return try T.initialize(rawValue: self.string) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt8 { return try T.initialize(rawValue: self.uInt8) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt16 { return try T.initialize(rawValue: self.uInt16) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt32 { return try T.initialize(rawValue: self.uInt32) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt64 { return try T.initialize(rawValue: self.uInt64) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt { return try T.initialize(rawValue: self.uInt) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int8 { return try T.initialize(rawValue: self.int8) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int16 { return try T.initialize(rawValue: self.int16) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int32 { return try T.initialize(rawValue: self.int32) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int64 { return try T.initialize(rawValue: self.int64) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int { return try T.initialize(rawValue: self.int) }
}
// optional
extension StringProvider {
public var bool: Bool? {
if let string = self.string { return Bool(string) }
return nil
}
// unsigned integer
public var uInt8: UInt8? {
if let string = self.string { return UInt8(string) }
return nil
}
public var uInt16: UInt16? {
if let string = self.string { return UInt16(string) }
return nil
}
public var uInt32: UInt32? {
if let string = self.string { return UInt32(string) }
return nil
}
public var uInt64: UInt64? {
if let string = self.string { return UInt64(string) }
return nil
}
public var uInt: UInt? {
if let string = self.string { return UInt(string) }
return nil
}
// signed integer
public var int8: Int8? {
if let string = self.string { return Int8(string) }
return nil
}
public var int16: Int16? {
if let string = self.string { return Int16(string) }
return nil
}
public var int32: Int32? {
if let string = self.string { return Int32(string) }
return nil
}
public var int64: Int64? {
if let string = self.string { return Int64(string) }
return nil
}
public var int: Int? {
if let string = self.string { return Int(string) }
return nil
}
// decimal
public var float: Float? {
if let string = self.string { return Float(string) }
return nil
}
public var double: Double? {
if let string = self.string { return Double(string) }
return nil
}
}
// non optional
extension StringProvider {
public var boolValue: Bool {
return bool ?? false
}
// unsigned integer
public var uInt8Value: UInt8 {
return uInt8 ?? 0
}
public var uInt16Value: UInt16 {
return uInt16 ?? 0
}
public var uInt32Value: UInt32 {
return uInt32 ?? 0
}
public var uInt64Value: UInt64 {
return uInt64 ?? 0
}
public var uIntValue: UInt {
return uInt ?? 0
}
// signed integer
public var int8Value: Int8 {
return int8 ?? 0
}
public var int16Value: Int16 {
return int16 ?? 0
}
public var int32Value: Int32 {
return int32 ?? 0
}
public var int64Value: Int64 {
return int64 ?? 0
}
public var intValue: Int {
return int ?? 0
}
// decimal
public var floatValue: Float {
return float ?? 0
}
public var doubleValue: Double {
return double ?? 0
}
public var stringValue: String {
return string ?? ""
}
}
// MARK: - XML Descriptions
extension XML {
public var description:String {
return self.toXMLString()
}
public func toXMLString() -> String {
var result = ""
var depth:Int = 0
describe(xml: self, depth: &depth, result: &result)
return result
}
private func describe(xml: XML, depth:inout Int, result: inout String) {
if xml.children.isEmpty {
result += xml.getCombine(numTabs: depth)
} else {
result += xml.getStartPart(numTabs: depth)
depth += 1
for child in xml.children {
describe(xml: child, depth: &depth, result: &result)
}
depth -= 1
result += xml.getEndPart(numTabs: depth)
}
}
private func getAttributeString() -> String {
return self.attributes.map{ " \($0.0)=\"\($0.1)\"" }.joined()
}
private func getStartPart(numTabs:Int) -> String {
return getDescription(numTabs: numTabs, closed: false)
}
private func getEndPart(numTabs:Int) -> String {
return String(repeating: "\t", count: numTabs) + "</\(name)>\n"
}
private func getCombine(numTabs:Int) -> String {
return self.getDescription(numTabs: numTabs, closed: true)
}
private func getDescription(numTabs:Int, closed:Bool) -> String {
var attr = self.getAttributeString()
attr = attr.isEmpty ? "" : attr + " "
let tabs = String(repeating: "\t", count: numTabs)
var valueString: String = ""
if let v = self.value {
valueString = v.trimmingCharacters(in: .whitespacesAndNewlines)
}
if attr.isEmpty {
switch (closed, self.value) {
case (true, .some(_)): return tabs + "<\(name)>\(valueString)</\(name)>\n"
case (true, .none): return tabs + "<\(name) />\n"
case (false, .some(_)): return tabs + "<\(name)>\(valueString)\n"
case (false, .none): return tabs + "<\(name)>\n"
}
} else {
switch (closed, self.value) {
case (true, .some(_)): return tabs + "<\(name)" + attr + ">\(valueString)</\(name)>\n"
case (true, .none): return tabs + "<\(name)" + attr + "/>\n"
case (false, .some(_)): return tabs + "<\(name)" + attr + ">\(valueString)\n"
case (false, .none): return tabs + "<\(name)" + attr + ">\n"
}
}
}
}
public class SimpleXMLParser: NSObject, XMLParserDelegate {
public var root:XML?
public let data:Data
weak var currentElement:XML?
var parseError:Swift.Error?
deinit {
self.root = nil
self.currentElement = nil
self.parseError = nil
}
public init(data: Data) {
self.data = data
super.init()
}
public func parse() throws {
let parser = XMLParser(data: data)
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
if let error = parseError {
throw error
}
}
// MARK: - XMLParserDelegate
@objc public func parser(_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String : String])
{
let element = XML(name: elementName, attributes: attributeDict)
if self.root == nil {
self.root = element
self.currentElement = element
} else {
self.currentElement?.addChild(element)
self.currentElement = element
}
}
@objc public func parser(_ parser: XMLParser, foundCharacters string: String) {
if let currentValue = self.currentElement?.value {
self.currentElement?.value = currentValue + string
} else {
self.currentElement?.value = string
}
}
@objc public func parser(_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?)
{
currentElement = currentElement?.parent
}
@objc public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Swift.Error) {
self.parseError = parseError
}
}
fileprivate func getXMLSubscriptKey(from string: String) -> XMLSubscriptKey? {
if string.hasPrefix("#") {
if let keyChain = KeyChain(string: string) {
return XMLSubscriptKey.keyChain(keyChain)
} else {
return nil
}
}
else if string.hasPrefix("@") {
let index = string.index(string.startIndex, offsetBy: 1)
let string = String(string[index...])
return XMLSubscriptKey.attribute(string)
}
else {
return XMLSubscriptKey.key(string)
}
}
| 35.112162 | 139 | 0.559789 |
50912194b67a26164aeaaea22658a582c0e126ff | 3,918 | //
// ChangeAppIconViewController.swift
// Rocket.Chat
//
// Created by Artur Rymarz on 08.02.2018.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
final class ChangeAppIconViewController: BaseViewController {
private let viewModel = ChangeAppIconViewModel()
@IBOutlet private weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
title = viewModel.title
collectionView?.register(
ReusableViewText.nib,
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: ReusableViewText.identifier
)
}
private func changeIcon(name: String) {
let iconName = name == "Default" ? nil : name
if #available(iOS 10.3, *) {
UIApplication.shared.setAlternateIconName(iconName) { error in
if let error = error {
self.reportError(message: (error as NSError).localizedDescription)
}
self.collectionView.reloadData()
}
} else {
reportError(message: viewModel.iosVersionMessage)
}
}
private func reportError(message: String?) {
guard let message = message else {
return
}
alert(title: viewModel.errorTitle, message: message, handler: nil)
}
}
extension ChangeAppIconViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.availableIcons.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: viewModel.cellIdentifier,
for: indexPath
) as? ChangeAppIconCell else {
fatalError("Could not dequeue reuable cell as ChangeAppIconCell")
}
let iconName = viewModel.availableIcons[indexPath.row]
var isSelected = false
if #available(iOS 10.3, *) {
if let selectedIcon = UIApplication.shared.alternateIconName {
isSelected = iconName == selectedIcon
} else {
isSelected = indexPath.row == 0
}
}
cell.setIcon(name: iconName, selected: isSelected)
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
if let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ReusableViewText.identifier, for: indexPath) as? ReusableViewText {
view.labelText.text = viewModel.header
return view
}
}
return UICollectionReusableView()
}
}
extension ChangeAppIconViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: collectionView.frame.width, height: 120)
}
return CGSize(width: 0, height: 0)
}
}
extension ChangeAppIconViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
changeIcon(name: viewModel.availableIcons[indexPath.row])
}
}
// MARK: Themeable
extension ChangeAppIconViewController {
override func applyTheme() {
super.applyTheme()
guard let theme = view.theme else { return }
view.backgroundColor = theme.auxiliaryBackground
}
}
| 31.095238 | 176 | 0.667432 |
1c4ad09dec5a59d21eab961acd03e421bc342542 | 289 | //
// Configuration.swift
// FastSpringCheckoutDemo
//
// Created by Helge Heß on 30.05.20.
// Copyright © 2020 ZeeZide GmbH. All rights reserved.
//
enum Configuration {
static let storeName = "zeezide.onfastspring.com"
static let productName = "soy-for-community-slacks"
}
| 20.642857 | 55 | 0.705882 |
64c2712f7c207b901ee0f951ac91b976a003f0ea | 940 | //
// Photo.swift
// Hiker
//
// Created by 张驰 on 2019/9/17.
// Copyright © 2019 张驰. All rights reserved.
//
import Foundation
import Photos
import DifferenceKit
class Photo {
var asset: PHAsset
var identifiers: [(String, Float)]?
var city: String?
var location: CLLocation? {
return asset.location
}
var createTime: Date? {
return asset.creationDate
}
init(_ asset: PHAsset, _ identifier: [(String, Float)]? = nil, _ locationStr: String? = nil) {
self.asset = asset
self.identifiers = identifier
self.city = locationStr
}
}
extension Photo: Equatable {
static func == (lhs: Photo, rhs: Photo) -> Bool {
return lhs.asset.localIdentifier == rhs.asset.localIdentifier
}
}
extension Photo: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(asset.localIdentifier)
}
}
extension Photo: Differentiable {}
| 21.363636 | 98 | 0.632979 |
5b4d933accc2f6b40afb6fd7cb6724059292753b | 430 | //
// GameModes.swift
// LoginPage_Udemy
//
// Created by Kas Song on 2020.06.06.
// Copyright © 2020 Kas Song. All rights reserved.
//
import Foundation
enum GameModes {
case easy
case hard
case expert
func chooseGameModes() -> Int {
switch self {
case .easy:
return 12
case .hard:
return 16
case .expert:
return 20
}
}
}
| 15.925926 | 51 | 0.532558 |
cc8a5aeddc3ab0cf084e127058ecf6a740f49262 | 18,937 | //
// ViewController.swift
// VideoQuickStart
//
// Copyright © 2016-2017 Twilio, Inc. All rights reserved.
//
import UIKit
import TwilioVideo
class ViewController: UIViewController {
// MARK: View Controller Members
// Configure access token manually for testing, if desired! Create one manually in the console
// at https://www.twilio.com/console/video/runtime/testing-tools
var accessToken = "TWILIO_ACCESS_TOKEN"
// Configure remote URL to fetch token from
var tokenUrl = "http://localhost:8000/token.php"
// Video SDK components
var room: TVIRoom?
var camera: TVICameraCapturer?
var localVideoTrack: TVILocalVideoTrack?
var localAudioTrack: TVILocalAudioTrack?
var remoteParticipant: TVIRemoteParticipant?
var remoteView: TVIVideoView?
// MARK: UI Element Outlets and handles
// `TVIVideoView` created from a storyboard
@IBOutlet weak var previewView: TVIVideoView!
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var roomTextField: UITextField!
@IBOutlet weak var roomLine: UIView!
@IBOutlet weak var roomLabel: UILabel!
@IBOutlet weak var micButton: UIButton!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.title = "QuickStart"
self.messageLabel.adjustsFontSizeToFitWidth = true;
self.messageLabel.minimumScaleFactor = 0.75;
if PlatformUtils.isSimulator {
self.previewView.removeFromSuperview()
} else {
// Preview our local camera track in the local video preview view.
self.startPreview()
}
// Disconnect and mic button will be displayed when the Client is connected to a Room.
self.disconnectButton.isHidden = true
self.micButton.isHidden = true
self.roomTextField.autocapitalizationType = .none
self.roomTextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController2.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
func setupRemoteVideoView() {
// Creating `TVIVideoView` programmatically
self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate:self)
self.view.insertSubview(self.remoteView!, at: 0)
// `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit
// scaleAspectFit is the default mode when you create `TVIVideoView` programmatically.
self.remoteView!.contentMode = .scaleAspectFit;
let centerX = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerY)
let width = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1,
constant: 0);
self.view.addConstraint(width)
let height = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.height,
multiplier: 1,
constant: 0);
self.view.addConstraint(height)
}
// MARK: IBActions
@IBAction func connect(sender: AnyObject) {
// Configure access token either from server or manually.
// If the default wasn't changed, try fetching from server.
if (accessToken == "TWILIO_ACCESS_TOKEN") {
do {
accessToken = try TokenUtils.fetchToken(url: tokenUrl)
} catch {
let message = "Failed to fetch access token"
logMessage(messageText: message)
return
}
}
// Prepare local media which we will share with Room Participants.
self.prepareLocalMedia()
// Preparing the connect options with the access token that we fetched (or hardcoded).
let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in
// Use the local media that we prepared earlier.
builder.audioTracks = self.localAudioTrack != nil ? [self.localAudioTrack!] : [TVILocalAudioTrack]()
builder.videoTracks = self.localVideoTrack != nil ? [self.localVideoTrack!] : [TVILocalVideoTrack]()
// Use the preferred audio codec
if let preferredAudioCodec = Settings.shared.audioCodec {
builder.preferredAudioCodecs = [preferredAudioCodec]
}
// Use the preferred video codec
if let preferredVideoCodec = Settings.shared.videoCodec {
builder.preferredVideoCodecs = [preferredVideoCodec]
}
// Use the preferred encoding parameters
if let encodingParameters = Settings.shared.getEncodingParameters() {
builder.encodingParameters = encodingParameters
}
// The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty
// Room `name`, the Client will create one for you. You can get the name or sid from any connected Room.
builder.roomName = self.roomTextField.text
}
// Connect to the Room using the options we provided.
room = TwilioVideo.connect(with: connectOptions, delegate: self)
logMessage(messageText: "Attempting to connect to room \(String(describing: self.roomTextField.text))")
self.showRoomUI(inRoom: true)
self.dismissKeyboard()
}
@IBAction func disconnect(sender: AnyObject) {
self.room!.disconnect()
logMessage(messageText: "Attempting to disconnect from room \(room!.name)")
}
@IBAction func toggleMic(sender: AnyObject) {
if (self.localAudioTrack != nil) {
self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)!
// Update the button title
if (self.localAudioTrack?.isEnabled == true) {
self.micButton.setTitle("Mute", for: .normal)
} else {
self.micButton.setTitle("Unmute", for: .normal)
}
}
}
// MARK: Private
func startPreview() {
if PlatformUtils.isSimulator {
return
}
// Preview our local camera track in the local video preview view.
camera = TVICameraCapturer(source: .frontCamera, delegate: self)
localVideoTrack = TVILocalVideoTrack.init(capturer: camera!, enabled: true, constraints: nil, name: "Camera")
if (localVideoTrack == nil) {
logMessage(messageText: "Failed to create video track")
} else {
// Add renderer to video track for local preview
localVideoTrack!.addRenderer(self.previewView)
logMessage(messageText: "Video track created")
// We will flip camera on tap.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController2.flipCamera))
self.previewView.addGestureRecognizer(tap)
}
}
func flipCamera() {
if (self.camera?.source == .frontCamera) {
self.camera?.selectSource(.backCameraWide)
} else {
self.camera?.selectSource(.frontCamera)
}
}
func prepareLocalMedia() {
// We will share local audio and video when we connect to the Room.
// Create an audio track.
if (localAudioTrack == nil) {
localAudioTrack = TVILocalAudioTrack.init(options: nil, enabled: true, name: "Microphone")
if (localAudioTrack == nil) {
logMessage(messageText: "Failed to create audio track")
}
}
// Create a video track which captures from the camera.
if (localVideoTrack == nil) {
self.startPreview()
}
}
// Update our UI based upon if we are in a Room or not
func showRoomUI(inRoom: Bool) {
self.connectButton.isHidden = inRoom
self.roomTextField.isHidden = inRoom
self.roomLine.isHidden = inRoom
self.roomLabel.isHidden = inRoom
self.micButton.isHidden = !inRoom
self.disconnectButton.isHidden = !inRoom
self.navigationController?.setNavigationBarHidden(inRoom, animated: true)
UIApplication.shared.isIdleTimerDisabled = inRoom
}
func dismissKeyboard() {
if (self.roomTextField.isFirstResponder) {
self.roomTextField.resignFirstResponder()
}
}
func cleanupRemoteParticipant() {
if ((self.remoteParticipant) != nil) {
if ((self.remoteParticipant?.videoTracks.count)! > 0) {
let remoteVideoTrack = self.remoteParticipant?.remoteVideoTracks[0].remoteTrack
remoteVideoTrack?.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
self.remoteParticipant = nil
}
func logMessage(messageText: String) {
messageLabel.text = messageText
}
}
// MARK: UITextFieldDelegate
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.connect(sender: textField)
return true
}
}
// MARK: TVIRoomDelegate
extension ViewController : TVIRoomDelegate {
func didConnect(to room: TVIRoom) {
// At the moment, this example only supports rendering one Participant at a time.
logMessage(messageText: "Connected to room \(room.name) as \(String(describing: room.localParticipant?.identity))")
if (room.remoteParticipants.count > 0) {
self.remoteParticipant = room.remoteParticipants[0]
self.remoteParticipant?.delegate = self
}
}
func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {
logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))")
self.cleanupRemoteParticipant()
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, didFailToConnectWithError error: Error) {
logMessage(messageText: "Failed to connect to room with error")
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, participantDidConnect participant: TVIRemoteParticipant) {
if (self.remoteParticipant == nil) {
self.remoteParticipant = participant
self.remoteParticipant?.delegate = self
}
logMessage(messageText: "Participant \(participant.identity) connected with \(participant.remoteAudioTracks.count) audio and \(participant.remoteVideoTracks.count) video tracks")
}
func room(_ room: TVIRoom, participantDidDisconnect participant: TVIRemoteParticipant) {
if (self.remoteParticipant == participant) {
cleanupRemoteParticipant()
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected")
}
}
// MARK: TVIRemoteParticipantDelegate
extension ViewController : TVIRemoteParticipantDelegate {
func remoteParticipant(_ participant: TVIRemoteParticipant,
publishedVideoTrack publication: TVIRemoteVideoTrackPublication) {
// Remote Participant has offered to share the video Track.
logMessage(messageText: "Participant \(participant.identity) published \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
unpublishedVideoTrack publication: TVIRemoteVideoTrackPublication) {
// Remote Participant has stopped sharing the video Track.
logMessage(messageText: "Participant \(participant.identity) unpublished \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
publishedAudioTrack publication: TVIRemoteAudioTrackPublication) {
// Remote Participant has offered to share the audio Track.
logMessage(messageText: "Participant \(participant.identity) published \(publication.trackName) audio track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
unpublishedAudioTrack publication: TVIRemoteAudioTrackPublication) {
// Remote Participant has stopped sharing the audio Track.
logMessage(messageText: "Participant \(participant.identity) unpublished \(publication.trackName) audio track")
}
func subscribed(to videoTrack: TVIRemoteVideoTrack,
publication: TVIRemoteVideoTrackPublication,
for participant: TVIRemoteParticipant) {
// We are subscribed to the remote Participant's audio Track. We will start receiving the
// remote Participant's video frames now.
logMessage(messageText: "Subscribed to \(publication.trackName) video track for Participant \(participant.identity)")
if (self.remoteParticipant == participant) {
setupRemoteVideoView()
videoTrack.addRenderer(self.remoteView!)
}
}
func unsubscribed(from videoTrack: TVIRemoteVideoTrack,
publication: TVIRemoteVideoTrackPublication,
for participant: TVIRemoteParticipant) {
// We are unsubscribed from the remote Participant's video Track. We will no longer receive the
// remote Participant's video.
logMessage(messageText: "Unsubscribed from \(publication.trackName) video track for Participant \(participant.identity)")
if (self.remoteParticipant == participant) {
videoTrack.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
func subscribed(to audioTrack: TVIRemoteAudioTrack,
publication: TVIRemoteAudioTrackPublication,
for participant: TVIRemoteParticipant) {
// We are subscribed to the remote Participant's audio Track. We will start receiving the
// remote Participant's audio now.
logMessage(messageText: "Subscribed to \(publication.trackName) audio track for Participant \(participant.identity)")
}
func unsubscribed(from audioTrack: TVIRemoteAudioTrack,
publication: TVIRemoteAudioTrackPublication,
for participant: TVIRemoteParticipant) {
// We are unsubscribed from the remote Participant's audio Track. We will no longer receive the
// remote Participant's audio.
logMessage(messageText: "Unsubscribed from \(publication.trackName) audio track for Participant \(participant.identity)")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
enabledVideoTrack publication: TVIRemoteVideoTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) enabled \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
disabledVideoTrack publication: TVIRemoteVideoTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) disabled \(publication.trackName) video track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
enabledAudioTrack publication: TVIRemoteAudioTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) enabled \(publication.trackName) audio track")
}
func remoteParticipant(_ participant: TVIRemoteParticipant,
disabledAudioTrack publication: TVIRemoteAudioTrackPublication) {
logMessage(messageText: "Participant \(participant.identity) disabled \(publication.trackName) audio track")
}
func failedToSubscribe(toAudioTrack publication: TVIRemoteAudioTrackPublication,
error: Error,
for participant: TVIRemoteParticipant) {
logMessage(messageText: "FailedToSubscribe \(publication.trackName) audio track, error = \(String(describing: error))")
}
func failedToSubscribe(toVideoTrack publication: TVIRemoteVideoTrackPublication,
error: Error,
for participant: TVIRemoteParticipant) {
logMessage(messageText: "FailedToSubscribe \(publication.trackName) video track, error = \(String(describing: error))")
}
}
// MARK: TVIVideoViewDelegate
extension ViewController : TVIVideoViewDelegate {
func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {
self.view.setNeedsLayout()
}
}
// MARK: TVICameraCapturerDelegate
extension ViewController : TVICameraCapturerDelegate {
func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) {
self.previewView.shouldMirror = (source == .frontCamera)
}
}
| 41.528509 | 185 | 0.623752 |
16db1d9f72e84b2f83c2fbf37c052996756d5f13 | 3,079 | //
// BackgroundFetcher.swift
// KanjiRyokucha
//
// Created by German Buela on 8/17/17.
// Copyright © 2017 German Buela. All rights reserved.
//
import Foundation
import ReactiveSwift
enum BackgroundFetcherResult {
case notChecked
case failure
case success(oldCount: Int, newCount: Int)
}
typealias BackgroundFetcherCompletion = (BackgroundFetcherResult) -> ()
/**
Goal is to get access to latest due count (saved in Global) and fetch current due
count from backend. All execution paths should lead to completion closure.
Prior to fetching status we log in to ensure active session.
For the purpose of background fetch, we don't care about reasons for failures --
we either get the values or not.
We don't care about the UI either. If the user opens the app, it will update its
UI as usual.
*/
class BackgroundFetcher {
// we prevent the notification that is meant for presenting credentials vc
let loginViewModel = LoginViewModel(sendLoginNotification: false)
var statusAction: Action<Void, Response, FetchError>?
let completion: BackgroundFetcherCompletion
init(completion: @escaping BackgroundFetcherCompletion) {
self.completion = completion
}
func start() {
log("Starting BackgroundFetcher")
loginViewModel.state.react { [weak self] loginState in
switch loginState {
case .loggedIn:
log("Logged in!")
if Database.getGlobal().useNotifications {
self?.getCurrentStatus()
} else {
self?.completion(.notChecked)
}
break
case let .failure(err):
log("Login failed with: \(err)")
self?.completion(.failure)
break
default:
break
}
}
log("Autologin...")
loginViewModel.autologin()
}
func getCurrentStatus() {
let oldCount = Database.getGlobal().latestDueCount
statusAction = Action<Void, Response, FetchError>(execute: { _ in
return GetStatusRequest().requestProducer()!
})
statusAction?.react { [weak self] response in
if let model = response.model as? GetStatusModel {
log("Status succeeded!")
self?.completion(.success(oldCount: oldCount, newCount: model.expiredCards))
} else {
log("Status not getting expected model")
self?.completion(.failure)
}
}
statusAction?.completed.react {
log("Status completed")
}
statusAction?.errors.react { [weak self] err in
log("Status failed with: \(err)")
self?.completion(.failure)
}
let delayInSeconds = 4.0
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + delayInSeconds) {
log("Getting status...")
self.statusAction?.apply().start()
}
}
}
| 32.072917 | 94 | 0.597921 |
64f914181063c892d22a607cb1968da4cb4c7923 | 3,225 | //
// MapView.swift
// Afrika
//
// Created by Jonathan Sweeney on 10/31/20.
//
import MapKit
import SwiftUI
struct MapView: View {
@State private var region: MKCoordinateRegion = {
var mapCoordinates = CLLocationCoordinate2D(latitude: 6.600286, longitude: 16.43776)
var mapZoomLevel = MKCoordinateSpan(latitudeDelta: 70.0, longitudeDelta: 70.0)
var mapRegion = MKCoordinateRegion(center: mapCoordinates, span: mapZoomLevel)
return mapRegion
}()
let locations: [NationalParkLocation] = Bundle.main.decode(K.Data.locationsJson)
var body: some View {
// MARK: - No1 Basic Map
// Map(coordinateRegion: $region)
// MARK: - No2 Advanced Map
Map(coordinateRegion: $region, annotationItems: locations, annotationContent: { item in
// (A) PIN: OLD STYLE (static)
// MapPin(coordinate: item.location, tint: .accentColor)
// (B) MARKERS: NEW STYLE (STATIC)
// MapMarker(coordinate: item.location, tint: .accentColor)
// (C) CUSTOM BASIC ANNOTATION (interactive)
// MapAnnotation(coordinate: item.location) {
// Image("logo")
// .resizable()
// .scaledToFit()
// .frame(width: 32, height: 32, alignment: .center)
// }//: ANNOTATION
// (D) CUSTOM ADVANCED ANNOTATION (Can be interactive)
MapAnnotation(coordinate: item.location) {
MapAnnotationView(location: item)
}
})//: MAP
.overlay(
HStack(alignment: .center, spacing: 12) {
Image("compass")
.resizable()
.scaledToFit()
.frame(width: 48, height: 48, alignment: .center)
VStack(alignment: .leading, spacing: 3) {
HStack {
Text("Latitude:")
.font(.footnote)
.fontWeight(.bold)
.foregroundColor(.accentColor)
Spacer()
Text("\(region.center.latitude)")
.font(.footnote)
.foregroundColor(.white)
}
Divider()
HStack {
Text("Longitude:")
.font(.footnote)
.fontWeight(.bold)
.foregroundColor(.accentColor)
Spacer()
Text("\(region.center.longitude)")
.font(.footnote)
.foregroundColor(.white)
}
}//: VSTACK
}//: HSTACK
.padding(.vertical, 12)
.padding(.horizontal, 16)
.background(
Color.black
.cornerRadius(8)
.opacity(0.6)
)
.padding(),
alignment: .top
)
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
| 35.43956 | 95 | 0.471628 |
ab47169393d732b89c61963fcdb236affbe29516 | 4,837 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A graphic that displays an Ingredient as a thumbnail, a card highlighting its image, or the back of a card highlighting its nutrition facts.
*/
import SwiftUI
struct IngredientGraphic: View {
var ingredient: Ingredient
var style: Style
var closeAction: () -> Void = {}
var flipAction: () -> Void = {}
enum Style {
case cardFront
case cardBack
case thumbnail
}
var displayingAsCard: Bool {
style == .cardFront || style == .cardBack
}
var shape = RoundedRectangle(cornerRadius: 16, style: .continuous)
var body: some View {
ZStack {
image
if style != .cardBack {
title
}
if style == .cardFront {
cardControls(for: .front)
.foregroundStyle(ingredient.title.color)
.opacity(ingredient.title.opacity)
.blendMode(ingredient.title.blendMode)
}
if style == .cardBack {
ZStack {
if let nutritionFact = ingredient.nutritionFact {
NutritionFactView(nutritionFact: nutritionFact)
.padding(.bottom, 70)
}
cardControls(for: .back)
}
.background(.thinMaterial)
}
}
.frame(minWidth: 130, maxWidth: 400, maxHeight: 500)
.compositingGroup()
.clipShape(shape)
.overlay {
shape
.inset(by: 0.5)
.stroke(.quaternary, lineWidth: 0.5)
}
.contentShape(shape)
.accessibilityElement(children: .contain)
}
var image: some View {
GeometryReader { geo in
ingredient.image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geo.size.width, height: geo.size.height)
.scaleEffect(displayingAsCard ? ingredient.cardCrop.scale : ingredient.thumbnailCrop.scale)
.offset(displayingAsCard ? ingredient.cardCrop.offset : ingredient.thumbnailCrop.offset)
.frame(width: geo.size.width, height: geo.size.height)
.scaleEffect(x: style == .cardBack ? -1 : 1)
}
.accessibility(hidden: true)
}
var title: some View {
Text(ingredient.name.uppercased())
.padding(.horizontal, 8)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.lineLimit(2)
.multilineTextAlignment(.center)
.foregroundStyle(ingredient.title.color)
.rotationEffect(displayingAsCard ? ingredient.title.rotation: .degrees(0))
.opacity(ingredient.title.opacity)
.blendMode(ingredient.title.blendMode)
.animatableFont(size: displayingAsCard ? ingredient.title.fontSize : 40, weight: .bold)
.minimumScaleFactor(0.25)
.offset(displayingAsCard ? ingredient.title.offset : .zero)
}
func cardControls(for side: FlipViewSide) -> some View {
VStack {
if side == .front {
CardActionButton(label: "Close", systemImage: "xmark.circle.fill", action: closeAction)
.scaleEffect(displayingAsCard ? 1 : 0.5)
.opacity(displayingAsCard ? 1 : 0)
}
Spacer()
CardActionButton(
label: side == .front ? "Open Nutrition Facts" : "Close Nutrition Facts",
systemImage: side == .front ? "info.circle.fill" : "arrow.left.circle.fill",
action: flipAction
)
.scaleEffect(displayingAsCard ? 1 : 0.5)
.opacity(displayingAsCard ? 1 : 0)
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
// MARK: - Previews
struct IngredientGraphic_Previews: PreviewProvider {
static let ingredient = Ingredient.orange
static var previews: some View {
Group {
IngredientGraphic(ingredient: ingredient, style: .thumbnail)
.frame(width: 180, height: 180)
.previewDisplayName("Thumbnail")
IngredientGraphic(ingredient: ingredient, style: .cardFront)
.aspectRatio(0.75, contentMode: .fit)
.frame(width: 500, height: 600)
.previewDisplayName("Card Front")
IngredientGraphic(ingredient: ingredient, style: .cardBack)
.aspectRatio(0.75, contentMode: .fit)
.frame(width: 500, height: 600)
.previewDisplayName("Card Back")
}
.previewLayout(.sizeThatFits)
}
}
| 35.306569 | 140 | 0.551375 |
564b91713c175a508111fca8d7cdd5d21f028e92 | 338 | //
// Length-of-Last-Word.swift
//
//
// Created by Vyacheslav Pronin on 09.11.2021.
//
import Foundation
class Solution {
func lengthOfLastWord(_ s: String) -> Int {
let array = s.split(separator: " ")
guard let last = array.last else {
return 0
}
return last.count
}
}
| 16.9 | 47 | 0.550296 |
e5aa27d4430c86e902662d1df1f8c97212ede792 | 9,874 | #if os(iOS) || os(macOS) // Added by Auth0toSPM
import Auth0ObjC // Added by Auth0toSPM
// OAuth2Grant.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(macOS) // Added by Auth0toSPM(original value '#if WEB_AUTH_PLATFORM')
import Foundation
import JWTDecode
#if SWIFT_PACKAGE
import Auth0ObjectiveC
#endif
protocol OAuth2Grant {
var defaults: [String: String] { get }
func credentials(from values: [String: String], callback: @escaping (Result<Credentials>) -> Void)
func values(fromComponents components: URLComponents) -> [String: String]
}
struct ImplicitGrant: OAuth2Grant {
let authentication: Authentication
let defaults: [String: String]
let responseType: [ResponseType]
let issuer: String
let leeway: Int
let maxAge: Int?
let organization: String?
init(authentication: Authentication,
responseType: [ResponseType] = [.token],
issuer: String,
leeway: Int,
maxAge: Int? = nil,
nonce: String? = nil,
organization: String? = nil) {
self.authentication = authentication
self.responseType = responseType
self.issuer = issuer
self.leeway = leeway
self.maxAge = maxAge
if let nonce = nonce {
self.defaults = ["nonce": nonce]
} else {
self.defaults = [:]
}
self.organization = organization
}
func credentials(from values: [String: String], callback: @escaping (Result<Credentials>) -> Void) {
let responseType = self.responseType
let validatorContext = IDTokenValidatorContext(authentication: authentication,
issuer: issuer,
leeway: leeway,
maxAge: maxAge,
nonce: self.defaults["nonce"],
organization: self.organization)
validateFrontChannelIDToken(idToken: values["id_token"], for: responseType, with: validatorContext) { error in
if let error = error { return callback(.failure(error)) }
guard !responseType.contains(.token) || values["access_token"] != nil else {
return callback(.failure(WebAuthError.missingAccessToken))
}
callback(.success(Credentials(json: values as [String: Any])))
}
}
func values(fromComponents components: URLComponents) -> [String: String] {
return components.a0_fragmentValues
}
}
struct PKCE: OAuth2Grant {
let authentication: Authentication
let redirectURL: URL
let defaults: [String: String]
let verifier: String
let responseType: [ResponseType]
let issuer: String
let leeway: Int
let maxAge: Int?
let organization: String?
init(authentication: Authentication,
redirectURL: URL,
generator: A0SHA256ChallengeGenerator = A0SHA256ChallengeGenerator(),
responseType: [ResponseType] = [.code],
issuer: String,
leeway: Int,
maxAge: Int? = nil,
nonce: String? = nil,
organization: String? = nil) {
self.init(authentication: authentication,
redirectURL: redirectURL,
verifier: generator.verifier,
challenge: generator.challenge,
method: generator.method,
responseType: responseType,
issuer: issuer,
leeway: leeway,
maxAge: maxAge,
nonce: nonce,
organization: organization)
}
init(authentication: Authentication,
redirectURL: URL,
verifier: String,
challenge: String,
method: String,
responseType: [ResponseType],
issuer: String,
leeway: Int,
maxAge: Int? = nil,
nonce: String? = nil,
organization: String? = nil) {
self.authentication = authentication
self.redirectURL = redirectURL
self.verifier = verifier
self.responseType = responseType
self.issuer = issuer
self.leeway = leeway
self.maxAge = maxAge
self.organization = organization
var newDefaults: [String: String] = [
"code_challenge": challenge,
"code_challenge_method": method
]
if let nonce = nonce {
newDefaults["nonce"] = nonce
}
self.defaults = newDefaults
}
func credentials(from values: [String: String], callback: @escaping (Result<Credentials>) -> Void) {
guard let code = values["code"] else {
let string = "No code found in parameters \(values)"
return callback(.failure(AuthenticationError(string: string)))
}
let idToken = values["id_token"]
let responseType = self.responseType
let authentication = self.authentication
let verifier = self.verifier
let redirectUrlString = self.redirectURL.absoluteString
let clientId = authentication.clientId
let isFrontChannelIdTokenExpected = responseType.contains(.idToken)
let validatorContext = IDTokenValidatorContext(authentication: authentication,
issuer: self.issuer,
leeway: self.leeway,
maxAge: self.maxAge,
nonce: self.defaults["nonce"],
organization: self.organization)
validateFrontChannelIDToken(idToken: idToken, for: responseType, with: validatorContext) { error in
if let error = error { return callback(.failure(error)) }
authentication
.tokenExchange(withCode: code, codeVerifier: verifier, redirectURI: redirectUrlString)
.start { result in
switch result {
case .failure(let error as AuthenticationError) where error.description == "Unauthorized":
// Special case for PKCE when the correct method for token endpoint authentication is not set (it should be None)
let webAuthError = WebAuthError.pkceNotAllowed("Unable to complete authentication with PKCE. PKCE support can be enabled by setting Application Type to 'Native' and Token Endpoint Authentication Method to 'None' for this app at 'https://manage.auth0.com/#/applications/\(clientId)/settings'.")
return callback(.failure(webAuthError))
case .failure(let error): return callback(.failure(error))
case .success(let credentials):
guard isFrontChannelIdTokenExpected else {
return validate(idToken: credentials.idToken, with: validatorContext) { error in
if let error = error { return callback(.failure(error)) }
callback(result)
}
}
let newCredentials = Credentials(accessToken: credentials.accessToken,
tokenType: credentials.tokenType,
idToken: idToken,
refreshToken: credentials.refreshToken,
expiresIn: credentials.expiresIn,
scope: credentials.scope)
return callback(.success(newCredentials))
}
}
}
}
func values(fromComponents components: URLComponents) -> [String: String] {
var items = components.a0_fragmentValues
components.a0_queryValues.forEach { items[$0] = $1 }
return items
}
}
// This method will skip the validation if the response type does not contain "id_token"
private func validateFrontChannelIDToken(idToken: String?,
for responseType: [ResponseType],
with context: IDTokenValidatorContext,
callback: @escaping (LocalizedError?) -> Void) {
guard responseType.contains(.idToken) else { return callback(nil) }
validate(idToken: idToken, with: context) { error in
if let error = error { return callback(error) }
callback(nil)
}
}
#endif
#endif // Added by Auth0toSPM
| 44.080357 | 317 | 0.582439 |
21cf5e11c632999b84b0713c0e647680036ee301 | 1,376 | public final class MongoTransactionDatabase: MongoDatabase {
public func commit() -> EventLoopFuture<Void> {
self.pool.next(for: .writable).flatMap { connection in
connection.executeCodable(
CommitTransaction(),
namespace: .administrativeCommand,
in: self.transaction,
sessionId: self.sessionId
).decodeReply(OK.self).map { _ in }
}
}
public func abort() -> EventLoopFuture<Void> {
self.pool.next(for: .writable).flatMap { connection in
connection.executeCodable(
AbortTransaction(),
namespace: .administrativeCommand,
in: self.transaction,
sessionId: self.sessionId
).decodeReply(OK.self).map { _ in }
}
}
}
struct CommitTransaction: Codable {
let commitTransaction = 1
init() {}
}
struct AbortTransaction: Codable {
let abortTransaction = 1
init() {}
}
internal struct OK: Decodable {
private enum CodingKeys: String, CodingKey {
case ok
}
private let ok: Int
public var isSuccessful: Bool { ok == 1 }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.ok = try container.decode(Int.self, forKey: .ok)
}
}
| 26.980392 | 71 | 0.587209 |
acb652b119ad3022d8a7955dd468b4b95f1829bd | 9,946 | //
// RatingView.swift
// Eco
//
// Created by DU on 6/15/19.
// Copyright © 2019 studio4. All rights reserved.
//
import UIKit
public protocol RatingViewDelegate: NSObjectProtocol {
func didUpdateRatingView(_ ratingView: RatingView, didUpdate rating: Double)
func isUpdateRatingView(_ ratingView: RatingView, isUpdating rating: Double)
}
@IBDesignable open class RatingView: UIView {
// MARK: Properties
public weak var delegate: RatingViewDelegate?
// List normal rating images (empty)
private var normalImageViews: [UIImageView] = []
// List filled rating images
private var filledImageViews: [UIImageView ] = []
// Defines images content mode, defaults is scaleAspectFit
public var imageContentMode: UIView.ContentMode = .scaleAspectFit
// Defines minimum rating image size
@IBInspectable open var minImageSize: CGSize = CGSize(width: 5.0, height: 5.0)
// Sets whether or not the rating view can be changed by panning.
@IBInspectable open var editable: Bool = true
// Default rating type
public var type: RatingViewType = .fullRating
// Sets the normal rating image (e.g. a star outline)
@IBInspectable open var normalImage: UIImage? {
didSet {
for imageView in normalImageViews {
imageView.image = normalImage
}
refreshImageViews()
}
}
// Sets the filled image that is overlayed on top of the empty image.
// Should be same size and shape as the empty image.
@IBInspectable open var fullImage: UIImage? {
didSet {
// Update full image views
for imageView in filledImageViews {
imageView.image = fullImage
}
refreshImageViews()
}
}
// Set the minimum rating value
@IBInspectable open var minRatingValue: Int = 0 {
didSet {
// Update current rating if needed
if currentRatingValue < Double(minRatingValue) {
currentRatingValue = Double(minRatingValue)
refreshImageViews()
}
}
}
// Set the maximum rating value
@IBInspectable open var maxRatingValue: Int = 5 {
didSet {
if maxRatingValue != oldValue {
removeImageViews()
initImageViews()
setNeedsLayout()
refreshImageViews()
}
}
}
// Set the current rating value
// we'll comparing the percent of currentRatingValue and maxRatingValue,
// e.g: max: 5 <-> current: 2.5, So, our rating result's 50% filled and 50% outline.
@IBInspectable open var currentRatingValue: Double = 0 {
didSet {
if currentRatingValue != oldValue {
refreshImageViews()
}
}
}
// MARK: RatingViewType
// Defines the type of rating view
public enum RatingViewType: Int {
case fullRating
case halfRating
case floatRating
// Returns true if rating can contain decimal places
func supportsFractions() -> Bool {
return self == .halfRating || self == .floatRating
}
}
// MARK: Initializations
required override public init(frame: CGRect) {
super.init(frame: frame)
initImageViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initImageViews()
}
// MARK: Helper methods
private func initImageViews() {
guard normalImageViews.isEmpty && filledImageViews.isEmpty else {
return
}
// Add new image views
for _ in 0..<maxRatingValue {
let normalImageView = UIImageView()
normalImageView.contentMode = imageContentMode
normalImageView.image = normalImage
normalImageViews.append(normalImageView)
addSubview(normalImageView)
let fullImageView = UIImageView()
fullImageView.contentMode = imageContentMode
fullImageView.image = fullImage
filledImageViews.append(fullImageView)
addSubview(fullImageView)
}
}
private func removeImageViews() {
// Remove old image views
for i in 0..<normalImageViews.count {
var imageView = normalImageViews[i]
imageView.removeFromSuperview()
imageView = filledImageViews[i]
imageView.removeFromSuperview()
}
normalImageViews.removeAll(keepingCapacity: false)
filledImageViews.removeAll(keepingCapacity: false)
}
// refreshImageViews hides or shows full images
private func refreshImageViews() {
for i in 0..<filledImageViews.count {
let imageView = filledImageViews[i]
if currentRatingValue >= Double(i+1) {
imageView.layer.mask = nil
imageView.isHidden = false
} else if currentRatingValue > Double(i) && currentRatingValue < Double(i+1) {
// Set mask layer for full image
let maskLayer = CALayer()
maskLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(currentRatingValue-Double(i))*imageView.frame.size.width, height: imageView.frame.size.height)
maskLayer.backgroundColor = UIColor.black.cgColor
imageView.layer.mask = maskLayer
imageView.isHidden = false
} else {
imageView.layer.mask = nil
imageView.isHidden = true
}
}
}
// Calculates the ideal ImageView size in a given CGSize
private func sizeForImage(_ image: UIImage, inSize size: CGSize) -> CGSize {
let imageRatio = image.size.width / image.size.height
let viewRatio = size.width / size.height
if imageRatio < viewRatio {
let scale = size.height / image.size.height
let width = scale * image.size.width
return CGSize(width: width, height: size.height)
} else {
let scale = size.width / image.size.width
let height = scale * image.size.height
return CGSize(width: size.width, height: height)
}
}
// Calculates new rating based on touch location in view
private func updateLocation(_ touch: UITouch) {
guard editable else {
return
}
let touchLocation = touch.location(in: self)
var newRating: Double = 0
for i in stride(from: (maxRatingValue-1), through: 0, by: -1) {
let imageView = normalImageViews[i]
guard touchLocation.x > imageView.frame.origin.x else {
continue
}
// Find touch point in image view
let newLocation = imageView.convert(touchLocation, from: self)
// Find decimal value for float or half rating
if imageView.point(inside: newLocation, with: nil) && (type.supportsFractions()) {
let decimalNum = Double(newLocation.x / imageView.frame.size.width)
// New rating for float type
newRating = Double(i) + decimalNum
if type == .halfRating {
// New rating for half type
newRating = Double(i) + (decimalNum > 0.75 ? 1 : (decimalNum > 0.25 ? 0.5 : 0))
}
} else {
// New rating for full type
newRating = Double(i) + 1.0
}
break
}
// Check min rating
currentRatingValue = newRating < Double(minRatingValue) ? Double(minRatingValue) : newRating
// Update delegate
delegate?.isUpdateRatingView(self, isUpdating: currentRatingValue)
}
// Override to calculate ImageView frames
override open func layoutSubviews() {
super.layoutSubviews()
guard let normalImage = normalImage else {
return
}
let desiredImageWidth = frame.size.width / CGFloat(normalImageViews.count)
let maxImageWidth = max(minImageSize.width, desiredImageWidth)
let maxImageHeight = max(minImageSize.height, frame.size.height)
let imageViewSize = sizeForImage(normalImage, inSize: CGSize(width: maxImageWidth, height: maxImageHeight))
let imageXOffset = (frame.size.width - (imageViewSize.width * CGFloat(normalImageViews.count))) /
CGFloat((normalImageViews.count - 1))
for i in 0..<maxRatingValue {
let imageFrame = CGRect(x: i == 0 ? 0 : CGFloat(i)*(imageXOffset+imageViewSize.width), y: 0, width: imageViewSize.width, height: imageViewSize.height)
var imageView = normalImageViews[i]
imageView.frame = imageFrame
imageView = filledImageViews[i]
imageView.frame = imageFrame
}
refreshImageViews()
}
// MARK: - Touch events
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
updateLocation(touch)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
updateLocation(touch)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didUpdateRatingView(self, didUpdate: currentRatingValue)
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didUpdateRatingView(self, didUpdate: currentRatingValue)
}
}
| 35.269504 | 162 | 0.592198 |
ff324e67282efaf903fe800384d44e452b7c6061 | 809 | //
// ActivityStateViewViewModel.swift
// AlphaWallet
//
// Created by Vladyslav Shepitko on 19.03.2021.
//
import UIKit
struct ActivityStateViewViewModel {
var stateImage: UIImage? {
switch state {
case .completed:
return nil
case .pending:
return R.image.activityPending()
case .failed:
return R.image.activityFailed()
}
}
var isInPendingState: Bool {
switch state {
case .completed, .failed:
return false
case .pending:
return true
}
}
private let state: Activity.State
private let nativeViewType: Activity.NativeViewType
init(activity: Activity) {
state = activity.state
nativeViewType = activity.nativeViewType
}
}
| 20.225 | 55 | 0.594561 |
9cdf40e7389075f79760d86493cf294cf1bc9777 | 1,003 | //
// korgLowPassFilter.swift
// AudioKit
//
// Autogenerated by scripts by Aurelius Prochazka. Do not edit directly.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
extension AKComputedParameter {
/// Analogue model of the Korg 35 Lowpass Filter
///
/// - returns: AKOperation
/// - parameter input: Input audio signal
/// - parameter cutoffFrequency: Filter cutoff (Default: 1000.0, Minimum: 0.0, Maximum: 22050.0)
/// - parameter resonance: Filter resonance (should be between 0-2) (Default: 1.0, Minimum: 0.0, Maximum: 2.0)
/// - parameter saturation: Filter saturation. (Default: 0.0, Minimum: 0.0, Maximum: 10.0)
///
public func korgLowPassFilter(
cutoffFrequency: AKParameter = 1_000.0,
resonance: AKParameter = 1.0,
saturation: AKParameter = 0.0
) -> AKOperation {
return AKOperation(module: "wpkorg35",
inputs: toMono(), cutoffFrequency, resonance, saturation)
}
}
| 35.821429 | 114 | 0.648056 |
9c9ee3543effa74854b33927079eefb1b0608965 | 11,765 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Distributed Actors open source project
//
// Copyright (c) 2019-2022 Apple Inc. and the Swift Distributed Actors project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of Swift Distributed Actors project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import DistributedActors
import Logging
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: ActorSingletonProxy
/// Proxy for a singleton actor.
///
/// The underlying `_ActorRef<Message>` for the singleton might change due to re-allocation, but all of that happens
/// automatically and is transparent to the ref holder.
///
/// The proxy has a buffer to hold messages temporarily in case the singleton is not available. The buffer capacity
/// is configurable in `ActorSingletonSettings`. Note that if the buffer becomes full, the *oldest* message
/// would be disposed to allow insertion of the latest message.
///
/// The proxy subscribes to events and feeds them into `AllocationStrategy` to determine the node that the
/// singleton runs on. If the singleton falls on *this* node, the proxy will spawn a `ActorSingletonManager`,
/// which manages the actual singleton actor, and obtain the ref from it. The proxy instructs the
/// `ActorSingletonManager` to hand over the singleton whenever the node changes.
internal class ActorSingletonProxy<Message: Codable> {
/// Settings for the `ActorSingleton`
private let settings: ActorSingletonSettings
/// The strategy that determines which node the singleton will be allocated
private let allocationStrategy: ActorSingletonAllocationStrategy
/// _Props of the singleton behavior
private let singletonProps: _Props?
/// The singleton behavior.
/// If `nil`, then this node is not a candidate for hosting the singleton. It would result
/// in a failure if `allocationStrategy` selects this node by mistake.
private let singletonBehavior: _Behavior<Message>?
/// The node that the singleton runs on
private var targetNode: UniqueNode?
/// The singleton ref
private var ref: _ActorRef<Message>?
/// The manager ref; non-nil if `targetNode` is this node
private var managerRef: _ActorRef<ActorSingletonManager<Message>.Directive>?
/// Message buffer in case singleton `ref` is `nil`
private let buffer: _StashBuffer<Message>
init(settings: ActorSingletonSettings, allocationStrategy: ActorSingletonAllocationStrategy, props: _Props? = nil, _ behavior: _Behavior<Message>? = nil) {
self.settings = settings
self.allocationStrategy = allocationStrategy
self.singletonProps = props
self.singletonBehavior = behavior
self.buffer = _StashBuffer(capacity: settings.bufferCapacity)
}
var behavior: _Behavior<Message> {
.setup { context in
if context.system.settings.enabled {
// Subscribe to ``Cluster/Event`` in order to update `targetNode`
context.system.cluster.events.subscribe(
context.subReceive(_SubReceiveId(id: "clusterEvent-\(context.name)"), Cluster.Event.self) { event in
try self.receiveClusterEvent(context, event)
}
)
} else {
// Run singleton on this node if clustering is not enabled
context.log.debug("Clustering not enabled. Taking over singleton.")
try self.takeOver(context, from: nil)
}
return _Behavior<Message>.receiveMessage { message in
try self.forwardOrStash(context, message: message)
return .same
}.receiveSpecificSignal(_Signals._PostStop.self) { context, _ in
// TODO: perhaps we can figure out where `to` is next and hand over gracefully?
try self.handOver(context, to: nil)
return .same
}
}
}
private func receiveClusterEvent(_ context: _ActorContext<Message>, _ event: Cluster.Event) throws {
// Feed the event to `AllocationStrategy` then forward the result to `updateTargetNode`,
// which will determine if `targetNode` has changed and react accordingly.
let node = self.allocationStrategy.onClusterEvent(event)
try self.updateTargetNode(context, node: node)
}
private func updateTargetNode(_ context: _ActorContext<Message>, node: UniqueNode?) throws {
guard self.targetNode != node else {
context.log.debug("Skip updating target node; New node is already the same as current targetNode", metadata: self.metadata(context))
return
}
let selfNode = context.system.cluster.uniqueNode
let previousTargetNode = self.targetNode
self.targetNode = node
switch node {
case selfNode:
context.log.debug("Node \(selfNode) taking over singleton \(self.settings.name)")
try self.takeOver(context, from: previousTargetNode)
default:
if previousTargetNode == selfNode {
context.log.debug("Node \(selfNode) handing over singleton \(self.settings.name)")
try self.handOver(context, to: node)
}
// Update `ref` regardless
self.updateRef(context, node: node)
}
}
private func takeOver(_ context: _ActorContext<Message>, from: UniqueNode?) throws {
guard let singletonBehavior = self.singletonBehavior else {
preconditionFailure("The actor singleton \(self.settings.name) cannot run on this node. Please review AllocationStrategySettings and/or actor singleton usage.")
}
// Spawn the manager then tell it to spawn the singleton actor
self.managerRef = try context.system._spawnSystemActor(
"singletonManager-\(self.settings.name)",
ActorSingletonManager(settings: self.settings, props: self.singletonProps ?? _Props(), singletonBehavior).behavior,
props: ._wellKnown
)
// Need the manager to tell us the ref because we can't resolve it due to random incarnation
let refSubReceive = context.subReceive(_SubReceiveId(id: "ref-\(context.name)"), _ActorRef<Message>?.self) {
self.updateRef(context, $0)
}
self.managerRef?.tell(.takeOver(from: from, replyTo: refSubReceive))
}
private func handOver(_ context: _ActorContext<Message>, to: UniqueNode?) throws {
// The manager stops after handing over the singleton
self.managerRef?.tell(.handOver(to: to))
self.managerRef = nil
}
private func updateRef(_ context: _ActorContext<Message>, node: UniqueNode?) {
switch node {
case .some(let node) where node == context.system.cluster.uniqueNode:
self.ref = context.myself
case .some(let node):
// Since the singleton is spawned as a child of the manager, its incarnation is random and therefore we
// can't construct its address despite knowing the path and node. Only the manager running on `targetNode`
// (i.e., where the singleton runs) has the singleton `ref`, and only the proxy on `targetNode` has `ref`
// pointing directly to the actual singleton. Proxies on other nodes connect to the singleton via `targetNode`
// proxy (i.e., their `ref`s point to `targetNode` proxy, not the singleton).
// FIXME: connecting to the singleton through proxy incurs an extra hop. an optimization would be
// to have proxies ask the `targetNode` proxy to "send me the ref once you have taken over"
// and before then the proxies can either set `ref` to `nil` (to stash messages) or to `targetNode`
// proxy as we do today. The challenge lies in serialization, as ActorSingletonProxy and ActorSingletonManager are generic.
let resolveContext = _ResolveContext<Message>(id: ._singletonProxy(name: self.settings.name, remote: node), system: context.system)
let ref = context.system._resolve(context: resolveContext)
self.updateRef(context, ref)
case .none:
self.ref = nil
}
}
private func updateRef(_ context: _ActorContext<Message>, _ newRef: _ActorRef<Message>?) {
context.log.debug("Updating ref from [\(optional: self.ref)] to [\(optional: newRef)], flushing \(self.buffer.count) messages")
self.ref = newRef
// Unstash messages if we have the singleton
guard let singleton = self.ref else {
return
}
while let stashed = self.buffer.take() {
context.log.debug("Flushing \(stashed), to \(singleton)")
singleton.tell(stashed)
}
}
private func forwardOrStash(_ context: _ActorContext<Message>, message: Message) throws {
// Forward the message if `singleton` is not `nil`, else stash it.
if let singleton = self.ref {
context.log.trace("Forwarding message \(message), to: \(singleton.id)", metadata: self.metadata(context))
singleton.tell(message)
} else {
do {
try self.buffer.stash(message: message)
context.log.trace("Stashed message: \(message)", metadata: self.metadata(context))
} catch {
switch error {
case _StashError.full:
// TODO: log this warning only "once in while" after buffer becomes full
context.log.warning("Buffer is full. Messages might start getting disposed.", metadata: self.metadata(context))
// Move the oldest message to dead letters to make room
if let oldestMessage = self.buffer.take() {
context.system.deadLetters.tell(DeadLetter(oldestMessage, recipient: context.id))
}
default:
context.log.warning("Unable to stash message, error: \(error)", metadata: self.metadata(context))
}
}
}
}
}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: ActorSingletonManager + logging
extension ActorSingletonProxy {
func metadata<Message>(_: _ActorContext<Message>) -> Logger.Metadata {
var metadata: Logger.Metadata = [
"tag": "singleton",
"singleton/name": "\(self.settings.name)",
"singleton/buffer": "\(self.buffer.count)/\(self.settings.bufferCapacity)",
]
metadata["targetNode"] = "\(optional: self.targetNode?.debugDescription)"
if let ref = self.ref {
metadata["ref"] = "\(ref.id)"
}
if let managerRef = self.managerRef {
metadata["managerRef"] = "\(managerRef.id)"
}
return metadata
}
}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Singleton path / address
extension ActorID {
static func _singletonProxy(name: String, remote node: UniqueNode) -> ActorID {
.init(remote: node, path: ._singletonProxy(name: name), incarnation: .wellKnown)
}
}
extension ActorPath {
static func _singletonProxy(name: String) -> ActorPath {
try! ActorPath._system.appending("singletonProxy-\(name)")
}
}
| 46.87251 | 172 | 0.621929 |
899065bfee68d44fda2d56ca1b36667491a27456 | 1,784 | /* The MIT License
*
* Copyright © 2020 NBCO YooMoney LLC
*
* 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.
*/
extension TextControl {
/// Modes for the line in the text control
enum LineMode {
/// Never visible
case never
/// If control is active shows normal line for normal state or error line if state is error
/// If control is not active and state is error shows error line
case whileActiveWithStateOrError
/// If control is active shows normal line for any state
/// If control is not active and state is error shows error line
case whileActiveOrError
/// Default mode is while active or error
static let `default`: LineMode = .whileActiveOrError
}
}
| 40.545455 | 99 | 0.722534 |
16a952db03cc3d4f338ab81d570751d010ba6935 | 5,057 | //
// ViewController.swift
// PeopleAndAppleStockPrices
//
// Created by Alex Paul on 12/7/18.
// Copyright © 2018 Pursuit. All rights reserved.
//
import UIKit
class StockViewController: UIViewController {
@IBOutlet weak var stocksTableView: UITableView!
// needs to be a 2d array
private var stockPrices = [StockPrice]()
var stocksByYear = [[StockPrice]]()
var stockMonth = [[StockPrice]]()
var sectionNames = [String]()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let detailedViewController = segue.destination as? StocksDetailedViewController,
let cellSelected = stocksTableView.indexPathForSelectedRow else { return }
let sectionStocks = self.stocksBySection(section: cellSelected.section)
let thisStock = sectionStocks[cellSelected.row]
detailedViewController.perstockDetails = thisStock
}
override func viewDidLoad() {
super.viewDidLoad()
// if let prices = StockPriceParser.getStocks() {
// stockPrices = prices
// print("there are \(stockPrices.count) prices")
// }
stocksTableView.dataSource = self
stocksTableView.delegate = self
title = "Stocks"
loadData()
getSectionNames()
}
func getSectionNames() {
for stock in stockPrices {
if !sectionNames.contains(stock.sectionName) { // if the section name does not have the section then add that section
sectionNames.append(stock.sectionName)
}
}
}
func stocksBySection(section: Int) -> [StockPrice] {
return stockPrices.filter ({$0.sectionName == sectionNames[section]})
}
func yearAndMonth(){
for yearNum in 2016...2018 {
let yearStock = stockPrices.filter{(stock) -> Bool in
let dateSeparated = stock.date.components(separatedBy: "-")
let currentStockYear = dateSeparated[0]
if Int(currentStockYear) == yearNum {
return true
} else {
return false
}
}
stocksByYear.append(yearStock)
}
for arrYearStocks in stocksByYear {
for monthNum in 1...12 {
let stockMonthArr = arrYearStocks.filter { (stock) -> Bool in
let dateSeparated = stock.date.components(separatedBy: "-")
let currentStockMonth = dateSeparated[1]
if Int(currentStockMonth) == monthNum {
return true
} else {
return false
}
}
if !stockMonthArr.isEmpty {
stockMonth.append(stockMonthArr)
}
}
}
}
func loadData() {
if let path = Bundle.main.path(forResource: "applstockinfo", ofType: "json") {
let url = URL.init(fileURLWithPath: path)
if let data = try? Data.init(contentsOf: url) {
do {
let stocksArray = try JSONDecoder().decode([StockPrice].self, from: data)
stockPrices = stocksArray.sorted(by: { (stockOne, stockTwo) -> Bool in
return stockOne.date < stockTwo.date
})
} catch {
print(error)
}
}
}
}
}
extension StockViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return sectionNames.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let thisSection = sectionNames[section]
let stocksInThissection = stockPrices.filter({$0.sectionName == thisSection})
var sum = 0.0
for stock in stocksInThissection {
sum += stock.open
}
let average = sum / Double(stocksInThissection.count)
return sectionNames[section] + " " + "Average \(String(format: "%.2f",average))"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stocksBySection(section: section).count // this will determine your sections
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StockPriceCell", for: indexPath)
let stocksinthissection = stocksBySection(section: indexPath.section)
let stock = stocksinthissection[indexPath.row]
cell.textLabel?.text = stock.date
cell.detailTextLabel?.text = "\(stock.open)"
cell.detailTextLabel?.text = "$" + String(format: "%.2f", stock.open)
return cell
}
}
| 33.490066 | 129 | 0.570496 |
d95ad658eebf7514368e34c210b7b279ba900754 | 4,814 | import Foundation
import Quick
import Nimble
@testable import Parchment
class PagingStateSpec: QuickSpec {
override func spec() {
describe("PagingState") {
describe("Scrolling") {
it("returns the current paging item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: Item(index: 1),
progress: 0,
initialContentOffset: .zero,
distance: 0)
expect(state.currentPagingItem).to(equal(Item(index: 0)))
}
it("returns the correct progress") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: Item(index: 1),
progress: 0.5,
initialContentOffset: .zero,
distance: 0)
expect(state.progress).to(equal(0.5))
}
describe("has an upcoming paging item") {
it("returns the correct upcoming paging item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: Item(index: 1),
progress: 0,
initialContentOffset: .zero,
distance: 0)
expect(state.upcomingPagingItem).to(equal(Item(index: 1)))
}
describe("visuallySelectedPagingItem") {
describe("progress is larger then 0.5") {
it("returns the upcoming paging item as the visually selected item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: Item(index: 1),
progress: 0.6,
initialContentOffset: .zero,
distance: 0)
expect(state.visuallySelectedPagingItem).to(equal(Item(index: 1)))
}
}
describe("progress is smaller then 0.5") {
it("returns the current paging item as the visually selected item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: Item(index: 1),
progress: 0.3,
initialContentOffset: .zero,
distance: 0)
expect(state.visuallySelectedPagingItem).to(equal(Item(index: 0)))
}
}
}
}
describe("does not have an upcoming paging item") {
it("returns nil for upcoming paging item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: nil,
progress: 0,
initialContentOffset: .zero,
distance: 0)
expect(state.upcomingPagingItem).to(beNil())
}
describe("visuallySelectedPagingItem") {
describe("progress is larger then 0.5") {
it("returns the current paging item as the visually selected item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: nil,
progress: 0.6,
initialContentOffset: .zero,
distance: 0)
expect(state.visuallySelectedPagingItem).to(equal(Item(index: 0)))
}
}
describe("progress is smaller then 0.5") {
it("returns the current paging item as the visually selected item") {
let state: PagingState = .scrolling(
pagingItem: Item(index: 0),
upcomingPagingItem: nil,
progress: 0.3,
initialContentOffset: .zero,
distance: 0)
expect(state.visuallySelectedPagingItem).to(equal(Item(index: 0)))
}
}
}
}
}
describe("Selected") {
let state: PagingState = .selected(pagingItem: Item(index: 0))
it("returns the current paging item") {
expect(state.currentPagingItem).to(equal(Item(index: 0)))
}
it("returns nil for the upcoming paging item") {
expect(state.upcomingPagingItem).to(beNil())
}
it("returns zero for the progress") {
expect(state.progress).to(equal(0))
}
it("returns the current paging item as the visually selected item") {
expect(state.visuallySelectedPagingItem).to(equal(Item(index: 0)))
}
}
}
}
}
| 32.972603 | 84 | 0.50187 |
75b5f16c61182b02585e8971052578f077b52f89 | 360 | //
// RatingResponse.swift
// TMDB
//
// Created by Tuyen Le on 9/27/20.
// Copyright © 2020 Tuyen Le. All rights reserved.
//
import Foundation
struct RatingResponse: Decodable {
let status: Int
let message: String
enum CodingKeys: String, CodingKey {
case status = "status_code"
case message = "status_message"
}
}
| 18 | 51 | 0.641667 |
914ac6e6606494298f03deb139bb9d82383fb73a | 17,171 | //
// IR.swift
// typewriter
//
// Created by mrriddler on 2017/6/5.
// Copyright © 2017年 typewriter. All rights reserved.
//
import Foundation
typealias Comments = [String]
typealias Type = String
typealias Variable = String
enum Nullable: String {
case required = "required"
case almost = "almost"
case optional = "optional"
}
enum RewrittenFormat {
case prototype
case json
static func formatFrom(describeFormat: DescribeFormat) -> RewrittenFormat {
switch describeFormat {
case .GPPLObjC:
return RewrittenFormat.prototype
case .GPPLJava:
return RewrittenFormat.prototype
case .JSON:
return RewrittenFormat.json
}
}
}
typealias Annotation = [String]
typealias Rewritten = (IRType?, Variable?, RewrittenFormat?)
typealias MemberVariable = (Comments?, IRType, Variable, Rewritten?, Nullable, Annotation?)
func finalVariable(memberVariable: MemberVariable) -> Variable {
return memberVariable.3?.1 ?? memberVariable.2
}
func finalType(memberVariable: MemberVariable) -> IRType {
return memberVariable.3?.0 ?? memberVariable.1
}
enum GenerateModuleType {
case prototypeInitializer
case prototypeInitializerPreprocess
case jsonInitializer
case jsonInitializerPreprocess
case equality
case print
case archive
case copy
case hash
case unidirectionalDataflow
case mutableVersion
}
typealias GenerateModules = [GenerateModuleType]
indirect enum IRType {
case float
case double
case uint32
case uint64
case sint32
case sint64
case bool
case string
case date
case array(type: IRType?)
case map(keyType: IRType?, valueType: IRType?)
case ambiguous(type: Type)
case any
func getNestedType() -> Type? {
switch self {
case .ambiguous(let type):
return type
case .array(let type):
if let type = type {
return type.getNestedType()
} else {
return nil
}
case .map(_, let valueType):
if let valueType = valueType {
return valueType.getNestedType()
} else {
return nil
}
default:
return nil
}
}
func setNestedType(desType: Type) -> IRType {
switch self {
case .ambiguous(_):
return .ambiguous(type: desType)
case .array(let type):
if let type = type {
return .array(type: type.setNestedType(desType: desType))
} else {
return .array(type: .ambiguous(type: desType))
}
case .map(let keyType, let valueType):
if let keyType = keyType, let valueType = valueType {
return .map(keyType: keyType, valueType: valueType.setNestedType(desType: desType))
} else {
return .map(keyType: .string, valueType: .ambiguous(type: desType))
}
default:
return self
}
}
func getNestedIRType() -> IRType? {
switch self {
case .ambiguous:
return self
case .array(let type):
if let type = type {
if let nestedType = type.getNestedIRType() {
return nestedType
} else {
return nil
}
} else {
return nil
}
case .map(_, let valueType):
if let valueType = valueType {
if let nestedType = valueType.getNestedIRType() {
return nestedType
} else {
return nil
}
} else {
return nil
}
default:
return nil
}
}
func setNestedIRType(desType: IRType) -> IRType {
switch self {
case .ambiguous(_):
return desType
case .array(let type):
if let type = type {
return .array(type: type.setNestedIRType(desType: desType))
} else {
return desType
}
case .map(let keyType, let valueType):
if let keyType = keyType, let valueType = valueType {
return .map(keyType: keyType, valueType: valueType.setNestedIRType(desType: desType))
} else {
return desType
}
default:
return self
}
}
}
extension IRType: Equatable {
public static func ==(lhs: IRType, rhs: IRType) -> Bool {
switch (lhs, rhs) {
case (.float, .float):
return true
case (.double, .double):
return true
case (.uint32, .uint32):
return true
case (.uint64, .uint64):
return true
case (.sint32, .sint32):
return true
case (.sint64, .sint64):
return true
case (.bool, .bool):
return true
case (.string, .string):
return true
case (.date, .date):
return true
case (.array, .array):
return true
case (.map, .map):
return true
case (.ambiguous, .ambiguous):
return true
case (.any, .any):
return true
default:
return false
}
}
}
class IR {
var path: String
var inputFormat: DescribeFormat
var srcName: String
var srcInheriting: String?
var srcImplement: [String]?
var desName: String
var desInheriting: String?
var memberVariableList: [MemberVariable]!
var generateModules: GenerateModules!
var referenceMap: [Variable: String]!
fileprivate var analyzer: Analyzer
init(path: String,
inputFormat: DescribeFormat,
srcName: String,
srcInheriting: String?,
srcImplement: [String]?,
desName: String,
desInheriting: String?,
memberVariableList: [MemberVariable]?,
generateModules: GenerateModules?,
referenceMap: [Variable: String]?,
analyzer: Analyzer) {
self.path = path
self.inputFormat = inputFormat
self.srcName = srcName
self.srcInheriting = srcInheriting
self.srcImplement = srcImplement
self.desName = desName
self.desInheriting = desInheriting
self.memberVariableList = memberVariableList
self.generateModules = generateModules
self.referenceMap = referenceMap
self.analyzer = analyzer
}
class func translationToIR(path: String,
inputFormat: DescribeFormat,
srcName: String,
srcInheriting: String?,
srcImplement: [String]?,
desName: String,
desInheriting: String?,
memberVariableToken: [MemberVariableToken],
options: AnalysisOptions,
flattenToken: [FlattenToken]?) -> IR {
var switchRewrittenToken = memberVariableToken
if inputFormat == .JSON {
switchRewrittenToken = switchRewrittenToken
.map{(varToken: MemberVariableToken) -> MemberVariableToken in
return (varToken.0,
varToken.1,
varToken.4 ?? varToken.2,
varToken.3,
(varToken.4 != nil ? varToken.2 : nil),
varToken.5,
varToken.6)}
}
let analyzer = Analyzer(options: options,
memberVariableToken: switchRewrittenToken,
flattenToken: flattenToken)
let ir = IR(path: path,
inputFormat: inputFormat,
srcName: srcName,
srcInheriting: srcInheriting,
srcImplement: srcImplement,
desName: desName,
desInheriting: desInheriting,
memberVariableList: nil,
generateModules: nil,
referenceMap: nil,
analyzer: analyzer)
return ir
}
func deduce() {
switch inputFormat {
case .GPPLObjC:
memberVariableList = DeducePrototypeStrategy.deduceTokenList(
src: path,
comment: analyzer.containOption(optionType: .comment) != nil,
typeConvertor: typeConvertor(forLanguage: .ObjC),
tokenList: analyzer.memberVariableTokenList())
generateModules = DeducePrototypeStrategy.deduceOptions(options: analyzer.analysisOptions())
referenceMap = DeducePrototypeStrategy.deduceReferenceMap(typeConvertor: typeConvertor(forLanguage: .ObjC),
tokenList: analyzer.memberVariableTokenList())
case .GPPLJava:
memberVariableList = DeducePrototypeStrategy.deduceTokenList(
src: path,
comment: analyzer.containOption(optionType: .comment) != nil,
typeConvertor: typeConvertor(forLanguage: .Java),
tokenList: analyzer.memberVariableTokenList())
generateModules = DeducePrototypeStrategy.deduceOptions(options: analyzer.analysisOptions())
referenceMap = DeducePrototypeStrategy.deduceReferenceMap(typeConvertor: typeConvertor(forLanguage: .Java),
tokenList: analyzer.memberVariableTokenList())
case .JSON:
memberVariableList = DeduceJSONStrategy.deduceTokenList(
src: path,
comment: analyzer.containOption(optionType: .comment) != nil,
tokenList: analyzer.memberVariableTokenList())
generateModules = DeduceJSONStrategy.deduceOptions(options: analyzer.analysisOptions())
referenceMap = DeduceJSONStrategy.deduceReferenceMap(tokenList: analyzer.memberVariableTokenList())
}
if isModelUnique() {
memberVariableList.insert((nil, .string, modelId(), nil, .optional, nil), at: 0);
}
}
func containModule(type: GenerateModuleType) -> Bool {
return generateModules.index(of: type) != nil
}
func isGenerateExtension() -> Bool {
return (isModelUnique() ||
containModule(type: .prototypeInitializerPreprocess) ||
containModule(type: .jsonInitializerPreprocess))
}
func isModelUnique() -> Bool {
return containModule(type: .unidirectionalDataflow)
}
func isMemberVariableReadOnly() -> Bool {
return analyzer.containOption(optionType: .immutable) != nil || analyzer.containOption(optionType: .constructOnly) != nil
}
func isContainRewrittenName() -> Bool {
for memberVariable in memberVariableList {
if memberVariable.3?.1 != nil {
return true
}
}
return false
}
func isContainBuildInRewrittenType() -> Bool {
return memberVariableList.contains(where: { element -> Bool in
if let rewrittenType = element.3?.0 {
switch (element.1, rewrittenType) {
case (.string, .float):
return true
case (.string, .double):
return true
case (.string, .sint32):
return true
case (.string, .sint64):
return true
case (.string, .uint32):
return true
case (.string, .uint64):
return true
case (.string, .bool):
return true
default:
break
}
}
return false
})
}
func isMemberVariableEnum(memberVariable: MemberVariable) -> Bool {
if let rewrittenType = memberVariable.3?.0 {
switch (memberVariable.1, rewrittenType) {
case (.string, .ambiguous):
if memberVariable.3?.2 != nil {
return false
} else {
return true
}
default:
break
}
}
return false
}
func isContainEnum() -> Bool {
return memberVariableList.contains{isMemberVariableEnum(memberVariable: $0)}
}
func findType(find: (IRType, IRType) -> Type?) -> [Type] {
var res = [Type]()
memberVariableList.forEach { (memberVariable: MemberVariable) in
_ = memberVariable.3?.0
.map{ (rewrittenType) in
switch (memberVariable.1, rewrittenType) {
case (.string, .ambiguous):
if !isMemberVariableEnum(memberVariable: memberVariable), let type = find(memberVariable.1, rewrittenType) {
res.append(type)
}
case (.ambiguous, .ambiguous),
(.array, .array),
(.map, .map):
if let type = find(memberVariable.1, rewrittenType) {
res.append(type)
}
default:
break
}
}
}
return res
}
func makeMemberVariableMap() -> [Variable: MemberVariable] {
var res = [Variable: MemberVariable]()
for memberVariable in memberVariableList {
res[finalVariable(memberVariable: memberVariable)] = memberVariable
}
return res
}
func makeRewrittenNameMap() -> [Variable: Variable] {
var res = [Variable: Variable]()
for memberVariable in memberVariableList {
if let rewritten = memberVariable.3?.1 {
res[rewritten] = memberVariable.2
}
}
return res
}
func makeFlattenMap() -> [Variable: Variable] {
var variableMap = [Variable: Variable]()
let flattenPath = flattenMemberVariablePath()
switch RewrittenFormat.formatFrom(describeFormat: inputFormat) {
case .json:
flattenPath.forEach({ (element) in
variableMap[element.0] = element.1
})
default:
break
}
return variableMap
}
func makeReferenceFlattenMap() -> [Variable: Variable] {
var variableMap = [Variable: Variable]()
memberVariableList.forEach { memberVariable in
if let rewrittenFormat = memberVariable.3?.2, memberVariable.3?.0 != nil {
switch rewrittenFormat {
case .json:
let variable = finalVariable(memberVariable: memberVariable)
if let referenceIR = jumpToReferenceIR(variable: variable) {
let flattenMap = referenceIR.makeFlattenMap()
flattenMap.forEach({ element in
variableMap["\(variable)\(memberVariableHierarchySeparator())\(element.key)"] = "\(variable)\(memberVariableHierarchySeparator())\(element.value)"
})
}
default:
break
}
}
}
return variableMap
}
func jumpToReferenceIR(variable: Variable) -> IR? {
if let path = referenceMap[variable] {
let referenceURL = URL(string: path, relativeTo: TranslationCache.sharedInstance.curDirectory)!
return TranslationCache.sharedInstance.irs[referenceURL]
}
return nil
}
func specialIncludeSuffix() -> String? {
return analyzer.containOption(optionType: .specialIncludeSuffix)
}
func modelId() -> String {
return "objectId"
}
}
extension IR {
func isContainFlattenMemberVariable() -> Bool {
return analyzer.isContainFlattenMemberVariable()
}
func memberVariableHierarchySeparator() -> String {
return analyzer.memberVariableHierarchySeparator()
}
func memberVariableRootPlaceHolder() -> String {
return analyzer.memberVariableRootPlaceHolder()
}
func memberVariableHierarchy() -> [Hierarchy] {
return analyzer.memberVariableHierarchy()
}
func referenceFreeHierachy() -> [Hierarchy] {
return analyzer.referenceFreeHierachy()
}
func flattenMemberVariablePath() -> [(Variable, String)] {
return analyzer.flattenMemberVariablePath()
}
}
| 32.769084 | 174 | 0.537534 |
bb7275844f33329ff607747338e182760df94b87 | 542 | //
// main.swift
// Reverse Integer
//
// Created by xuezhaofeng on 2017/8/3.
// Copyright © 2017年 paladinfeng. All rights reserved.
//
import Foundation
class Solution {
func reverse(_ x: Int) -> Int {
var temp: Int = x
var new: Int = 0
while temp != 0 {
new = new * 10 + temp % 10
temp = temp / 10
}
if abs(new) > Int(Int32.max) {
return 0
}
return new
}
}
let result = Solution().reverse(1534236469);
print(INT32_MAX)
print(result)
| 18.689655 | 55 | 0.535055 |
2867b48d36478ad699c8297e06f444eed1cd78cd | 3,410 | //
// Business.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class Business: NSObject {
let name: String?
let address: String?
let imageURL: NSURL?
let categories: String?
let distance: String?
let ratingImageURL: NSURL?
let reviewCount: NSNumber?
init(dictionary: NSDictionary) {
name = dictionary["name"] as? String
let imageURLString = dictionary["image_url"] as? String
if imageURLString != nil {
imageURL = NSURL(string: imageURLString!)!
} else {
imageURL = nil
}
let location = dictionary["location"] as? NSDictionary
var address = ""
if location != nil {
let addressArray = location!["address"] as? NSArray
if addressArray != nil && addressArray!.count > 0 {
address = addressArray![0] as! String
}
let neighborhoods = location!["neighborhoods"] as? NSArray
if neighborhoods != nil && neighborhoods!.count > 0 {
if !address.isEmpty {
address += ", "
}
address += neighborhoods![0] as! String
}
}
self.address = address
let categoriesArray = dictionary["categories"] as? [[String]]
if categoriesArray != nil {
var categoryNames = [String]()
for category in categoriesArray! {
let categoryName = category[0]
categoryNames.append(categoryName)
}
categories = categoryNames.joinWithSeparator(", ")
} else {
categories = nil
}
let distanceMeters = dictionary["distance"] as? NSNumber
if distanceMeters != nil {
let milesPerMeter = 0.000621371
distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue)
} else {
distance = nil
}
let ratingImageURLString = dictionary["rating_img_url_large"] as? String
if ratingImageURLString != nil {
ratingImageURL = NSURL(string: ratingImageURLString!)
} else {
ratingImageURL = nil
}
reviewCount = dictionary["review_count"] as? NSNumber
}
class func businesses(array array: [NSDictionary]) -> [Business] {
var businesses = [Business]()
for dictionary in array {
let business = Business(dictionary: dictionary)
businesses.append(business)
}
return businesses
}
class func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) {
YelpClient.sharedInstance.searchWithTerm(term, completion: completion)
}
class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> Void {
YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, completion: completion)
}
class func searchWithTermAndOffset(term: String, offset: Int, completion: ([Business]!, NSError!) -> Void) {
YelpClient.sharedInstance.searchWithTermAndOffset(term, offset: offset, completion: completion) }
}
| 34.795918 | 156 | 0.580059 |
deb2a737ef5189c9b67efe0838725112e9c681be | 1,189 | //
// RotationLockedNavigationController.swift
// Screenshotter
//
// Created by Rizwan Sattar on 11/13/14.
// Copyright (c) 2014 Cluster Labs, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class RotationLockedNavigationController: UINavigationController {
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return [UIInterfaceOrientationMask.Portrait]
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return UIInterfaceOrientation.Portrait
}
override func shouldAutorotate() -> Bool {
return true
}
}
| 31.289474 | 92 | 0.738436 |
c15d5db2404bf61bf2dbf7100b25367fe55cedb8 | 5,811 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
import MapKit
import CoreLocation
class RestaurantDetailViewController: UIViewController {
var chosenRestaurant:Restaurant! /* Restaurant chosen by the user to see details. */
var reviewKeywords:String!
@IBOutlet weak var eventDetailHolderView: UIView!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var scrollViewContentView: UIView!
@IBOutlet weak var restaurantDetailHolderView: UIView!
let kBackButtonTitle = "RESTAURANTS"
/// restaurant detail view
weak var restaurantDetailView: RecommendedRestaurantDetailView!
private let buttonFrame = CGRect.init(x: 31, y: 39.5, width: 109, height: 13)
/**
Method called upon view did load to set up holderView, map, and adds subview
*/
override func viewDidLoad() {
super.viewDidLoad()
setUpHolderViewWithRestaurant()
setupRecommendedRestaurantDetailView()
eventDetailHolderView.addSubview(restaurantDetailView)
// set up navigation items.
Utils.setNavigationItems(viewController: self, rightButtons: [MoreIconBarButtonItem()], leftButtons: [WhitePathIconBarButtonItem(), UIBarButtonItem(customView: backButton)])
Utils.setupNavigationTitleLabel(viewController: self, title: "", spacing: 1.0, titleFontSize: 17, color: UIColor.white)
self.navigationController?.isNavigationBarHidden = false
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
// Set up the navigation bar so that we can color the nav bar to be dark blue, and the default symbols to be white.
Utils.setupBackButton(button: backButton, title: kBackButtonTitle, textColor: UIColor.white, frame: buttonFrame)
// set up navigation items.
Utils.setNavigationItems(viewController: self, rightButtons: [MoreIconBarButtonItem()], leftButtons: [WhitePathIconBarButtonItem(), UIBarButtonItem(customView: backButton)])
Utils.setupNavigationTitleLabel(viewController: self, title: "", spacing: 1.0, titleFontSize: 17, color: UIColor.white)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
}
@IBAction func didPressBackButton(_ sender: AnyObject) {
_ = self.navigationController?.popViewController(animated: true)
}
func setupRecommendedRestaurantDetailView() {
// splice the restaurant address into address, city, state.
var locationAddress = self.chosenRestaurant.getAddress().components(separatedBy: ",")
// load data into restaurant details view
restaurantDetailView.setupData(openNowStatus: self.chosenRestaurant.getOpenNowStatus(),
openingTimeNow: self.chosenRestaurant.getOpeningTimeNow(),
locationName:self.chosenRestaurant.getName(),
locationAddress: locationAddress[0],
city: "\(locationAddress[1]),\(locationAddress[2])",
fullAddress: self.chosenRestaurant.getAddress(),
priceLevel: Double(self.chosenRestaurant.getExpense()),
rating: self.chosenRestaurant.getRating(),
reviewNegativeHighlight: self.determineReviewSentiment(type: "negative"),
reviewPositiveHighlight: self.determineReviewSentiment(type: "positive"))
// Make website view clickable.
let tap = UITapGestureRecognizer(target: self, action: #selector(visitWebsiteTapped))
restaurantDetailView.visitWebsiteView.addGestureRecognizer(tap)
}
func setUpHolderViewWithRestaurant() {
restaurantDetailView = RecommendedRestaurantDetailView.instanceFromNib()
}
func visitWebsiteTapped() {
UIApplication.shared.open(URL(string: self.chosenRestaurant.getWebsite())!, options: [:])
}
/**
Method to determine positive and negative sentiments in reviews.
- paramater type: String to specify whether to determine positive or negative sentiments.
*/
func determineReviewSentiment(type:String) -> String{
if self.chosenRestaurant.getReviews().count == 0 {
return "No reviews found for me to analyze what people thought of this restaurant."
}
if type == "negative" {
if self.chosenRestaurant.getNegativeSentiments().count == 0 {
return "I found 0 hints to any negative sentiments in the reviews I have."
} else {
return self.chosenRestaurant.getNegativeSentiments().joined(separator: ", ")
}
} else {
if self.chosenRestaurant.getPositiveSentiments().count == 0 {
return "I found 0 hints to any positive sentiments in the reviews I have."
} else {
return self.chosenRestaurant.getPositiveSentiments().joined(separator: ", ")
}
}
}
}
| 46.488 | 181 | 0.663053 |
281a5908d11e892b30b3a63aadf890bdf890fc2d | 1,235 | import Foundation
import UIKit
import Carlos
class ImageCacheSampleViewController: BaseCacheViewController {
private var cache: BasicCache<URL, UIImage>!
@IBOutlet weak var imageView: UIImageView?
override func fetchRequested() {
super.fetchRequested()
cache.get(URL(string: urlKeyField?.text ?? "")!)
.onCompletion { result in
guard let imageView = self.imageView else {
return
}
switch result {
case .success(let image):
imageView.image = image
case .error(_):
imageView.image = self.imageWithColor(.darkGray, size: imageView.frame.size)
default:
break
}
}
}
private func imageWithColor(_ color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
override func titleForScreen() -> String {
return "Image cache"
}
override func setupCache() {
super.setupCache()
cache = CacheProvider.imageCache()
}
}
| 25.204082 | 86 | 0.650202 |
ddbf127f27af43be0d1ce9be77e3362f17d4e0f3 | 1,136 | import Vapor
final class Station : NodeRepresentable, JSONRepresentable {
var stationID : Int
var name : String
var lat : Double
var lon : Double
var available : Int
var empty : Int
init(stationID : Int, name : String, lat : Double, lon : Double, available : Int, empty : Int) {
self.stationID = stationID
self.name = name
self.lat = lat
self.lon = lon
self.available = available
self.empty = empty
}
func makeNode(in context: Context?) throws -> Node {
return try Node(node: ["id" : stationID, "a" : available, "e" : empty])
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", stationID)
try json.set("a", available)
try json.set("e", empty)
/*
try json.set("stationID", stationID)
try json.set("name", name)
try json.set("lat", lat)
try json.set("lon", lon)
try json.set("available", available)
try json.set("empty", empty)
*/
return json
}
}
| 24.170213 | 100 | 0.52993 |
72cc5a612db6aae077b4d78a12a75351e93c34a1 | 2,361 | //
// MarvelAPIClientTest.swift
// MarvelTests
//
// Created by Lorrayne Paraiso on 02/11/18.
// Copyright © 2018 Lorrayne Paraiso. All rights reserved.
//
@testable import Marvel
import XCTest
class MarvelAPIClientTest: XCTestCase {
private var apiClient: MarvelAPIClient = MarvelAPIClient()
func testAPIWithNoInvalidParams() {
let expectation = XCTestExpectation(description: "Calls the Marvel API with limit/count set to an invalid value. This should return nothing or nil")
apiClient.get(GetCharacters(limit: -128, orderBy: SortingOrder.REVERSED_MODIFIED.rawValue)) { (response) in
switch(response) {
case .success(_):
XCTFail("The API should not have returned valid data! Something is broken on Marvel's end.")
expectation.fulfill()
break
case .failure(let error):
XCTAssert(type(of: error) == APIError.self, "The API client should've returned an error of type APIError. Something is broken on Marvel's end (or maybe you messed up somewhere...).")
expectation.fulfill()
break
}
}
wait(for: [expectation], timeout: 3.0)
}
func testAPIClientWithValidParams() {
let expectation = XCTestExpectation(description: "Calls the Marvel API with limit/count set to 10. This should return something")
apiClient.get(GetCharacters(limit: 10, orderBy: SortingOrder.REVERSED_MODIFIED.rawValue)) { (response) in
switch(response) {
case .success(let dataContainer):
XCTAssertNotNil(dataContainer, "Data container must not be nil!")
XCTAssertNotNil(dataContainer.results, "Data container's results must not be nil!")
XCTAssertEqual(dataContainer.results.count, 10, "Data container's results must contain 10 items!")
expectation.fulfill()
break
case .failure(let error):
XCTFail("The API should have returned valid data! Something is broken on Marvel's end (or maybe you messed up somewhere...). Error: \(error)")
expectation.fulfill()
break
}
}
wait(for: [expectation], timeout: 10.0)
}
}
| 39.35 | 198 | 0.616264 |
1a314dc233e6a2e467e5d2ea5472b2e343c071f7 | 872 | //
// ViewController.swift
// PipeSlider
//
// Created by mehdi on 10/29/1398 AP.
// Copyright © 1398 AP nikoosoft. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var leftToRight: PipeSlider! {
didSet {
leftToRight.direction = .leftToRight
}
}
@IBOutlet weak var rightToLeft: PipeSlider! {
didSet {
rightToLeft.direction = .rightToLeft
}
}
@IBOutlet weak var topDown: PipeSlider! {
didSet {
topDown.direction = .topDown
}
}
@IBOutlet weak var bottomUp: PipeSlider! {
didSet {
bottomUp.direction = .bottomUp
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 20.761905 | 58 | 0.563073 |
bba64cd691c4f3341a4b63e02b36f5963880e87d | 2,392 | //
// ViewController.swift
// ConcessionaryAppWithProtocols
//
// Created by fresneda on 1/17/19.
// Copyright © 2019 fresneda. All rights reserved.
//
import UIKit
class CatalogViewController: BaseViewController {
// MARK: - Outlets
@IBOutlet weak var sortButton: UIBarButtonItem!
@IBOutlet weak var carsTableView: UITableView!
// MARK: - Model
var viewModel: CatalogViewModel {
get{
return self.model as! CatalogViewModel
}
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel.initData()
self.setupView()
}
// MARK: - Setup
private func setupView() {
self.title = self.viewModel.catalogNavBarTitle
self.sortButton.title = self.viewModel.sortButtonTitle
self.setupTableView()
}
private func setupTableView() {
self.carsTableView.delegate = self
self.carsTableView.dataSource = self
self.carsTableView.tableFooterView = UIView()
self.carsTableView.reloadData()
}
// MARK: - Actions
@IBAction func sortList(_ action: Any){
self.sortButton.title = self.viewModel.sortButtonTitle
self.viewModel.toggleSortButton()
for (index, _) in self.viewModel.catalog.enumerated(){
self.carsTableView.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: UITableView.RowAnimation.left)
}
}
}
extension CatalogViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: - MANDATORY METHODS
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.catalog.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.viewModel.generateCell(for: indexPath)
}
// MARK: - OPTIONAL METHODS
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat.init(self.viewModel.cellHeight)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.model!.coordinator?.viewDetail(
_carData: self.viewModel.catalog[indexPath.row],
_brand: self.viewModel.brand
)
}
}
| 29.170732 | 124 | 0.647157 |
e8796c86dc1b0be88c751aa5968b1fb1ef1a15f2 | 5,402 | //
// NacaFileLines.swift
// App
//
// Created by Ben Schultz on 3/23/20.
//
import Foundation
import Vapor
class NachaRecord: FixedLengthField {
init(from string: String, type paramType: Int, validations: [FieldParseValidation]) throws {
super.init("", size: 94)
let typeFromString = Int(string.prefix(1))
guard paramType == typeFromString else {
throw Abort(.badRequest, reason: "Parse error on \(string). Call to NACHA type \(paramType) parser, but first character is \(String(describing: typeFromString)).")
}
guard string.lengthOfBytes(using: .ascii) == 94 else {
throw Abort(.badRequest, reason: "Parse error on \(text). String is not equal to 94 characters.")
}
// test to make sure record is valid (numerics are all numeric, etc.)
for validation in validations {
let testStr = String(string[validation.lowerBound...validation.upperBound])
let testResult = validation.routine(testStr, validation.compValue)
switch testResult {
case .error(let reason):
throw Abort(.badRequest, reason: "Parse error on \(text).\nPosition \(validation.lowerBound + 1) to \(validation.upperBound + 1)\n\(reason)")
case .success:
break
}
}
self.text = string
} // end init
required init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let string = try container.decode(String.self)
guard string.count == 94 else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "NACHA record must be 94 characters")
}
super.init(string, size: 94)
}
}
class NachaType1: NachaRecord {
init(from string: String) throws {
var validations = [FieldParseValidation]()
validations.append(FieldParseValidation(lowerBound: 1, upperBound: 2, routine: FieldParseValidation.isConstant, compValue: "01"))
validations.append(FieldParseValidation(lowerBound: 3, upperBound: 3, routine: FieldParseValidation.isConstant, compValue: " "))
validations.append(FieldParseValidation(lowerBound: 4, upperBound: 12, routine: FieldParseValidation.isNumeric, compValue: nil))
try super.init(from: string, type: 1, validations: validations)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
class NachaType9: NachaRecord {
init(from string: String) throws {
var tmpstr = string
let len = string.lengthOfBytes(using: .ascii)
if len < 94 {
let addSpaces = String(repeating: " ", count: 94 - len)
tmpstr = tmpstr + addSpaces
}
let validations = [FieldParseValidation]()
try super.init(from: tmpstr, type: 9, validations: validations)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
class NachaType5: NachaRecord {
init(from string: String) throws {
let validations = [FieldParseValidation]()
try super.init(from: string, type: 5, validations: validations)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
class NachaType8: NachaRecord {
var aeCount: Int? { return val(from: 4, to: 9) }
var hash: Int? { return val(from: 10, to: 19) }
var debitAmount: Double? { return val(from: 20, to: 31) }
var creditAmount: Double? { return val(from: 32, to: 43) }
init(from string: String) throws {
let validations = [FieldParseValidation]()
try super.init(from: string, type: 8, validations: validations)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
class NachaType6: NachaRecord {
var uuid = UUID()
var aba: String? { return val(from: 3, to: 11) }
var accountNumber: String? { return val(from: 12, to: 28) }
var amount: Double? { return val(from: 29, to: 38) }
var idNumber: String? { return val(from: 39, to: 53 ) }
var name: String? { return val(from: 54, to: 75) }
var hash: Int? { return val(from: 3, to: 10) }
var isDebit: Bool {
let type: String? = val(from: 1, to: 2)
return type == "27"
}
init(from string: String) throws {
let validations = [FieldParseValidation]()
try super.init(from: string, type: 6, validations: validations)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
class NachaType7: NachaRecord {
var hash: Int? { return val(from: 4, to: 11) }
init(from string: String) throws {
let validations = [FieldParseValidation]()
try super.init(from: string, type: 7, validations: validations)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
class NachaFilePadding: NachaRecord {
init() throws {
let line = String(repeating: "9", count: 94)
try super.init(from: line, type: 9, validations: [FieldParseValidation]())
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
| 31.964497 | 176 | 0.614957 |
113b4d6da72b121a4f65979da992ad3a373d09cc | 2,343 | //
// SILGATT5_6TestCase.swift
// BlueGecko
//
// Created by Kamil Czajka on 25.3.2021.
// Copyright © 2021 SiliconLabs. All rights reserved.
//
import Foundation
class SILGATT5_6TestCase: SILTestCase {
var testID: String = "5.6"
var testName: String = "BLE Characteristics Types Test case"
var testResult: SILObservable<SILTestResult?> = SILObservable(initialValue: nil)
var observableTokens: [SILObservableToken?] = []
private var disposeBag = SILObservableTokenBag()
private lazy var userLenCharacteristicTestHelper = SILIOPUserLenCharacteristicTestHelper(testCase: self,
testedCharacteristicUUID: iopTestCharacteristicTypesRWUserLen1,
exceptedValue: ExceptedValue,
count: 1)
private var iopTestCharacteristicTypesRWUserLen1 = SILIOPPeripheral.SILIOPTestCharacteristicTypes.IOPTestChar_RWUserLen1.cbUUID
private let ExceptedValue = "0x55"
init() { }
func injectParameters(parameters: Dictionary<String, Any>) {
userLenCharacteristicTestHelper.injectParameters(parameters: parameters)
}
func performTestCase() {
weak var weakSelf = self
let userLenCharacteristicTestHelperSubscription = userLenCharacteristicTestHelper.testResult.observe( { testResult in
guard let weakSelf = weakSelf else { return }
guard let testResult = testResult else { return }
weakSelf.userLenCharacteristicTestHelper.invalidateObservableTokens()
weakSelf.publishTestResult(passed: testResult.passed, description: testResult.description)
})
disposeBag.add(token: userLenCharacteristicTestHelperSubscription)
observableTokens.append(userLenCharacteristicTestHelperSubscription)
publishStartTestEvent()
userLenCharacteristicTestHelper.performTestCase()
}
func getTestArtifacts() -> Dictionary<String, Any> {
return [:]
}
func stopTesting() {
userLenCharacteristicTestHelper.invalidateObservableTokens()
invalidateObservableTokens()
}
}
| 40.396552 | 156 | 0.644473 |
e551253ef76003889ea9e85896fe28b540ef186d | 1,158 | //
// VerticalCollectionViewDelegate.swift
// ScrollStackKitDemo
//
// Created by Marco Del Giudice on 08/10/21.
//
import UIKit
class VerticalCollectionViewDelegate: NSObject, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private let itemsPerRow: CGFloat = 1
private let sectionInsets = UIEdgeInsets(top: 8, left: 24, bottom: 16, right: 24)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * 2
let widthPerItem = (UIScreen.main.bounds.width - paddingSpace) / itemsPerRow
return CGSize(width: widthPerItem, height: 200)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
}
| 38.6 | 170 | 0.75475 |
76ca80fb128c8f294b2e904d9eaae6e336af841c | 225 | //
// RecordCoordinatorType.swift
// PixelTest
//
// Created by Kane Cheshire on 16/10/2019.
//
import UIKit
protocol RecordCoordinatorType {
func record(_ view: UIView, config: Config) throws -> UIImage
}
| 15 | 65 | 0.675556 |
ede39dc9af71f6f3cca859863826223af243fb6a | 3,655 | /// Copyright (c) 2018 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
//Realm Platform은 Realm Database를 사용하는 응용 프로그램을 위한 다중 플랫폼 데이터 동기화 솔루션을
//제공하는 서버 소프트웨어이다. 앱에서 Realm 데이터베이스를 사용하는 경우 몇 줄의 코드로 서버에 연결하여
//앱을 실행하는 모든 기기에서 실시간 데이터를 전송할 수 있다. p.255
//유사한 솔루션에 비해 Realm Platform의 장점은 다음과 같다.
//• 자동 데이터 동기화 : Realm은 서버 연결을 유지 관리하고, 필요에 따라 모든 데이터 변경 사항을 동기화한다.
//• 실시간 양방향 동기화 : Realm은 로컬 변경 사항을 클라우드로 전송하는 것 이상의 역할을 한다.
// 또한, 모든 장치 및 플랫폼에서 모든 변경 사항을 동기화한다.
//• 데이터 변환 없음 : JSON, Codable 혹은 다른 데이터 변환을 사용하지 않아도 된다. Realm API에서 가져올 때
// 동기화된 데이터를 서버에서 원활하게 가져올 수 있다.
//• 충돌 없음 : End-to-End 데이터 인프라로 Realm이 동기화 충돌을 피하도록 신경쓴다/
//• 다중 플랫폼 실시간 동기화 : iPhone, Android, tvOS, macOS등 응용 프로그램을 동일한 서버 인스턴스에 연결할 수 있으며
// 사용자는이 플랫폼에서 모든 장치에 대한 데이터를 즉시 가져올 수 있다.
//• 자체 호스팅 또는 PaaS : 이미 호스팅 된 Realm Cloud에 연결하여 시작하거나, 자체 인프라에서 Realm Platform을
// 자체 호스팅하고, 사내 데이터에 대한 모든 액세스 권한을 가질 수 있다.
//https://cloud.realm.io
//인스턴스에서 사용하지 않는 인증 방법은 비활성화 시키는 것이 좋다.
//Realm Studio와, Realm Flatform을 같이 사용한다.
//• Admin users : 서버의 모든 파일에 액세스하고 수정할 수 있다.
//• Regular users: : 개인 사용자 폴더에서 파일을 생성, 액세스 및 수정할 수 있다.
// 또한 다른 사용자가 공유 파일을 공동 작업하도록 초대 할 수 있다.
// 이 사용자는 nobody 사용자가 소유 한 파일에 액세스 할 수도 있다.
//여기서는 Regular로 생성한 chatuser 사용자로 인스턴스에 연결하고 공유 DB의 데이터를 동기화한다.
//Accessing synced data
//서버에서 동기화된 Realm을 여는 두 가지 방법이 있다.
//• 서버에서 전체 DB를 동기화한다. : 단순히 서버에서 Realm을 복제하고 클라이언트와 동기화하는 것.
// 일반적으로 비효율적이기에 자주 사용하지는 않는다.
//• 해당 데이터가 응용 프로그램에 필요할 때만 Realm DB의 일부를 실시간으로 동기화한다. : 부분 동기화
// 주로 사용하게 되는 방법이다.
//Local notification subscription
//Realm notification을 사용해서 UI를 업데이트 할 수 있다. p.261
//Remote sync subscription
//서버 동기화는 Local notification과 매우 유사하게 작동한다. p.262
//SyncSubscription<Object>로 구독이 활성화되어 있는 동안 레코드에 대한 모든 변경 사항이 서버에서 동기화된다.
//구독을 취소하면, 즉시 로컬에 캐시된 데이터가 삭제된다.
//로컬에서 서버의 Realm에 쿼리하여 일치하는 모든 객체를 가져와 로컬 Realm에 저장한다. 서버나 Realm Cloud에 연결된
//다른 클라이언트에서 새 사용자를 추가한 경우, 변경 사항이 로컬 DB에 반영되어 변경 사항 알림이 전송된다.
//앱의 전체적인 로직은 p.263
//Chat - ChatRoom - ChatItem의 구조이다.
| 44.036145 | 83 | 0.729685 |
287bbef859671ead231ebf582bc664e06dd104e5 | 7,385 | //
// Pool.swift
// LittlinkRouterPerfect
//
// Created by Brent Royal-Gordon on 10/27/16.
//
//
import Dispatch
/// Errors emitted by a Pool.
public enum PoolError: Error {
/// Attempting to `retrieve()` an unused `Resource` took longer than the
/// `timeout`.
case timedOut
}
/// A shared pool of `Resource` which can be added to and removed from in a
/// threadsafe fashion.
///
/// To use a `Pool`, initialize it with a `maximum` number of `Resources` to
/// manage, a `timeout` indicating the maximum time it should wait for a
/// `Resource` to be relinquished if all of them are in use, and a `constructor`
/// which creates a new `Resource`.
///
/// A `Pool` can manage any kind of object, but it's included in this module to
/// support `SQLConnection` pools. When managing a pool of `SQLConnection`s, you
/// can use a special constructor which creates connections from a provided
/// `SQLDatabase`.
///
/// Once the `Pool` has been created, you use the `retrieve()` method to get an
/// object from the pool, and the `relinquish(_:)` method to return it to the pool.
/// Alternatively, use `discard(_:)` to indicate that the object should be destroyed
/// and a new one created; this is useful when the object is in an unknown state.
/// If you want to wrap up all these calls into one mistake-resistant method, use
/// the `withOne(do:)` method.
//
// FIXME: I actually have little experience with these primitives, particularly
// semaphores. Review by someone who knows more about them than I do would be
// welcome.
public final class Pool<Resource: AnyObject> {
private let constructor: () throws -> Resource
private let timeout: DispatchTimeInterval
private let counter: DispatchSemaphore
private var resourceIsAvailable: [ByIdentity<Resource>: Bool] = [:]
private let queue = DispatchQueue(label: "ConnectionPool.queue")
/// Creates a `Pool`. The pool is initially empty, but it may eventually contain
/// up to `maximum` objects.
///
/// - Parameter maximum: The maximum number of `Resource` objects in the pool.
///
/// - Parameter timeout: Indicates the maximum time to wait when there are
/// `maximum` objects in the pool and none of them have been
/// relinquished.
///
/// - Parameter constructor: A function which can create a new `Resource`.
/// Automatically called when someone tries to `retrieve()` an
/// existing `Resource` and there aren't any, but the `maximum`
/// has not been reached.
public init(maximum: Int = 10, timeout: DispatchTimeInterval = .seconds(10), constructor: @escaping () throws -> Resource) {
self.constructor = constructor
self.counter = DispatchSemaphore(value: maximum)
self.timeout = timeout
}
/// Retrieves a currently unused `Resource` from the `Pool`, marking it as
/// used until it's passed to `relinquish(_:)`.
///
/// - Throws: `PoolError.timedOut` if there are none available and none are
/// relinquished within `timeout`, or any error thrown by `constructor`.
///
/// - Note: This call is synchronized so that it is safe to call from any thread
/// or queue.
public func retrieve() throws -> Resource {
func isAvailable(_: ByIdentity<Resource>, available: Bool) -> Bool {
return available
}
guard counter.wait(timeout: .now() + timeout) != .timedOut else {
throw PoolError.timedOut
}
return try queue.sync {
if let index = resourceIsAvailable.index(where: isAvailable) {
let resource = resourceIsAvailable[index].key.object
resourceIsAvailable[resource] = false
return resource
}
let newResource = try constructor()
resourceIsAvailable[newResource] = false
return newResource
}
}
private func resetAvailability(of resource: Resource, to available: Bool?) {
queue.sync {
precondition(resourceIsAvailable[resource] == false)
resourceIsAvailable[resource] = available
counter.signal()
}
}
/// Returns `resource` to the `Pool` to be reused.
///
/// - Parameter resource: The resource to relinquish. It may be returned by a
/// future call to `retrieve()`.
///
/// - Precondition: `resource` was returned by a prior call to `retrieve()`.
///
/// - Note: This call is synchronized so that it is safe to call from any thread
/// or queue.
public func relinquish(_ resource: Resource) {
resetAvailability(of: resource, to: true)
}
/// Frees up `resource`'s slot in the pool. `resource` itself will never be
/// reused, but a new instance of `Resource` may be allocated in its place.
///
/// This is useful when `resource` may be in an inconsistent state, such as
/// when an error occurs.
///
/// - Parameter resource: The resource to discard. It will not be returned by
/// any future call to `retrieve()`.
///
/// - Precondition: `resource` was returned by a prior call to `retrieve()`.
///
/// - Note: This call is synchronized so that it is safe to call from any thread
/// or queue.
public func discard(_ resource: Resource) {
resetAvailability(of: resource, to: nil)
}
/// Calls `fn` with a newly-`retrieve()`d `Resource`, then `relinquish(_:)`es
/// or `discard(_:)`s the resource as appropriate.
///
/// The resource is `relinquish(_:)`ed if `fn` returns successfully, or
/// `discard(_:)`ed if `fn` throws.
///
/// - Parameter fn: The function to run with the `Resource`.
///
/// - Returns: The return value of `fn`.
///
/// - Throws: If `retrieve()` or `fn` throw.
public func withOne<R>(do fn: (Resource) throws -> R) throws -> R {
let resource = try retrieve()
do {
let ret = try fn(resource)
relinquish(resource)
return ret
}
catch {
discard(resource)
throw error
}
}
}
// WORKAROUND: #2 Swift doesn't support same-type requirements on generics
private protocol _ByIdentityProtocol: Hashable {
associatedtype Object: AnyObject
init(_ object: Object)
}
private struct ByIdentity<Object: AnyObject> {
let object: Object
init(_ object: Object) {
self.object = object
}
}
// WORKAROUND: #2 Swift doesn't support same-type requirements on generics
extension ByIdentity: Hashable, _ByIdentityProtocol {
static func == (lhs: ByIdentity, rhs: ByIdentity) -> Bool {
return ObjectIdentifier(lhs.object) == ObjectIdentifier(rhs.object)
}
var hashValue: Int {
return ObjectIdentifier(object).hashValue
}
}
// WORKAROUND: #2 Swift doesn't support same-type requirements on generics
extension Dictionary where Key: _ByIdentityProtocol {
subscript(key: Key.Object) -> Value? {
get {
return self[Key(key)]
}
set {
self[Key(key)] = newValue
}
}
}
| 37.48731 | 128 | 0.616791 |
6a8d8034b7938ca58b3a91c8450486f5d30fa523 | 880 | //
// artTests.swift
// artTests
//
// Created by Itamar Marom on 07/05/2021.
//
import XCTest
@testable import art
class artTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.882353 | 111 | 0.656818 |
fe10cb4598e4a57adb4d43beed4a1b7e85881a7f | 680 | //
// uselsee.swift
// DKSwift
//
// Created by 邓凯 on 2020/3/25.
// Copyright © 2020 邓凯. All rights reserved.
//
import Foundation
import HandyJSON
class CABaseViewController: DKBaseViewController {}
class BangDingView: UIView {}
class XiuGaiView: UIView {}
class GoldBuZu: UIView {}
//class BangDingView: UIView {}
//class BangDingView: UIView {}
protocol BaseP {
func pMeth()
}
class confirmP: BaseP {
func pMeth() {
}
}
class BaseC<Type> where Type: BaseP {
func cMeth() -> Type {
let a = confirmP()
return a as! Type
}
}
//extension BaseC: BaseP {
//
//
//}
func test() {
let dic: [String: BaseC<confirmP>] = [:]
}
| 15.111111 | 51 | 0.622059 |
0eadd3ae27da15d3594f8c573c3795c9e0369af8 | 3,439 | //
// ContentView.swift
// generator
//
// Created by Vlad Z. on 7/14/20.
//
import SwiftUI
import CoreGraphics
struct ContentView: View {
@Binding
var image: NSImage?
@State
var isHovering: Bool
var body: some View {
VStack(spacing: 15) {
VStack {
Text("PNG, JPG, JPEG, HEIC")
Button(action: selectFile) {
Text("From Finder")
}
}
InputImageView(image: self.$image)
.onHover { hovering in
isHovering = hovering
}
.background(isHovering ? Color.gray : Color.black)
.cornerRadius(8)
.onTapGesture { selectFile() }
}.padding(.all, 20)
}
private func selectFile() {
NSOpenPanel.openImage { (result) in
if case let .success(image) = result {
self.image = image
}
}
}
init() {
self._image = .constant(nil)
self._isHovering = .init(initialValue: false)
}
}
struct InputImageView: View {
@Binding var image: NSImage?
var body: some View {
ZStack {
if self.image != nil {
Image(nsImage: self.image!)
.resizable()
.aspectRatio(contentMode: .fit)
} else {
Text("Drag and drop image file")
.frame(width: 320)
}
}
.frame(height: 320)
.onDrop(of: ["public.url","public.file-url"], isTargeted: nil) { (items) -> Bool in
if let item = items.first {
if let identifier = item.registeredTypeIdentifiers.first {
print("onDrop with identifier = \(identifier)")
if identifier == "public.url" || identifier == "public.file-url" {
item.loadItem(forTypeIdentifier: identifier, options: nil) { (urlData, error) in
DispatchQueue.main.async {
if let urlData = urlData as? Data {
let urll = NSURL(absoluteURLWithDataRepresentation: urlData, relativeTo: nil) as URL
if let img = NSImage(contentsOf: urll) {
self.image = img
guard img.size.height < 80,
img.size.width < 80 else { return }
let imageRef = img.cgImage(forProposedRect: nil, context: nil, hints: nil)
let bitmap = Bitmap(from: imageRef!)
(0..<bitmap.width).forEach { i in
(0..<bitmap.height).forEach { j in
let nanogramCheck = bitmap[i, j].alpha != 0
print("[\(i); \(j)]: \(nanogramCheck)")
}
}
}
}
}
}
}
}
return true
} else {
print("item not here")
return false }
}
}
}
| 34.049505 | 120 | 0.409712 |
763d7191919e7150f14abfd654187d01edae734e | 297 | //
// ViewModelType.swift
// MVVMPureObservables
//
// Created by krawiecp-home on 25/01/2019.
// Copyright © 2019 tailec. All rights reserved.
//
import Foundation
protocol ViewModelType {
associatedtype Input
associatedtype Output
func transform(input: Input) -> Output
}
| 17.470588 | 49 | 0.703704 |
014f0020de02a7abe99f881a1331417b17b65de1 | 475 | //
// ShellCommand.swift
//
//
// Created by lzh on 2021/9/18.
//
struct ShellCommand {
static func gitPush(filePath: String, message: String) throws {
try Shell.run("git pull")
try Shell.run("git add \(filePath)")
try Shell.run("git commit -m '\(message)'")
try Shell.run("git push")
}
static func git(tag: String) throws {
try Shell.run("git tag \(tag)")
try Shell.run("git push origin \(tag)")
}
}
| 22.619048 | 67 | 0.568421 |
293063578a10f9a3553358f80472be038d682273 | 2,418 | /***************************************************************************
* Copyright 2014-2016 SPECURE GmbH
* Copyright 2016-2017 alladin-IT GmbH
*
* 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
///
struct RTPResult {
///
var jitterMap: [UInt16: Double]
///
var receivedPackets: UInt16
///
var maxJitter: Int64
///
var meanJitter: Int64
///
var skew: Int64
///
var maxDelta: Int64
///
var outOfOrder: UInt16
///
var minSequential: UInt16
///
var maxSequential: UInt16
//
///
init() {
jitterMap = [UInt16: Double]()
receivedPackets = 0
maxJitter = 0
meanJitter = 0
skew = 0
maxDelta = 0
outOfOrder = 0
minSequential = 0
maxSequential = 0
}
///
init(jitterMap: [UInt16: Double], maxJitter: Int64, meanJitter: Int64, skew: Int64, maxDelta: Int64, outOfOrder: UInt16, minSequential: UInt16, maxSequential: UInt16) {
self.jitterMap = jitterMap
self.receivedPackets = UInt16(jitterMap.count)
self.maxJitter = maxJitter
self.meanJitter = meanJitter
self.skew = skew
self.maxDelta = maxDelta
self.outOfOrder = outOfOrder
self.minSequential = (minSequential > receivedPackets) ? receivedPackets : minSequential
self.maxSequential = (maxSequential > receivedPackets) ? receivedPackets : maxSequential
}
}
///
extension RTPResult: CustomStringConvertible {
///
var description: String {
return "RTPResult: [jitterMap: \(jitterMap), maxJitter: \(maxJitter), meanJitter: \(meanJitter), " +
"skew: \(skew), maxDelta: \(maxDelta), outOfOrder: \(outOfOrder), minSequential: \(minSequential), maxSequential: \(maxSequential)]"
}
}
| 27.477273 | 172 | 0.604218 |
fec51b6594acdbb6b0863bcbe9de40fc4d69ecce | 1,257 | //
// SwiftyTimer.swift
// WHCWSIFT
//
// Created by Haochen Wang on 9/24/17.
// Copyright © 2017 Haochen Wang. All rights reserved.
//
import Foundation
public extension Timer
{
@discardableResult
final class func after(_ interval: TimeInterval, _ wrapper: ClosureWrapper<Timer>) -> Timer
{
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, 0, 0, 0) {_ in
if let block = wrapper.closure
{
block(timer)
}
}
return timer
}
@discardableResult
final class func every(_ interval: TimeInterval, _ wrapper: ClosureWrapper<Timer>) -> Timer
{
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
if let block = wrapper.closure
{
block(timer)
}
}
return timer
}
final func start(runLoop: RunLoop = .current, modes: [RunLoop.Mode] = [RunLoop.Mode.default])
{
for (_, mode) in modes.enumerated().reversed()
{
runLoop.add(self, forMode: mode)
}
}
}
| 26.744681 | 130 | 0.590294 |
d7aae9228908d4b0c2135fed846e9f8661ff3f0e | 8,759 | //: Blocks are a data storage abstraction. We support Float, Double (real and complex) and Int blocks.
//: Complex blocks are structures made up of two real Blocks. This is a split storage format.
//: Real blocks are classes to allow for deinit and ARC to free memory.
import Foundation
import Accelerate
//: Data types; for this implementation everything is done dynamically
public enum BlockTypes: String {
case f, cf, d, cd, i, ui
}
//: a class to handle creation and deinit for Views of type Double
fileprivate class DataDouble: NSObject {
let dta: UnsafeRawPointer
let length: Int
let derived: Bool
init(length: Int){
self.length = length
self.derived = false
let dta = UnsafeMutablePointer<Double>.allocate(capacity: length)
dta.initialize(repeating: 0.0, count: length )
self.dta = UnsafeRawPointer(dta)
}
init(data: UnsafeRawPointer, length: Int){
self.length = length
self.dta = data
self.derived = true
}
deinit {
if !self.derived {
let dta = UnsafeMutablePointer<Double>(mutating: self.dta.assumingMemoryBound(to: Double.self))
dta.deallocate()
}
}
}
//: a class to handle creation and deinit for Views of type Float
fileprivate class DataFloat: NSObject {
let dta: UnsafeRawPointer
let length: Int
let derived: Bool
init(length: Int){
self.length = length
self.derived = false
let dta = UnsafeMutablePointer<Float>.allocate(capacity: length)
dta.initialize(repeating: 0.0, count: length )
self.dta = UnsafeRawPointer(dta)
}
init(data: UnsafeRawPointer, length: Int){
self.length = length
self.dta = data
self.derived = true
}
deinit {
if !self.derived {
let dta = UnsafeMutablePointer<Float>(mutating: self.dta.assumingMemoryBound(to: Float.self))
dta.deallocate()
}
}
}
//: Accelerate uses UInt32 for indexing, offsets and length
fileprivate class DataUInt32: NSObject {
let dta: UnsafeRawPointer
let length: Int
let derived: Bool
init(length: Int){
self.length = length
self.derived = false
let dta = UnsafeMutablePointer<UInt32>.allocate(capacity: length)
dta.initialize(repeating: 0, count: length )
self.dta = UnsafeRawPointer(dta)
}
init(data: UnsafeRawPointer, length: Int){
self.length = length
self.dta = data
self.derived = true
}
deinit {
if !self.derived {
let dta = UnsafeMutablePointer<UInt32>(mutating: self.dta.assumingMemoryBound(to: UInt32.self))
dta.deallocate()
}
}
}
//: Accelerate uses Int32 for strides
fileprivate class DataInt32: NSObject {
let dta: UnsafeRawPointer
let length: Int
let derived: Bool
init(length: Int){
self.length = length
self.derived = false
let dta = UnsafeMutablePointer<Int32>.allocate(capacity: length)
dta.initialize(repeating: 0, count: length )
self.dta = UnsafeRawPointer(dta)
}
init(data: UnsafeRawPointer, length: Int){
self.length = length
self.dta = data
self.derived = true
}
deinit {
if !self.derived {
let dta = UnsafeMutablePointer<Int32>(mutating: self.dta.assumingMemoryBound(to: Int32.self))
dta.deallocate()
}
}
}
//: complex views are structures. They don't allocate any memory from the heap directly
fileprivate struct DataComplexDouble {
let dtaReal: DataDouble
let dtaImag: DataDouble
init(length: Int){
self.dtaReal = DataDouble(length: length)
self.dtaImag = DataDouble(length: length)
}
}
fileprivate struct DataComplexFloat {
let dtaReal: DataFloat
let dtaImag: DataFloat
init(length: Int){
self.dtaReal = DataFloat(length: length)
self.dtaImag = DataFloat(length: length)
}
}
//: Blocks are data raw data containers. The type is set at create.
public struct Block {
public let count: Int
public var dta: UnsafeRawPointer?
public var imagDta: UnsafeRawPointer?
public let type: BlockTypes
let derived: Bool
let dtaObj: Any //need to retain data object so ARC does not collect it
public init(length: Int, type: BlockTypes){
self.count = length
self.derived = false
switch type{
case .f:
let dta = DataFloat(length: length)
self.dtaObj = dta
self.dta = dta.dta
self.type = type
case .cf:
let dta = DataComplexFloat(length: length)
self.dtaObj = dta
self.dta = dta.dtaReal.dta
self.imagDta = dta.dtaImag.dta
self.type = type
case .d:
let dta = DataDouble(length: length)
self.dtaObj = dta
self.dta = dta.dta
self.type = type
case .cd:
let dta = DataComplexDouble(length: length)
self.dtaObj = dta
self.dta = dta.dtaReal.dta
self.imagDta = dta.dtaImag.dta
self.type = type
case .i:
let dta = DataInt32(length: length)
self.dtaObj = dta
self.dta = dta.dta
self.type = type
case .ui:
let dta = DataUInt32(length: length)
self.dtaObj = dta
self.dta = dta.dta
self.type = type
}
}
public subscript(index: Int) -> Scalar {
get {
switch self.type {
case .f:
let dta = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self))
return Scalar((dta! + index).pointee)
case .d:
let dta = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self))
return Scalar((dta! + index).pointee)
case .cf:
let dtaReal = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self))
let dtaImag = UnsafeMutablePointer<Float>(mutating: self.imagDta?.assumingMemoryBound(to: Float.self))
return Scalar(DSPComplex(real: (dtaReal! + index).pointee,
imag: (dtaImag! + index).pointee))
case .cd:
let dtaReal = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self))
let dtaImag = UnsafeMutablePointer<Double>(mutating: self.imagDta?.assumingMemoryBound(to: Double.self))
return Scalar(DSPDoubleComplex(real: (dtaReal! + index).pointee, imag: (dtaImag! + index).pointee))
case .i:
let dta = UnsafeMutablePointer<Int32>(mutating: self.dta?.assumingMemoryBound(to: Int32.self))
return Scalar((dta! + index).pointee)
case .ui:
let dta = UnsafeMutablePointer<UInt32>(mutating: self.dta?.assumingMemoryBound(to: UInt32.self))
return Scalar((dta! + index).pointee)
}
}
set(value) {
switch self.type {
case .f:
let dta = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self))
(dta! + index).pointee = value.realf
case .d:
let dta = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self))
(dta! + index).pointee = value.reald
case .cf:
let dtaReal = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self))
let dtaImag = UnsafeMutablePointer<Float>(mutating: self.imagDta?.assumingMemoryBound(to: Float.self))
(dtaReal! + index).pointee = value.realf
(dtaImag! + index).pointee = value.imagf
case .cd:
let dtaReal = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self))
let dtaImag = UnsafeMutablePointer<Double>(mutating: self.imagDta?.assumingMemoryBound(to: Double.self))
(dtaReal! + index).pointee = value.reald
(dtaImag! + index).pointee = value.imagd
case .i:
let dta = UnsafeMutablePointer<Int32>(mutating: self.dta?.assumingMemoryBound(to: Int32.self))
(dta! + index).pointee = value.int
case .ui:
let dta = UnsafeMutablePointer<UInt32>(mutating: self.dta?.assumingMemoryBound(to: UInt32.self))
(dta! + index).pointee = UInt32(value.int)
}
}
}
}
| 37.917749 | 120 | 0.601781 |
acaaec4f83a31d9b192011f66f58f80f98a38de5 | 3,042 | //
// NSObject+Ext.swift
// Ext
//
// Created by naijoug on 2021/1/28.
//
import Foundation
public extension ExtWrapper where Base: NSObject {
/**
Reference:
- https://stackoverflow.com/questions/24494784/get-class-name-of-object-as-string-in-swift
*/
var typeName: String { String(describing: type(of: base)) }
static var typeName: String { String(describing: Base.self) }
}
extension ExtWrapper where Base: NSObject {
/**
Reference :
- https://stackoverflow.com/questions/5339276/what-are-the-dangers-of-method-swizzling-in-objective-c
- https://stackoverflow.com/questions/39562887/how-to-implement-method-swizzling-swift-3-0
- https://nshipster.com/swift-objc-runtime/
*/
public static func swizzlingClassMethod(_ cls: AnyClass,
original originalSEL: Selector,
swizzled swizzledSEL: Selector) {
guard let originalMethod = class_getClassMethod(cls, originalSEL),
let swizzledMethod = class_getClassMethod(cls, swizzledSEL) else {
return
}
swizzlingMethod(cls,
originalSEL: originalSEL,
swizzledSEL: swizzledSEL,
originalMethod: originalMethod,
swizzledMethod: swizzledMethod)
}
public static func swizzlingInstanceMethod(_ cls: AnyClass,
original originalSEL: Selector,
swizzled swizzledSEL: Selector) {
guard let originalMethod = class_getInstanceMethod(cls, originalSEL),
let swizzledMethod = class_getInstanceMethod(cls, swizzledSEL) else {
return
}
swizzlingMethod(cls,
originalSEL: originalSEL,
swizzledSEL: swizzledSEL,
originalMethod: originalMethod,
swizzledMethod: swizzledMethod)
}
private static func swizzlingMethod(_ cls: AnyClass,
originalSEL: Selector,
swizzledSEL: Selector,
originalMethod: Method,
swizzledMethod: Method) {
let isAddSuccess = class_addMethod(cls,
originalSEL,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod))
guard isAddSuccess else {
method_exchangeImplementations(originalMethod, swizzledMethod)
return
}
class_replaceMethod(cls,
swizzledSEL,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod))
}
}
| 38.025 | 109 | 0.533859 |
d90c2298fc2f660963235ca75a2e5361906095ee | 1,265 | //
// 35SearchInsertPositionTests.swift
// AlgorithmTests
//
// Created by vchan on 2021/2/10.
//
import XCTest
@testable import Algorithm
class SearchInsertPositionTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let solution = Solution()
XCTAssert(solution.searchInsert([], 5) == 0)
XCTAssert(solution.searchInsert([1,3,5,6], 5) == 2)
XCTAssert(solution.searchInsert([1,3,5,6], 2) == 1)
XCTAssert(solution.searchInsert([1,3,5,6], 7) == 4)
XCTAssert(solution.searchInsert([1,3,5,6], 0) == 0)
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 30.119048 | 111 | 0.639526 |
03ed8baf8a7e43ec749e4cc49d2c0ba91a49a852 | 1,184 | /// A key/gamepad event.
public struct KeyEvent: InputEvent {
/// A flag that indicates if the event is a repeat caused by the user holding the key down.
public let isRepeat: Bool
/// The modifier keys that were pressed when the event occurred.
public let modifiers: KeyModifierSet
/// The code of the key related to the event.
///
/// This property represents a layout-independent key code (as opposed to the character it may
/// generate) that designates the key that has been pressed or released. It can be used to handle
/// keys based on their physical location on the keyboard rather than their semantic (e.g. to map
/// keys to a specific set of game inputs).
///
/// - Important: Do not use this property to determine character inputs.
public let code: Int
/// A symbolic, printable representation of the key ressed by the user.
///
/// The value of this property depends on the keyboard layout.
///
/// - Important: Do not use this property to determine character inputs.
public let symbol: String?
public unowned let firstResponder: InputResponder?
public let timestamp: Milliseconds
public var userData: [String: Any]?
}
| 34.823529 | 99 | 0.722128 |
f8cdd973fb1eba16ab99e014fa99a407b0bcfe1a | 2,173 | //
// AppDelegate.swift
// BBMetalImageDemo
//
// Created by Kaibo Lu on 4/1/19.
// Copyright © 2019 Kaibo Lu. All rights reserved.
//
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.
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.234043 | 285 | 0.754717 |
18998f65788bf4864a4ea8d6fc4572f7ce263219 | 4,377 | //
// recordScreen2.swift
// App - CS
//
// Created by Justin Semelhago & Hassaan Inayatali on 4/3/18.
// Copyright © 2018 Justin Semelhago & Hassaan Inayatali. All rights reserved.
//
import UIKit
import AVFoundation
var counter1 = 0
var soundPlayer1 : AVAudioPlayer!
class recordScreen2: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if (counter1 == 0){
setupRecorder()
playBtn2.isEnabled = false
}
let url = getFileURL()
do{
soundPlayer1 = try AVAudioPlayer(contentsOf : url as URL)
}catch{
print(error)
}
if (soundPlayer1 == nil){
playBtn2.isEnabled = false
}
counter1 += 1
}
var fileName1 = "audioFile1.aac"
var soundRecorder : AVAudioRecorder!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var recordBtn2: UIButton!
@IBOutlet weak var playBtn2: UIButton!
@IBOutlet weak var nextBtn2: UIButton!
func setupRecorder(){
let recordSettings = [ AVFormatIDKey : kAudioFormatMPEG4AAC, AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue, AVEncoderBitRateKey : 320000, AVNumberOfChannelsKey : 2, AVSampleRateKey : 44100.0 ] as [String : Any]
let _ : NSError?
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
}catch{
print(error)
}
let url1 = getFileURL()
do{
soundRecorder = try AVAudioRecorder(url : url1 as URL, settings : recordSettings)
}catch{
print("Something went wrong")
}
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
func getCacheDirectory() -> URL{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
open func getFileURL() -> NSURL{
let pathURL = getCacheDirectory().appendingPathComponent(fileName1)
let pathString = pathURL.path
let filePath = NSURL(fileURLWithPath : pathString)
return filePath
}
@IBAction func record2(_ sender: UIButton) {
if sender.titleLabel?.text == "Record"{
setupRecorder()
soundRecorder.deleteRecording()
soundRecorder.record()
sender.setTitle("Stop", for : .normal)
playBtn2.isEnabled = false
nextBtn2.isEnabled = false
}else{
soundRecorder.stop()
sender.setTitle("Record", for : .normal)
playBtn2.isEnabled = false
}
}
@IBAction func playSound2(_ sender: UIButton) {
if sender.titleLabel?.text == "Play"{
recordBtn2.isEnabled = false
nextBtn2.isEnabled = false
sender.setTitle("Stop", for : .normal)
preparePlayer()
soundPlayer1.play()
}else{
soundPlayer1.stop()
sender.setTitle("Play", for : .normal)
}
}
func preparePlayer(){
let _ : NSError?
let url = getFileURL()
do{
soundPlayer1 = try AVAudioPlayer(contentsOf : url as URL)
}catch{
print(error)
}
soundPlayer1.delegate = self
soundPlayer1.prepareToPlay()
soundPlayer1.volume = 10.0
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
playBtn2.isEnabled = true
nextBtn2.isEnabled = true
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordBtn2.isEnabled = true
nextBtn2.isEnabled = true
playBtn2.setTitle("Play", for : .normal)
}
/*
// 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.
}
*/
}
| 30.823944 | 227 | 0.609093 |
217cb6de3f70debb4f6c7a6ce646da7d23409b54 | 2,900 | //
// MasterViewController.swift
// TableViews
//
// Created by Brandon Lee on 8/14/15.
// Copyright (c) 2015 Brandon Lee. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
let fruits = ["Apples", "Bananas", "Oranges", "Pineapples", "Watermelons", "Strawberries", "Raspberries", "Grapes", "Pomegranates", "Peaches", "Cherries", "Dates"]
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let fruit = fruits[indexPath.row]
(segue.destinationViewController as! DetailViewController).detailItem = fruit
}
}
}
/* HIGH LEVEL OVERVIEW
* Tableviews are instances of the UITableView controller class. UITableViewController conforms to UITableView
* data source protocol, which helps the tableview controller construct the view, by communicating with the app's data model.
* The protocol has two required methods, one that helps the tableview determine how many rows to create, which
* it does by querying the data model for its size. And a second that creates a cell for a particular row, supplies
* the relevant information from the data model, and then adds it to the row. The tableview knows what info pertains
* to which row by using an IndexPath. An IndexPath associated with the tableview stores indexes for specific sections
* and rows in the tableview. The tableview then uses this IndexPath to retrieve data from the data model and populate
* the view.
*/
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let fruit = fruits[indexPath.row]
cell.textLabel!.text = fruit
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
}
| 37.662338 | 167 | 0.69069 |
fc4bba897ee1457287acacaadc5a1b4390d151c3 | 10,863 | import Foundation
import HttpPipeline
import Prelude
func privacyPolicyMiddleware(
_ conn: Conn<StatusLineOpen, Void>
) -> IO<Conn<ResponseEnded, Data>> {
conn
|> writeStatus(.ok)
>=> respond(
text: #"""
Privacy Policy & Terms
======================
Personal identification information
-----------------------------------
We collect device ID of registered Users. None of this information is sold or provided to third parties, except to provide the products and services you’ve requested, with your permission, or as required by law.
Non-personal identification information
---------------------------------------
We may collect non-personal identification information about Users whenever they interact with the App, This may include: the type of device, the operating system, and other similar information.
How we use collected information
--------------------------------
Point-Free, Inc. collects and uses Users personal information for the following purposes:
1. To personalize user experience: to understand how our Users as a group use the App.
2. To improve our App.
3. To improve customer service.
4. To process transactions: We may use the information Users provide about themselves when placing an order only to provide service to that order. We do not share this information with outside parties except to the extent necessary to provide the service.
5. To send periodic push notifications: The push tokens Users provide for order processing, will only be used to send them information and updates pertaining to their activity.
How we protect your information
-------------------------------
We adopt appropriate data collection, storage and processing practices and security measures to protect against unauthorized access, alteration, disclosure or destruction of your personal information, username, password, transaction information and data stored on our Site.
Sensitive and private data exchange between the Site and its Users happens over a SSL secured communication channel and is encrypted and protected with digital signatures.
Sharing your personal information
---------------------------------
We do not sell, trade, or rent Users’ personal identification information to others.
Compliance with children’s online privacy protection act
--------------------------------------------------------
Protecting the privacy of the very young is especially important. For that reason, we never collect or maintain information at our Site from those we actually know are under 13, and no part of our website is structured to attract anyone under 13.
Changes to this privacy policy
------------------------------
Point-Free, Inc. has the discretion to update this privacy policy at any time. When we do, we will revise the updated date at the bottom of this page.
Contacting us
-------------
Questions about this policy can be sent to [email protected].
This document was last updated on March 9, 2021.
"""#)
}
//Privacy Policy
//
//Your privacy is important to us. It is Point-Free, Inc.’s policy to respect your privacy and comply with any applicable law and regulation regarding any personal information we may collect about you, including across our website, https://www.isowords.xyz, and other sites we own and operate.
//
//
//This policy is effective as of 10 March 2021 and was last updated on 10 March 2021.
//
//Information We Collect
//
//Information we collect includes both information you knowingly and actively provide us when using or participating in any of our services and promotions, and any information automatically sent by your devices in the course of accessing our products and services.
//
//Log Data
//
//When you visit our website, our servers may automatically log the standard data provided by your web browser. It may include your device’s Internet Protocol (IP) address, your browser type and version, the pages you visit, the time and date of your visit, the time spent on each page, other details about your visit, and technical details that occur in conjunction with any errors you may encounter.
//
//
//Please be aware that while this information may not be personally identifying by itself, it may be possible to combine it with other data to personally identify individual persons.
//
//Personal Information
//
//We may ask for personal information which may include one or more of the following:
//
//
//Name
//
//Legitimate Reasons for Processing Your Personal Information
//
//We only collect and use your personal information when we have a legitimate reason for doing so. In which instance, we only collect personal information that is reasonably necessary to provide our services to you.
//
//Collection and Use of Information
//
//We may collect personal information from you when you do any of the following on our website:
//
//
//Use a mobile device or web browser to access our content
//Contact us via email, social media, or on any similar technologies
//When you mention us on social media
//
//
//We may collect, hold, use, and disclose information for the following purposes, and personal information will not be further processed in a manner that is incompatible with these purposes:
//
//
//Please be aware that we may combine information we collect about you with general information or research data we receive from other trusted sources.
//
//Security of Your Personal Information
//
//When we collect and process personal information, and while we retain this information, we will protect it within commercially acceptable means to prevent loss and theft, as well as unauthorized access, disclosure, copying, use, or modification.
//
//
//Although we will do our best to protect the personal information you provide to us, we advise that no method of electronic transmission or storage is 100% secure, and no one can guarantee absolute data security. We will comply with laws applicable to us in respect of any data breach.
//
//
//You are responsible for selecting any password and its overall security strength, ensuring the security of your own information within the bounds of our services.
//
//How Long We Keep Your Personal Information
//
//We keep your personal information only for as long as we need to. This time period may depend on what we are using your information for, in accordance with this privacy policy. If your personal information is no longer required, we will delete it or make it anonymous by removing all details that identify you.
//
//
//However, if necessary, we may retain your personal information for our compliance with a legal, accounting, or reporting obligation or for archiving purposes in the public interest, scientific, or historical research purposes or statistical purposes.
//
//Children’s Privacy
//
//We do not aim any of our products or services directly at children under the age of 13, and we do not knowingly collect personal information about children under 13.
//
//International Transfers of Personal Information
//
//The personal information we collect is stored and/or processed where we or our partners, affiliates, and third-party providers maintain facilities. Please be aware that the locations to which we store, process, or transfer your personal information may not have the same data protection laws as the country in which you initially provided the information. If we transfer your personal information to third parties in other countries: (i) we will perform those transfers in accordance with the requirements of applicable law; and (ii) we will protect the transferred personal information in accordance with this privacy policy.
//
//Your Rights and Controlling Your Personal Information
//
//You always retain the right to withhold personal information from us, with the understanding that your experience of our website may be affected. We will not discriminate against you for exercising any of your rights over your personal information. If you do provide us with personal information you understand that we will collect, hold, use and disclose it in accordance with this privacy policy. You retain the right to request details of any personal information we hold about you.
//
//
//If we receive personal information about you from a third party, we will protect it as set out in this privacy policy. If you are a third party providing personal information about somebody else, you represent and warrant that you have such person’s consent to provide the personal information to us.
//
//
//If you have previously agreed to us using your personal information for direct marketing purposes, you may change your mind at any time. We will provide you with the ability to unsubscribe from our email-database or opt out of communications. Please be aware we may need to request specific information from you to help us confirm your identity.
//
//
//If you believe that any information we hold about you is inaccurate, out of date, incomplete, irrelevant, or misleading, please contact us using the details provided in this privacy policy. We will take reasonable steps to correct any information found to be inaccurate, incomplete, misleading, or out of date.
//
//
//If you believe that we have breached a relevant data protection law and wish to make a complaint, please contact us using the details below and provide us with full details of the alleged breach. We will promptly investigate your complaint and respond to you, in writing, setting out the outcome of our investigation and the steps we will take to deal with your complaint. You also have the right to contact a regulatory body or data protection authority in relation to your complaint.
//
//Limits of Our Policy
//
//Our website may link to external sites that are not operated by us. Please be aware that we have no control over the content and policies of those sites, and cannot accept responsibility or liability for their respective privacy practices.
//
//Changes to This Policy
//
//At our discretion, we may change our privacy policy to reflect updates to our business processes, current acceptable practices, or legislative or regulatory changes. If we decide to change this privacy policy, we will post the changes here at the same link by which you are accessing this privacy policy.
//
//
//If required by law, we will get your permission or give you the opportunity to opt in to or opt out of, as applicable, any new uses of your personal information.
//
//Contact Us
//
//For any questions or concerns regarding your privacy, you may contact us using the following details:
//
//
//Michael Williams
//[email protected]
//
| 64.278107 | 628 | 0.751634 |
7a9a300591777250e51abf73dba14f795a790d38 | 2,562 | //
//===--- CommonList.swift - Defines the CommonList class ----------===//
//
// This source file is part of the SwiftCase open source project
//
// Created by wangfd on 2021/9/26.
// Copyright © 2021 SwiftCase. All rights reserved.
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See more information
//
//===----------------------------------------------------------------------===//
import Foundation
import SnapKit
import UIKit
class CommonListCell<ItemType>: UITableViewCell {
var item: ItemType?
override required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
protocol CommonListDelegate: AnyObject {
func didSelectItem<Item>(_ item: Item)
}
class CommonList<ItemType, CellType: CommonListCell<ItemType>>: UIView, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView
var items: [ItemType]! = [] {
didSet {
self.tableView.reloadData()
}
}
weak var delegate: CommonListDelegate?
override init(frame: CGRect) {
tableView = UITableView(frame: .zero, style: .plain)
super.init(frame: frame)
setupViews()
}
func setupViews() {
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
addSubview(tableView)
tableView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: CellType? = tableView.dequeueReusableCell(withIdentifier: "cellId") as? CellType
if cell == nil {
cell = CellType(style: .subtitle, reuseIdentifier: "cellId")
}
cell?.item = items[indexPath.row]
return cell!
}
func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.didSelectItem(items[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
}
| 29.448276 | 116 | 0.638564 |
90ecdafbd62fd44ce28cdfcad9dc9052089ff130 | 874 | //
// HRTests.swift
// HRTests
//
// Created by lipeng on 2018/11/29.
// Copyright © 2018 lipeng. All rights reserved.
//
import XCTest
@testable import HR
class HRTests: XCTestCase {
override func 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.
}
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.
}
}
}
| 24.971429 | 111 | 0.644165 |
d60aa8ccff590d296f81f7d631169db4abf6156d | 31,929 | import Foundation
import TSCBasic
import TuistCore
import TuistGraph
import TuistGraphTesting
import TuistSupport
import XCTest
@testable import TuistKit
@testable import TuistSupportTesting
final class ProjectEditorMapperTests: TuistUnitTestCase {
var subject: ProjectEditorMapper!
override func setUp() {
super.setUp()
system.swiftVersionStub = { "5.2" }
developerEnvironment.stubbedArchitecture = .arm64
subject = ProjectEditorMapper()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_edit_when_there_are_helpers_and_setup_and_config_and_dependencies_and_tasks() throws {
// Given
let sourceRootPath = try temporaryPath()
let projectManifestPaths = [sourceRootPath].map { $0.appending(component: "Project.swift") }
let configPath = sourceRootPath.appending(components: Constants.tuistDirectoryName, "Config.swift")
let dependenciesPath = sourceRootPath.appending(components: Constants.tuistDirectoryName, "Dependencies.swift")
let helperPaths = [sourceRootPath].map { $0.appending(component: "Project+Template.swift") }
let templates = [sourceRootPath].map { $0.appending(component: "template") }
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
let projectName = "Manifests"
let projectsGroup = ProjectGroup.group(name: projectName)
let tasksPaths = [
sourceRootPath.appending(component: "TaskOne.swift"),
sourceRootPath.appending(component: "TaskTwo.swift"),
]
// When
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: configPath,
dependenciesPath: dependenciesPath,
projectManifests: projectManifestPaths,
editablePluginManifests: [],
pluginProjectDescriptionHelpersModule: [],
helpers: helperPaths,
templates: templates,
tasks: tasksPaths,
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
let project = try XCTUnwrap(graph.projects.values.first)
let targets = graph.targets.values.lazy
.flatMap(\.values)
.sorted(by: { $0.name < $1.name })
// Then
XCTAssertEqual(graph.name, "TestManifests")
XCTAssertEqual(targets.count, 7)
XCTAssertEqual(project.targets.sorted { $0.name < $1.name }, targets)
// Generated Manifests target
let manifestsTarget = try XCTUnwrap(project.targets.first(where: { $0.name == sourceRootPath.basename + projectName }))
XCTAssertEqual(targets.last, manifestsTarget)
XCTAssertEqual(manifestsTarget.platform, .macOS)
XCTAssertEqual(manifestsTarget.product, .staticFramework)
XCTAssertEqual(manifestsTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(manifestsTarget.sources.map(\.path), projectManifestPaths)
XCTAssertEqual(manifestsTarget.filesGroup, projectsGroup)
XCTAssertEqual(manifestsTarget.dependencies, [.target(name: "ProjectDescriptionHelpers")])
// Generated Helpers target
let helpersTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "ProjectDescriptionHelpers" }))
XCTAssertTrue(targets.contains(helpersTarget))
XCTAssertEqual(helpersTarget.name, "ProjectDescriptionHelpers")
XCTAssertEqual(helpersTarget.platform, .macOS)
XCTAssertEqual(helpersTarget.product, .staticFramework)
XCTAssertEqual(helpersTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(helpersTarget.sources.map(\.path), helperPaths)
XCTAssertEqual(helpersTarget.filesGroup, projectsGroup)
XCTAssertEmpty(helpersTarget.dependencies)
// Generated Templates target
let templatesTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "Templates" }))
XCTAssertTrue(targets.contains(templatesTarget))
XCTAssertEqual(templatesTarget.name, "Templates")
XCTAssertEqual(templatesTarget.platform, .macOS)
XCTAssertEqual(templatesTarget.product, .staticFramework)
XCTAssertEqual(templatesTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(templatesTarget.sources.map(\.path), templates)
XCTAssertEqual(templatesTarget.filesGroup, projectsGroup)
XCTAssertEmpty(templatesTarget.dependencies)
// Generated Config target
let configTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "Config" }))
XCTAssertTrue(targets.contains(configTarget))
XCTAssertEqual(configTarget.name, "Config")
XCTAssertEqual(configTarget.platform, .macOS)
XCTAssertEqual(configTarget.product, .staticFramework)
XCTAssertEqual(configTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(configTarget.sources.map(\.path), [configPath])
XCTAssertEqual(configTarget.filesGroup, projectsGroup)
XCTAssertEmpty(configTarget.dependencies)
// Generated Dependencies target
let dependenciesTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "Dependencies" }))
XCTAssertTrue(targets.contains(dependenciesTarget))
XCTAssertEqual(dependenciesTarget.name, "Dependencies")
XCTAssertEqual(dependenciesTarget.platform, .macOS)
XCTAssertEqual(dependenciesTarget.product, .staticFramework)
XCTAssertEqual(
dependenciesTarget.settings,
expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory])
)
XCTAssertEqual(dependenciesTarget.sources.map(\.path), [dependenciesPath])
XCTAssertEqual(dependenciesTarget.filesGroup, projectsGroup)
XCTAssertEmpty(dependenciesTarget.dependencies)
// Generated TaskOne target
let taskOneTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "TaskOne" }))
XCTAssertTrue(targets.contains(taskOneTarget))
XCTAssertEqual(taskOneTarget.name, "TaskOne")
XCTAssertEqual(taskOneTarget.platform, .macOS)
XCTAssertEqual(taskOneTarget.product, .staticFramework)
XCTAssertEqual(taskOneTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(taskOneTarget.sources.map(\.path), [tasksPaths[0]])
XCTAssertEqual(taskOneTarget.filesGroup, projectsGroup)
XCTAssertEmpty(taskOneTarget.dependencies)
// Generated TaskTwo target
let taskTwoTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "TaskTwo" }))
XCTAssertTrue(targets.contains(taskTwoTarget))
XCTAssertEqual(taskTwoTarget.name, "TaskTwo")
XCTAssertEqual(taskTwoTarget.platform, .macOS)
XCTAssertEqual(taskTwoTarget.product, .staticFramework)
XCTAssertEqual(taskTwoTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(taskTwoTarget.sources.map(\.path), [tasksPaths[1]])
XCTAssertEqual(taskTwoTarget.filesGroup, projectsGroup)
XCTAssertEmpty(taskTwoTarget.dependencies)
// Generated Project
XCTAssertEqual(project.path, sourceRootPath.appending(component: projectName))
XCTAssertEqual(project.name, projectName)
XCTAssertEqual(project.settings, Settings(
base: [
"ONLY_ACTIVE_ARCH": "NO",
"EXCLUDED_ARCHS": "x86_64",
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
))
XCTAssertEqual(project.filesGroup, projectsGroup)
// Generated Scheme
XCTAssertEqual(project.schemes.count, 1)
let scheme = try XCTUnwrap(project.schemes.first)
XCTAssertEqual(scheme.name, projectName)
let buildAction = try XCTUnwrap(scheme.buildAction)
XCTAssertEqual(buildAction.targets.lazy.map(\.name).sorted(), targets.map(\.name))
let runAction = try XCTUnwrap(scheme.runAction)
XCTAssertEqual(runAction.filePath, tuistPath)
let generateArgument = "generate --path \(sourceRootPath)"
XCTAssertEqual(runAction.arguments, Arguments(launchArguments: [LaunchArgument(name: generateArgument, isEnabled: true)]))
}
func test_edit_when_there_are_no_helpers_and_no_setup_and_no_config_and_no_dependencies() throws {
// Given
let sourceRootPath = try temporaryPath()
let projectManifestPaths = [sourceRootPath].map { $0.appending(component: "Project.swift") }
let helperPaths: [AbsolutePath] = []
let templates: [AbsolutePath] = []
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
let projectName = "Manifests"
let projectsGroup = ProjectGroup.group(name: projectName)
// When
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: nil,
dependenciesPath: nil,
projectManifests: projectManifestPaths,
editablePluginManifests: [],
pluginProjectDescriptionHelpersModule: [],
helpers: helperPaths,
templates: templates,
tasks: [],
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
let project = try XCTUnwrap(graph.projects.values.first)
let targets = graph.targets.values.lazy
.flatMap(\.values)
.sorted(by: { $0.name < $1.name })
// Then
XCTAssertEqual(targets.count, 1)
XCTAssertEmpty(targets.flatMap(\.dependencies))
// Generated Manifests target
let manifestsTarget = try XCTUnwrap(project.targets.last(where: { $0.name == sourceRootPath.basename + projectName }))
XCTAssertEqual(manifestsTarget.platform, .macOS)
XCTAssertEqual(manifestsTarget.product, .staticFramework)
XCTAssertEqual(manifestsTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(manifestsTarget.sources.map(\.path), projectManifestPaths)
XCTAssertEqual(manifestsTarget.filesGroup, projectsGroup)
XCTAssertEmpty(manifestsTarget.dependencies)
// Generated Project
XCTAssertEqual(project.path, sourceRootPath.appending(component: projectName))
XCTAssertEqual(project.name, projectName)
XCTAssertEqual(project.settings, Settings(
base: [
"ONLY_ACTIVE_ARCH": "NO",
"EXCLUDED_ARCHS": "x86_64",
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
))
XCTAssertEqual(project.filesGroup, projectsGroup)
// Generated Scheme
XCTAssertEqual(project.schemes.count, 1)
let scheme = try XCTUnwrap(project.schemes.first)
XCTAssertEqual(scheme.name, projectName)
let buildAction = try XCTUnwrap(scheme.buildAction)
XCTAssertEqual(buildAction.targets.map(\.name), targets.map(\.name))
let runAction = try XCTUnwrap(scheme.runAction)
XCTAssertEqual(runAction.filePath, tuistPath)
let generateArgument = "generate --path \(sourceRootPath)"
XCTAssertEqual(runAction.arguments, Arguments(launchArguments: [LaunchArgument(name: generateArgument, isEnabled: true)]))
}
func test_tuist_edit_with_more_than_one_manifest() throws {
// Given
let sourceRootPath = try temporaryPath()
let configPath = sourceRootPath.appending(components: Constants.tuistDirectoryName, "Config.swift")
let dependenciesPath = sourceRootPath.appending(components: Constants.tuistDirectoryName, "Dependencies.swift")
let otherProjectPath = "Module"
let projectManifestPaths = [
sourceRootPath.appending(component: "Project.swift"),
sourceRootPath.appending(component: otherProjectPath).appending(component: "Project.swift"),
]
let helperPaths: [AbsolutePath] = []
let templates: [AbsolutePath] = []
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
let projectName = "Manifests"
// When
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: configPath,
dependenciesPath: dependenciesPath,
projectManifests: projectManifestPaths,
editablePluginManifests: [],
pluginProjectDescriptionHelpersModule: [],
helpers: helperPaths,
templates: templates,
tasks: [],
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
let project = try XCTUnwrap(graph.projects.values.first)
let targets = graph.targets.values.lazy
.flatMap(\.values)
.sorted(by: { $0.name < $1.name })
// Then
XCTAssertEqual(targets.count, 4)
XCTAssertEmpty(targets.flatMap(\.dependencies))
// Generated Manifests target
let manifestOneTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "ModuleManifests" }))
XCTAssertEqual(manifestOneTarget.name, "ModuleManifests")
XCTAssertEqual(manifestOneTarget.platform, .macOS)
XCTAssertEqual(manifestOneTarget.product, .staticFramework)
XCTAssertEqual(
manifestOneTarget.settings,
expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory])
)
XCTAssertEqual(manifestOneTarget.sources.map(\.path), [try XCTUnwrap(projectManifestPaths.last)])
XCTAssertEqual(manifestOneTarget.filesGroup, .group(name: projectName))
XCTAssertEmpty(manifestOneTarget.dependencies)
// Generated Manifests target
let manifestTwoTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "\(sourceRootPath.basename)Manifests" }))
XCTAssertEqual(manifestTwoTarget.platform, .macOS)
XCTAssertEqual(manifestTwoTarget.product, .staticFramework)
XCTAssertEqual(
manifestTwoTarget.settings,
expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory])
)
XCTAssertEqual(manifestTwoTarget.sources.map(\.path), [try XCTUnwrap(projectManifestPaths.first)])
XCTAssertEqual(manifestTwoTarget.filesGroup, .group(name: projectName))
XCTAssertEmpty(manifestTwoTarget.dependencies)
// Generated Config target
let configTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "Config" }))
XCTAssertEqual(configTarget.name, "Config")
XCTAssertEqual(configTarget.platform, .macOS)
XCTAssertEqual(configTarget.product, .staticFramework)
XCTAssertEqual(configTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(configTarget.sources.map(\.path), [configPath])
XCTAssertEqual(configTarget.filesGroup, .group(name: projectName))
XCTAssertEmpty(configTarget.dependencies)
// Generated Project
XCTAssertEqual(project.path, sourceRootPath.appending(component: projectName))
XCTAssertEqual(project.name, projectName)
XCTAssertEqual(project.settings, Settings(
base: [
"ONLY_ACTIVE_ARCH": "NO",
"EXCLUDED_ARCHS": "x86_64",
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
))
XCTAssertEqual(project.filesGroup, .group(name: projectName))
// Generated Scheme
XCTAssertEqual(project.schemes.count, 1)
let scheme = try XCTUnwrap(project.schemes.first)
XCTAssertEqual(scheme.name, projectName)
let buildAction = try XCTUnwrap(scheme.buildAction)
XCTAssertEqual(buildAction.targets.map(\.name).sorted(), targets.map(\.name).sorted())
let runAction = try XCTUnwrap(scheme.runAction)
XCTAssertEqual(runAction.filePath, tuistPath)
let generateArgument = "generate --path \(sourceRootPath)"
XCTAssertEqual(runAction.arguments, Arguments(launchArguments: [LaunchArgument(name: generateArgument, isEnabled: true)]))
}
func test_tuist_edit_with_one_plugin_no_projects() throws {
let sourceRootPath = try temporaryPath()
let pluginManifestPaths = [sourceRootPath].map { $0.appending(component: "Plugin.swift") }
let editablePluginManifests = pluginManifestPaths.map {
EditablePluginManifest(name: $0.parentDirectory.basename, path: $0.parentDirectory)
}
let helperPaths: [AbsolutePath] = []
let templates: [AbsolutePath] = []
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
let projectName = "Plugins"
let projectsGroup = ProjectGroup.group(name: projectName)
// When
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: nil,
dependenciesPath: nil,
projectManifests: [],
editablePluginManifests: editablePluginManifests,
pluginProjectDescriptionHelpersModule: [],
helpers: helperPaths,
templates: templates,
tasks: [],
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
let project = try XCTUnwrap(graph.projects.values.first)
let targets = graph.targets.values.lazy
.flatMap(\.values)
.sorted(by: { $0.name < $1.name })
// Then
XCTAssertEqual(targets.count, 1)
XCTAssertEmpty(targets.flatMap(\.dependencies))
// Generated Plugin target
let pluginTarget = try XCTUnwrap(project.targets.last(where: { $0.name == sourceRootPath.basename }))
XCTAssertEqual(pluginTarget.platform, .macOS)
XCTAssertEqual(pluginTarget.product, .staticFramework)
XCTAssertEqual(pluginTarget.settings, expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory]))
XCTAssertEqual(pluginTarget.sources.map(\.path), pluginManifestPaths)
XCTAssertEqual(pluginTarget.filesGroup, projectsGroup)
XCTAssertEmpty(pluginTarget.dependencies)
// Generated Project
XCTAssertEqual(project.path, sourceRootPath.appending(component: projectName))
XCTAssertEqual(project.name, projectName)
XCTAssertEqual(project.settings, Settings(
base: [
"ONLY_ACTIVE_ARCH": "NO",
"EXCLUDED_ARCHS": "x86_64",
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
))
XCTAssertEqual(project.filesGroup, projectsGroup)
// Generated Schemes
XCTAssertEqual(project.schemes.count, 2)
let schemes = project.schemes
XCTAssertEqual(schemes.map(\.name).sorted(), [pluginTarget.name, "Plugins"].sorted())
let pluginBuildAction = try XCTUnwrap(schemes.first?.buildAction)
XCTAssertEqual(pluginBuildAction.targets.map(\.name), [pluginTarget.name])
let allPluginsBuildAction = try XCTUnwrap(schemes.last?.buildAction)
XCTAssertEqual(allPluginsBuildAction.targets.map(\.name).sorted(), targets.map(\.name).sorted())
}
func test_tuist_edit_with_more_than_one_plugin_no_projects() throws {
let sourceRootPath = try temporaryPath()
let pluginManifestPaths = [
sourceRootPath.appending(component: "A").appending(component: "Plugin.swift"),
sourceRootPath.appending(component: "B").appending(component: "Plugin.swift"),
]
let editablePluginManifests = pluginManifestPaths.map {
EditablePluginManifest(name: $0.parentDirectory.basename, path: $0.parentDirectory)
}
let helperPaths: [AbsolutePath] = []
let templates: [AbsolutePath] = []
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
let projectName = "Plugins"
let projectsGroup = ProjectGroup.group(name: projectName)
// When
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: nil,
dependenciesPath: nil,
projectManifests: [],
editablePluginManifests: editablePluginManifests,
pluginProjectDescriptionHelpersModule: [],
helpers: helperPaths,
templates: templates,
tasks: [],
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
let project = try XCTUnwrap(graph.projects.values.first)
let targets = graph.targets.values.lazy
.flatMap(\.values)
.sorted(by: { $0.name < $1.name })
// Then
XCTAssertEqual(targets.count, 2)
XCTAssertEmpty(targets.flatMap(\.dependencies))
// Generated first plugin target
let firstPluginTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "A" }))
XCTAssertEqual(firstPluginTarget.platform, .macOS)
XCTAssertEqual(firstPluginTarget.product, .staticFramework)
XCTAssertEqual(
firstPluginTarget.settings,
expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory])
)
XCTAssertEqual(firstPluginTarget.sources.map(\.path), [pluginManifestPaths[0]])
XCTAssertEqual(firstPluginTarget.filesGroup, projectsGroup)
XCTAssertEmpty(firstPluginTarget.dependencies)
// Generated second plugin target
let secondPluginTarget = try XCTUnwrap(project.targets.last(where: { $0.name == "B" }))
XCTAssertEqual(secondPluginTarget.platform, .macOS)
XCTAssertEqual(secondPluginTarget.product, .staticFramework)
XCTAssertEqual(
secondPluginTarget.settings,
expectedSettings(includePaths: [sourceRootPath, sourceRootPath.parentDirectory])
)
XCTAssertEqual(secondPluginTarget.sources.map(\.path), [pluginManifestPaths[1]])
XCTAssertEqual(secondPluginTarget.filesGroup, projectsGroup)
XCTAssertEmpty(secondPluginTarget.dependencies)
// Generated Project
XCTAssertEqual(project.path, sourceRootPath.appending(component: projectName))
XCTAssertEqual(project.name, projectName)
XCTAssertEqual(project.settings, Settings(
base: [
"ONLY_ACTIVE_ARCH": "NO",
"EXCLUDED_ARCHS": "x86_64",
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
))
XCTAssertEqual(project.filesGroup, projectsGroup)
// Generated Schemes
let schemes = project.schemes.sorted(by: { $0.name < $1.name })
XCTAssertEqual(project.schemes.count, 3)
XCTAssertEqual(
schemes.map(\.name),
[firstPluginTarget.name, secondPluginTarget.name, "Plugins"].sorted()
)
let firstBuildAction = try XCTUnwrap(schemes[0].buildAction)
XCTAssertEqual(
firstBuildAction.targets.map(\.name),
[firstPluginTarget].map(\.name)
)
let secondBuildAction = try XCTUnwrap(schemes[1].buildAction)
XCTAssertEqual(secondBuildAction.targets.map(\.name), [secondPluginTarget].map(\.name))
let pluginsBuildAction = try XCTUnwrap(schemes[2].buildAction)
XCTAssertEqual(
pluginsBuildAction.targets.map(\.name).sorted(),
[firstPluginTarget, secondPluginTarget].map(\.name).sorted()
)
}
func test_tuist_edit_plugin_only_takes_required_sources() throws {
// Given
let sourceRootPath = try temporaryPath()
let pluginManifestPath = sourceRootPath.appending(component: "Plugin.swift")
let editablePluginManifests = [
EditablePluginManifest(name: pluginManifestPath.parentDirectory.basename, path: pluginManifestPath.parentDirectory),
]
let helperPaths: [AbsolutePath] = []
let templates: [AbsolutePath] = []
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
try createFiles([
"Unrelated/Source.swift",
"Source.swift",
"ProjectDescriptionHelpers/data.json",
"Templates/strings.stencil",
])
let helperSources = try createFiles([
"ProjectDescriptionHelpers/HelperA.swift",
"ProjectDescriptionHelpers/HelperB.swift",
])
let templateSources = try createFiles([
"Templates/custom.swift",
"Templates/strings.stencil",
])
// When
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: nil,
dependenciesPath: nil,
projectManifests: [],
editablePluginManifests: editablePluginManifests,
pluginProjectDescriptionHelpersModule: [],
helpers: helperPaths,
templates: templates,
tasks: [],
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
// Then
let project = try XCTUnwrap(graph.projects.values.first)
let pluginTarget = try XCTUnwrap(project.targets.first)
XCTAssertEqual(
pluginTarget.sources,
([pluginManifestPath] + helperSources + templateSources).map { SourceFile(path: $0) }
)
}
func test_tuist_edit_project_with_plugin() throws {
// Given
let sourceRootPath = try temporaryPath()
let projectManifestPaths = [sourceRootPath].map { $0.appending(component: "Project.swift") }
let helperPaths: [AbsolutePath] = []
let templates: [AbsolutePath] = []
let projectDescriptionPath = sourceRootPath.appending(component: "ProjectDescription.framework")
let tuistPath = AbsolutePath("/usr/bin/foo/bar/tuist")
let projectName = "Manifests"
let projectsGroup = ProjectGroup.group(name: projectName)
// When
let pluginHelpersPath = AbsolutePath("/Path/To/Plugin/ProjectDescriptionHelpers")
let graph = try subject.map(
name: "TestManifests",
tuistPath: tuistPath,
sourceRootPath: sourceRootPath,
destinationDirectory: sourceRootPath,
configPath: nil,
dependenciesPath: nil,
projectManifests: projectManifestPaths,
editablePluginManifests: [],
pluginProjectDescriptionHelpersModule: [.init(name: "Plugin", path: pluginHelpersPath)],
helpers: helperPaths,
templates: templates,
tasks: [],
projectDescriptionPath: projectDescriptionPath,
projectAutomationPath: sourceRootPath.appending(component: "ProjectAutomation.framework")
)
let project = try XCTUnwrap(graph.projects.values.first)
let targets = graph.targets.values.lazy
.flatMap(\.values)
.sorted(by: { $0.name < $1.name })
// Then
XCTAssertEqual(targets.count, 1)
XCTAssertEmpty(targets.flatMap(\.dependencies))
// Generated Manifests target
let manifestsTarget = try XCTUnwrap(project.targets.last(where: { $0.name == sourceRootPath.basename + projectName }))
XCTAssertEqual(manifestsTarget.platform, .macOS)
XCTAssertEqual(manifestsTarget.product, .staticFramework)
XCTAssertEqual(
manifestsTarget.settings,
expectedSettings(includePaths: [
sourceRootPath,
sourceRootPath.parentDirectory,
pluginHelpersPath.parentDirectory,
pluginHelpersPath.parentDirectory.parentDirectory,
])
)
XCTAssertEqual(manifestsTarget.sources.map(\.path), projectManifestPaths)
XCTAssertEqual(manifestsTarget.filesGroup, projectsGroup)
XCTAssertEmpty(manifestsTarget.dependencies)
// Generated Project
XCTAssertEqual(project.path, sourceRootPath.appending(component: projectName))
XCTAssertEqual(project.name, projectName)
XCTAssertEqual(project.settings, Settings(
base: [
"ONLY_ACTIVE_ARCH": "NO",
"EXCLUDED_ARCHS": "x86_64",
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
))
XCTAssertEqual(project.filesGroup, projectsGroup)
// Generated Scheme
XCTAssertEqual(project.schemes.count, 1)
let scheme = try XCTUnwrap(project.schemes.first)
XCTAssertEqual(scheme.name, projectName)
let buildAction = try XCTUnwrap(scheme.buildAction)
XCTAssertEqual(buildAction.targets.map(\.name), targets.map(\.name))
let runAction = try XCTUnwrap(scheme.runAction)
XCTAssertEqual(runAction.filePath, tuistPath)
let generateArgument = "generate --path \(sourceRootPath)"
XCTAssertEqual(runAction.arguments, Arguments(launchArguments: [LaunchArgument(name: generateArgument, isEnabled: true)]))
}
fileprivate func expectedSettings(includePaths: [AbsolutePath]) -> Settings {
let paths = includePaths
.map(\.pathString)
.map { "\"\($0)\"" }
return Settings(
base: [
"FRAMEWORK_SEARCH_PATHS": .array(paths),
"LIBRARY_SEARCH_PATHS": .array(paths),
"SWIFT_INCLUDE_PATHS": .array(paths),
"SWIFT_VERSION": .string("5.2"),
],
configurations: Settings.default.configurations,
defaultSettings: .recommended
)
}
}
| 44.970423 | 130 | 0.671208 |
213c60dcc285fb7edee0bf9b4158894e378069da | 757 | extension ObjectAPI.RequestError: CustomDebugStringConvertible {
public var debugDescription: String {
var description = "ObjectAPI.RequestError"
switch self {
case .apiError(_):
description += ".apiError:\n\n\(debugDetails)\n"
case .statusCodeError(_):
description += ".statusCodeError:\n\n\(debugDetails)\n"
}
return description
}
}
extension ObjectAPI.RequestError: DebugDetails {
public var debugDetails: String {
let details: String
switch self {
case .apiError(let error):
details = error.debugDetails
case .statusCodeError(let error):
details = error.debugDetails
}
return details
}
}
| 25.233333 | 67 | 0.610304 |
bf2059da05c5340bdda71f2400bd3bf990cd7cdc | 2,484 | //
// ReaderRestViewController.swift
// PeasNovel
//
// Created by lieon on 2019/6/11.
// Copyright © 2019 NotBroken. All rights reserved.
//
import UIKit
import RxSwift
import RealmSwift
class ReaderRestViewController: BaseViewController {
@IBOutlet weak var cancleBtn: UIButton!
@IBOutlet weak var faceBtn: UIButton!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var contactLabel: UILabel!
@IBOutlet weak var closeBtn: UIButton!
@IBOutlet weak var contactBtn: UIButton!
var enterAction: (() -> Void)?
var cancleAction: (() -> Void)?
var forceAction: (() -> Void)?
var closeAction: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
let enterAction = self.enterAction
let cancleAction = self.cancleAction
let forceAction = self.forceAction
let closeAction = self.closeAction
cancleBtn.layer.cornerRadius = 21
cancleBtn.layer.borderColor = UIColor.theme.cgColor
cancleBtn.layer.borderWidth = 1
containerView.layer.cornerRadius = 4
containerView.layer.masksToBounds = true
contactBtn.layer.cornerRadius = 21
contactBtn.layer.masksToBounds = true
faceBtn.layer.cornerRadius = 21
faceBtn.layer.masksToBounds = true
contactBtn.setTitleColor(UIColor.white, for: .normal)
faceBtn.setTitleColor(UIColor.white, for: .normal)
closeBtn.rx.tap.mapToVoid()
.subscribe(onNext: { (_) in
self.dismiss(animated: true, completion: closeAction)
})
.disposed(by: bag)
contactBtn.rx.tap.mapToVoid()
.subscribe(onNext: { (_) in
self.dismiss(animated: true, completion: enterAction)
})
.disposed(by: bag)
cancleBtn.rx.tap.mapToVoid()
.subscribe(onNext: { (_) in
self.dismiss(animated: true, completion: cancleAction)
})
.disposed(by: bag)
faceBtn.rx.tap.mapToVoid()
.subscribe(onNext: { (_) in
self.dismiss(animated: true, completion: forceAction)
})
.disposed(by: bag)
/// 弹出之后,清空数据
let realm = try! Realm(configuration: Realm.Configuration.defaultConfiguration)
let record = FullScreenBookReadingTime()
try? realm.write {
realm.add(record, update: .all)
}
}
}
| 32.684211 | 87 | 0.608696 |
6473ae6b4f6066f2ae8984d54dc20d5e0df8b340 | 888 | //
// ValidationService.swift
// ordermentum-swift-sdk
//
// Created by Brandon Stillitano on 9/4/19.
// Copyright © 2019 Ordermentum. All rights reserved.
//
import Foundation
import Alamofire
public class ValidationService {
public init() {}
/**
* Validate a list of products to ensure that they are orderable in their
* current configuration.
* Returns a Profile.UserProfile
*/
public func validateItems(_ requestObject: ValidationRequestBody, completion: @escaping (Bool, Validation?, ErrorResponse?) -> Void) {
//Build Route
let route = ValidationRouter.validateItems(requestObject) as URLRequestConvertible
//Call API
Service<Validation, ErrorResponse>().request(route: route) { (result, responseObject, errorObject) in
completion(result, responseObject, errorObject)
}
}
}
| 29.6 | 138 | 0.681306 |
6a11a3e2ca5954371665a61c9e15ec9db9dcfb03 | 200 | extension UIView {
func addSubviews(_ subviews: UIView...) {
subviews.forEach(addSubview)
}
}
// Add multiple subviews in a single line
view.addSubview(imageView, slider, view, label) | 25 | 47 | 0.7 |
d73fea7062eec6db87b3b53f50c8cf431940ab74 | 1,597 | //
// Variable.swift
// CDBuild
//
// Created by xcbosa on 2021/8/20.
//
import Foundation
/// 描述一个运行时变量
class CDBuildVariable {
var data = Set<String>()
public init() { }
public init(fromVariableLiterial variables: [CDBuildVariable]) {
add(variables: variables)
}
public init(fromStringLiterial string: String) {
data.insert(string)
}
public func add(string: String) {
if !data.contains(string) {
data.insert(string)
}
}
public func add(variables: [CDBuildVariable]) {
for it in variables { add(variable: it) }
}
public func add(variable: CDBuildVariable) {
for dat in variable.data {
if !data.contains(dat) {
data.insert(dat)
}
}
}
public func remove(regex: String) {
guard let reg = try? NSRegularExpression(pattern: regex, options: .useUnixLineSeparators) else { return }
for it in data {
if reg.numberOfMatches(in: it, options: .reportCompletion, range: NSRange(location: 0, length: it.count)) > 0 {
data.remove(it)
}
}
}
public var firstString: String { data.first ?? "" }
public var commandString: String {
var build = "", id = 0
for it in data {
build.append("\"")
build.append(it)
build.append("\"")
id += 1
if id < data.count {
build.append(" ")
}
}
return build
}
}
| 23.144928 | 123 | 0.520977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.