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
|
---|---|---|---|---|---|
8919c65b0f4e35ab27d5774a52146388109e27e2 | 1,988 | //
// SwinjectStoryboardExtension.swift
// Hackers
//
// Created by Weiran Zhang on 21/04/2019.
// Copyright © 2019 Weiran Zhang. All rights reserved.
//
import SwinjectStoryboard
extension SwinjectStoryboard {
@objc class func setup() {
let container = defaultContainer
container.storyboardInitCompleted(FeedViewController.self) { resolver, controller in
controller.authenticationUIService = resolver.resolve(AuthenticationUIService.self)!
controller.swipeCellKitActions = resolver.resolve(SwipeCellKitActions.self)!
}
container.storyboardInitCompleted(CommentsViewController.self) { resolver, controller in
controller.authenticationUIService = resolver.resolve(AuthenticationUIService.self)!
controller.swipeCellKitActions = resolver.resolve(SwipeCellKitActions.self)!
controller.navigationService = resolver.resolve(NavigationService.self)!
}
container.storyboardInitCompleted(SettingsViewController.self) { resolver, controller in
controller.sessionService = resolver.resolve(SessionService.self)!
controller.authenticationUIService = resolver.resolve(AuthenticationUIService.self)!
}
container.register(SessionService.self) { _ in
SessionService()
}.inObjectScope(.container)
container.register(AuthenticationUIService.self) { resolver in
AuthenticationUIService(sessionService: resolver.resolve(SessionService.self)!)
}.inObjectScope(.container)
container.register(SwipeCellKitActions.self) { resolver in
SwipeCellKitActions(
authenticationUIService: resolver.resolve(AuthenticationUIService.self)!)
}
container.register(NavigationService.self) { _ in
NavigationService()
}.inObjectScope(.container)
}
class func getService<T>() -> T? {
return defaultContainer.resolve(T.self)
}
}
| 41.416667 | 96 | 0.70674 |
50f7063de061207bf5ca6d1b693ed9895bd08567 | 3,193 | /*
Copyright 2009-2016 Urban Airship Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE URBAN AIRSHIP INC ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL URBAN AIRSHIP INC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import AirshipKit
class HomeViewController: UIViewController {
@IBOutlet var enablePushButton: UIButton!
@IBOutlet var channelIDButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "refreshView",
name: "channelIDUpdated",
object: nil);
}
override func viewWillAppear(animated: Bool) {
refreshView()
}
func refreshView () {
if (UAirship.push().userPushNotificationsEnabled) {
channelIDButton.setTitle(UAirship.push().channelID, forState: UIControlState.Normal)
channelIDButton.hidden = false
enablePushButton.hidden = true
return
}
channelIDButton.hidden = true
enablePushButton.hidden = true
}
@IBAction func buttonTapped(sender: UIButton) {
if (sender == enablePushButton) {
UAirship.push().userPushNotificationsEnabled = true
}
//The channel ID will need to wait for push registration to return the channel ID
if (sender == channelIDButton) {
if ((UAirship.push().channelID) != nil) {
UIPasteboard.generalPasteboard().string = UAirship.push().channelID
let message = UAInAppMessage()
message.alert = NSLocalizedString("UA_Copied_To_Clipboard", tableName: "UAPushUI", comment: "Copied to clipboard string")
message.position = UAInAppMessagePosition.Top
message.duration = 1.5
message.primaryColor = UIColor(red: 255/255, green: 200/255, blue: 40/255, alpha: 1)
message.secondaryColor = UIColor(red: 0/255, green: 105/255, blue: 143/255, alpha: 1)
UAirship.inAppMessaging().displayMessage(message)
}
}
}
}
| 38.939024 | 137 | 0.695271 |
71a78df1de6a9cb6f7967d4effb35c7d2709bad3 | 193 |
import Foundation
@objc public class TestSubtitle: NSObject {
public static func create(with mimetype: String) -> Subtitle {
print("\(#function)")
return SubRib()
}
}
| 19.3 | 66 | 0.642487 |
8f5f986c7d53507f166c44eb43bc880492339a35 | 1,770 |
//Copyright (c) [2021] [Michael Haslam]
//
//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 SwiftUI
struct StoriesListView: View {
@EnvironmentObject var storyListVM: StoryListViewModel
var body: some View {
NavigationView {
ScrollView {
VStack (spacing: 20){
ForEach(storyListVM.storyViewModels) { storyViewModel in
StoryCardView(storyViewModel: storyViewModel)
}
}
.padding()
}
.navigationBarHidden(true)
}
}
}
struct StoriesListView_Previews: PreviewProvider {
static var previews: some View {
StoriesListView().environmentObject(StoryListViewModel())
}
}
| 38.478261 | 80 | 0.697175 |
fe1bf132dbbe8c867da6e7845bf484dd3efc917a | 499 | //
// AppDelegate.swift
// Smart_image
//
// Created by Yifan Xu on 9/23/16.
// Copyright © 2016 Yifan Xu. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| 18.481481 | 71 | 0.711423 |
64aa6f1a24a5bd552c5ae5872f4a72578d385072 | 6,879 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
/// Super-naive code to read a .sfz file, as produced by vonRed's free ESX24-to-SFZ program
/// See https://bitbucket.org/vonred/exstosfz/downloads/ (you'll need Python 3 to run it).
extension AKSampler {
/// Load an SFZ at the given location
///
/// Parameters:
/// - path: Path to the file as a string
/// - fileName: Name of the SFZ file
///
open func loadSFZ(path: String, fileName: String) {
loadSFZ(url: URL(fileURLWithPath: path).appendingPathComponent(fileName))
}
/// Load an SFZ at the given location
///
/// Parameters:
/// - url: File url to the SFZ file
///
open func loadSFZ(url: URL) {
stopAllVoices()
unloadAllSamples()
var lowNoteNumber: MIDINoteNumber = 0
var highNoteNumber: MIDINoteNumber = 127
var noteNumber: MIDINoteNumber = 60
var lowVelocity: MIDIVelocity = 0
var highVelocity: MIDIVelocity = 127
var sample: String = ""
var loopMode: String = ""
var loopStartPoint: Float32 = 0
var loopEndPoint: Float32 = 0
let samplesBaseURL = url.deletingLastPathComponent()
do {
let data = try String(contentsOf: url, encoding: .ascii)
let lines = data.components(separatedBy: .newlines)
for line in lines {
let trimmed = String(line.trimmingCharacters(in: .whitespacesAndNewlines))
if trimmed == "" || trimmed.hasPrefix("//") {
// ignore blank lines and comment lines
continue
}
if trimmed.hasPrefix("<group>") {
// parse a <group> line
for part in trimmed.dropFirst(7).components(separatedBy: .whitespaces) {
if part.hasPrefix("key") {
noteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0
lowNoteNumber = noteNumber
highNoteNumber = noteNumber
} else if part.hasPrefix("lokey") {
lowNoteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0
} else if part.hasPrefix("hikey") {
highNoteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0
} else if part.hasPrefix("pitch_keycenter") {
noteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0
}
}
}
if trimmed.hasPrefix("<region>") {
// parse a <region> line
for part in trimmed.dropFirst(8).components(separatedBy: .whitespaces) {
if part.hasPrefix("lovel") {
lowVelocity = MIDIVelocity(part.components(separatedBy: "=")[1]) ?? 0
} else if part.hasPrefix("hivel") {
highVelocity = MIDIVelocity(part.components(separatedBy: "=")[1]) ?? 0
} else if part.hasPrefix("loop_mode") {
loopMode = part.components(separatedBy: "=")[1]
} else if part.hasPrefix("loop_start") {
loopStartPoint = Float32(part.components(separatedBy: "=")[1]) ?? 0
} else if part.hasPrefix("loop_end") {
loopEndPoint = Float32(part.components(separatedBy: "=")[1]) ?? 0
} else if part.hasPrefix("sample") {
sample = trimmed.components(separatedBy: "sample=")[1]
}
}
let noteFrequency = Float(440.0 * pow(2.0, (Double(noteNumber) - 69.0) / 12.0))
let noteLog = "load \(noteNumber) \(noteFrequency) NN range \(lowNoteNumber)-\(highNoteNumber)"
AKLog("\(noteLog) vel \(lowVelocity)-\(highVelocity) \(sample)")
let sampleDescriptor = AKSampleDescriptor(noteNumber: Int32(noteNumber),
noteFrequency: noteFrequency,
minimumNoteNumber: Int32(lowNoteNumber),
maximumNoteNumber: Int32(highNoteNumber),
minimumVelocity: Int32(lowVelocity),
maximumVelocity: Int32(highVelocity),
isLooping: loopMode != "",
loopStartPoint: loopStartPoint,
loopEndPoint: loopEndPoint,
startPoint: 0.0,
endPoint: 0.0)
let sampleFileURL = samplesBaseURL.appendingPathComponent(sample)
if sample.hasSuffix(".wv") {
sampleFileURL.path.withCString { path in
loadCompressedSampleFile(from: AKSampleFileDescriptor(sampleDescriptor: sampleDescriptor,
path: path))
}
} else {
if sample.hasSuffix(".aif") || sample.hasSuffix(".wav") {
let compressedFileURL = samplesBaseURL
.appendingPathComponent(String(sample.dropLast(4) + ".wv"))
let fileMgr = FileManager.default
if fileMgr.fileExists(atPath: compressedFileURL.path) {
compressedFileURL.path.withCString { path in
loadCompressedSampleFile(
from: AKSampleFileDescriptor(sampleDescriptor: sampleDescriptor,
path: path))
}
} else {
let sampleFile = try AKAudioFile(forReading: sampleFileURL)
loadAKAudioFile(from: sampleDescriptor, file: sampleFile)
}
}
}
}
}
} catch {
AKLog("Could not load SFZ: \(error.localizedDescription)")
}
buildKeyMap()
restartVoices()
}
}
| 52.113636 | 117 | 0.463149 |
e2f56a0fe0b2a5595c4677fd9112d41c9e0d82f7 | 1,907 | import AppKit
private extension URL {
static let showRSSURL = URL(string: "https://showrss.info/")!
static let appURL = URL(string: "http://github.com/mipstian/catch")!
static let bugReportURL = URL(string: "https://github.com/mipstian/catch/issues/new?labels=bug")!
static let featureRequestURL = URL(string: "https://github.com/mipstian/catch/issues/new?labels=enhancement")!
static let helpURL = URL(string: "https://github.com/mipstian/catch/wiki/Configuration")!
}
class Browser: NSObject {
static func openInBackground(url: URL) {
// Open a link without bringing app that handles it to the foreground
NSWorkspace.shared.open(
[url],
withAppBundleIdentifier: nil,
options: .withoutActivation,
additionalEventParamDescriptor: nil,
launchIdentifiers: nil
)
}
static func openInBackground(file: String) {
// Open a file without bringing app that handles it to the foreground
NSWorkspace.shared.openFile(file, withApplication: nil, andDeactivate: false)
}
}
// MARK: Actions
extension Browser {
@IBAction private func browseService(_: Any?) {
// Launch the system browser, open ShowRSS
NSWorkspace.shared.open(.showRSSURL)
}
@IBAction private func browseWebsite(_: Any?) {
// Launch the system browser, open the applications's website
NSWorkspace.shared.open(.appURL)
}
@IBAction private func browseHelp(_: Any?) {
// Launch the system browser, open the applications's on-line help
NSWorkspace.shared.open(.helpURL)
}
@IBAction private func browseFeatureRequest(_: Any?) {
// Launch the system browser, open the applications's feature request page
NSWorkspace.shared.open(.featureRequestURL)
}
@IBAction private func browseBugReport(_: Any?) {
// Launch the system browser, open the applications's bug report page
NSWorkspace.shared.open(.bugReportURL)
}
}
| 32.322034 | 112 | 0.716308 |
75ddba86e516eff0154182131f126e1b896dda80 | 1,352 | // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Created by Sam Deane on 09/03/21.
// All code (c) 2021 - present day, Elegant Chaos Limited.
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#if canImport(SwiftUI)
#if canImport(UIKit)
import SwiftUI
public typealias BarcodeCallback = (String) -> ()
/// SwiftUI View which wraps a CaptureUIViewController.
/// Could easily be adapted to work with an AppKit variant too.
///
/// Accepts a callback block which it calls whenever a barcode
/// has been detected.
public struct CaptureView : UIViewControllerRepresentable {
let callback: BarcodeCallback
public init(callback: @escaping BarcodeCallback) {
self.callback = callback
}
public func makeUIViewController(context: UIViewControllerRepresentableContext<CaptureView>) -> CaptureUIViewController {
let controller = CaptureUIViewController()
controller.callback = callback
return controller
}
public func updateUIViewController(_ uiViewController: CaptureUIViewController, context: UIViewControllerRepresentableContext<CaptureView>) {
}
public static func dismantleUIViewController(_ uiViewController: CaptureUIViewController, coordinator: ()) {
uiViewController.cleanup()
}
}
#endif
#endif
| 31.44186 | 145 | 0.651627 |
efabc06313d0951ee42d966184964c3a462c32a2 | 1,103 | import Foundation
public struct Publication {
public let id : String
public let name : String
public let desc : String
public let url : URL
public let imageURL : URL
}
extension Publication : Serializable {
public init?(from json : JSONDictionary) {
guard let id = json["id"] as? String,
let name = json["name"] as? String,
let desc = json["description"] as? String,
let u = json["url"] as? String,
let url = URL(string: u),
let i = json["imageUrl"] as? String,
let imageUrl = URL(string: i)
else { return nil }
self.id = id
self.name = name
self.desc = desc
self.url = url
self.imageURL = imageUrl
}
public func toDictionary() -> JSONDictionary {
let dict : JSONDictionary = [
"id" : id,
"name" : name,
"description" : desc,
"url" : url.absoluteString,
"imageUrl" : imageURL.absoluteString,
]
return dict
}
}
| 24.511111 | 54 | 0.515866 |
01d4f3724c39e956f729d30eedabcfa449206ab6 | 155 | //
// CatetoryHeaderView.swift
// Explorer
//
// Created by Zagahr on 11.09.18.
// Copyright © 2018 Zagahr. All rights reserved.
//
import Foundation
| 15.5 | 49 | 0.683871 |
8a86021c9c92c80a5025d773a982eae61b92d2b7 | 1,069 | import Foundation
import CommonWallet
import SoraUI
class WalletBaseAmountView: UIView {
@IBOutlet private(set) var borderView: BorderedContainerView!
@IBOutlet private(set) var fieldBackgroundView: TriangularedView!
@IBOutlet private(set) var animatedTextField: AnimatedTextField!
@IBOutlet private(set) var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupSubviews()
}
func setupSubviews() {
_ = R.nib.walletAmountView(owner: self)
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
}
}
| 30.542857 | 86 | 0.720299 |
9b48a15cb376f6e846255b3c5ed3324617a6f274 | 2,380 | //
// ComposeTweetViewController.swift
// Twitter
//
// Created by Archit Rathi on 2/14/16.
// Copyright © 2016 Archit Rathi. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController {
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var tweetText: UITextField!
@IBOutlet weak var characterLimitLabel: UILabel!
@IBOutlet weak var sendButton1: UIButton!
var user: User!
override func viewDidLoad() {
super.viewDidLoad()
TwitterClient.sharedInstance.myCredentials() { (user, error) -> () in
self.user = user
if (user.name != nil) {
self.usernameLabel.text = user.name
}
if (user.profileImageUrl != nil) {
self.profileImage.setImageWithURL(NSURL(string: user.profileImageUrl!)!)
}
// Do any additional setup after loading the view.
}
}
@IBAction func textChanged(sender: AnyObject) {
print("changed")
let temp = tweetText.text
let numTemp = temp?.characters.count
characterLimitLabel.text = "\(140 - numTemp!)"
if (Int(characterLimitLabel.text!)! <= 0) {
tweetText.text = String(tweetText.text!.characters.dropLast())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendButton(sender: AnyObject) {
if (tweetText.text != nil) {
let messageToSend = tweetText.text!.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil)
TwitterClient.sharedInstance.makeTweet(messageToSend)
}
dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 29.382716 | 167 | 0.634874 |
4b2cb6902e0cde9935ae3354736a99e3c223b99f | 2,089 | //
// SSRLoginViewController.swift
// SSRSwift
//
// Created by shendong on 2019/12/31.
// Copyright © 2019 Don.shen. All rights reserved.
//
import UIKit
class SSRLoginViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Login"
let button = UIButton(type: .custom)
button.backgroundColor = UIColor(hex6: "#62CCB0")
button.setTitle("Login", for: .normal)
button.rx.tap.subscribe(onNext: {
if SSRUserManager.shared.isLogin(){
Toast(text: "已登录").show()
return
}
SSRUserManager.shared.login(userId: "ssr", userKey: "123236").done { (arg) in
let (result, error) = arg
if result == true{
Toast(text: "登录成功", type: 1).show()
}else{
if let nserror = error as NSError?{
Toast(text: nserror.localizedDescription, type: 1).show()
}
}
}.catch { error in
VLog(error)
}
}).disposed(by: base_disposeBag)
view.addSubview(button)
button.snp.makeConstraints { [weak self] (make) -> Void in
make.width.height.equalTo(100)
make.center.equalTo(self!.view)
}
let logOutButton = UIButton(type: .custom)
logOutButton.backgroundColor = UIColor(hex6: "#62CCB0")
logOutButton.setTitle("LogOut", for: .normal)
logOutButton.rx.tap.subscribe(onNext: {
SSRUserManager.shared.logOut()
Toast(text: "Logout Success").show()
UIApplication.shared.openURL(URL(string: "https://app.huamengxiaoshuo.com/vnovel/test/")!)
}).disposed(by: base_disposeBag)
view.addSubview(logOutButton)
logOutButton.snp.makeConstraints { [weak self] (make) -> Void in
make.top.equalTo(button.snp_bottom).offset(100.0)
make.width.height.equalTo(100)
make.centerX.equalTo(self!.view)
}
}
}
| 36.649123 | 102 | 0.56247 |
e0f1bb8344765a3782f42546cb9146780193dbdc | 2,722 | //
// EthAddress.swift
//
//
// Created by Yehor Popovych on 26.08.2021.
//
import Foundation
public struct EthAccount: AccountProtocol, ExtendedAddressProtocol, Equatable, Hashable {
public typealias Addr = EthAddress
public typealias Base = EthAddress
public let address: EthAddress
public let path: Bip32Path
public var index: UInt32 { accountIndex }
public var isChange: Bool { false }
public var accountIndex: UInt32 { path.accountIndex! }
public init(pubKey: Data, path: Bip32Path) throws {
let addr: EthAddress
do {
addr = try EthAddress(pubKey: pubKey)
} catch AddressError.badPublicKey(key: let pk) {
throw AccountError.badPublicKey(key: pk)
}
try self.init(address: addr, path: path)
}
public init(address: EthAddress, path: Bip32Path) throws {
guard path.isValidEthereumAccount else {
throw AccountError.badBip32Path(path: path)
}
self.address = address
self.path = path
}
}
public struct EthAddress: AddressProtocol, Equatable, Hashable {
public typealias Extended = EthAccount
public static let rawAddressSize = 20
public let rawAddress: Data
public init(pubKey: Data) throws {
guard let raw = Algos.Ethereum.address(from: pubKey) else {
throw AccountError.badPublicKey(key: pubKey)
}
self.rawAddress = raw
}
public init(hex: String, eip55: Bool = false) throws {
guard let addr = Algos.Ethereum.address(from: hex, eip55: eip55) else {
throw AddressError.badAddressString(address: hex)
}
self.rawAddress = addr
}
public func hex(eip55: Bool = false) -> String {
return Algos.Ethereum.hexAddress(rawAddress: rawAddress, eip55: eip55)
}
public func verify(message: Data, signature: Signature) -> Bool {
return Algos.Ethereum.verify(address: rawAddress,
message: message,
signature: signature.raw) ?? false
}
public func extended(path: Bip32Path) throws -> Extended {
do {
return try EthAccount(address: self, path: path)
} catch AccountError.badBip32Path(path: let p) {
throw AddressError.badBip32Path(path: p)
}
}
}
extension EthAddress: AvalancheCodable {
public init(from decoder: AvalancheDecoder) throws {
self.rawAddress = try decoder.decode(size: Self.rawAddressSize)
}
public func encode(in encoder: AvalancheEncoder) throws {
try encoder.encode(rawAddress, size: Self.rawAddressSize)
}
}
| 30.58427 | 89 | 0.627112 |
f9aba9ba76d39182999df7f7595b719ed0c051a1 | 7,673 | //
// Line.swift
// Distance
//
// Created by CoderXu on 2020/11/11.
//
import Foundation
import simd
//定义直线
struct Line {
let position:simd_float3
let direction:simd_float3
///点在直线上的投影坐标
static func projectionOnLine(from point:simd_float3, to line:Line) -> simd_float3 {
let vector = point - line.position
let normalizedDirection = normalize(line.direction)
let dotValue = dot(vector, normalizedDirection)
let tarPoint = line.position + dotValue * normalizedDirection
return tarPoint
}
///点与直线间的距离
static func distanceBetween(point:simd_float3, line:Line) -> Float{
let position = projectionOnLine(from: point, to: line)
return distance(position, point)
}
///点与直线间距离的平方
static func distanceSquaredBetween(point:simd_float3, line:Line) -> Float {
let position = projectionOnLine(from: point, to: line)
return distance_squared(position, point)
}
/// 精度不够高
static func distanceBetween2(point:simd_float3, line:Line) -> Float {
let vector = point - line.position
let normalizedDirection = normalize(line.direction)
let dotValue = dot(vector, normalizedDirection)
let tarPoint = line.position + dotValue * normalizedDirection
let disVector = point - tarPoint
if disVector.tooLittleToBeNormalized() || vector.tooLittleToBeNormalized() {
return 0
}
let normalizedDis = normalize(disVector)
return dot(vector, normalizedDis)
}
///点是否在直线上(误差范围内)
static func isPointOnLine(point:simd_float3, line:Line) -> Bool {
let tarPoint = projectionOnLine(from: point, to: line)
return tarPoint.isAlmostSamePoint(to: point)
}
///点是否在直线上(误差范围内)
static func isPointOnLine2(point:simd_float3, line:Line) -> Bool {
let vector = point - line.position
return vector.isAlmostParallel(to: line.direction)
}
/// 精度不够高
static func isPointOnLine3(point:simd_float3, line:Line) -> Bool {
let vector = point - line.position
if vector.tooLittleToBeNormalized() {
return true
}
let normalizedVector = normalize(vector)
let normalizedDirection = normalize(line.direction)
let dotValue = dot(normalizedVector, normalizedDirection)
return abs(dotValue - 1) < Float.leastNonzeroMagnitude
}
static func pointToLineTest() {
let line = Line(position: simd_float3(0, 0, 0), direction: simd_float3(0, 0, 1))
let pointC = simd_float3(1, 5, 2000019)
let distance = distanceBetween2(point: pointC, line: line)
let distanceSquared = distanceSquaredBetween(point: pointC, line: line)
let tarPoint = projectionOnLine(from: pointC, to: line)
print("距离\(distance),距离平方\(distanceSquared), 投影点\(tarPoint)")
print(isPointOnLine(point: pointC, line: line),isPointOnLine2(point: pointC, line: line),isPointOnLine3(point: pointC, line: line))
if (distanceSquared < Float.toleranceThreshold) {
print("点在直线上")
} else {
print("点不在直线上")
}
}
///直线与直线是否平行(误差范围内)
static func isParallel(line1:Line, line2:Line) -> Bool {
return line1.direction.isAlmostParallel(to: line2.direction)
}
///直线与直线是否重合(误差范围内)
static func isSame(line1:Line, line2:Line) -> Bool {
if !isParallel(line1: line1, line2: line2) {
return false
}
let vector = line1.position - line2.position
if vector.tooLittleToBeNormalized() {//防止接近0的向量被判定为平行
return false
} else {
return vector.isAlmostParallel(to: line1.direction)
}
}
///直线与直线间的距离
static func distanceBetween(line1:Line, line2:Line) -> Float {
let parallelResult = line2.direction.almostParallelRelative(to: line1.direction)
let crossValue = parallelResult.crossValue
if parallelResult.isParallel {
// 平行
return distanceBetween(point:line1.position, line:line2)
}
let distanceVector = normalize(crossValue)
let vector = line1.position - line2.position
let dis = dot(distanceVector, vector)
return abs(dis)
}
///直线与直线最近点坐标
static func footPoints(line1:Line, line2:Line) -> (simd_float3, simd_float3)? {
let parallelResult = line2.direction.almostParallelRelative(to: line1.direction)
let crossValue = parallelResult.crossValue
if parallelResult.isParallel {
// 平行
return nil
}
let distanceVector = normalize(crossValue)
let vector = line1.position - line2.position
let dis = dot(distanceVector, vector)
let point2OnPlane = line2.position + dis * distanceVector
let projectionOnLine1 = projectionOnLine(from: point2OnPlane, to: line1)
let result = projectionOnLine1.almostSamePoint(to: point2OnPlane)
if result.isSame {
// 垂足是 line2.position
return (point2OnPlane,line2.position)
}
let projectionVector = projectionOnLine1 - point2OnPlane
let squared = result.distanceSquared
let x1:Float = squared / dot(line2.direction, projectionVector)
let footPoint2 = point2OnPlane + x1 * line2.direction
let footPoint1 = footPoint2 - dis * distanceVector
return (footPoint1, footPoint2)
}
static func pointToLineTest2() {
let line1 = Line(position: simd_float3(0, 0, 0), direction: simd_float3(0, 0, 1))
let line2 = Line(position: simd_float3(50000, 50000, 50000), direction: simd_float3(1, 1, 1))
let disBetween = distanceBetween(line1: line1, line2: line2)
print("distanceBetween\(disBetween)")
if let (foot1, foot2) = footPoints(line1: line1, line2: line2) {
print(foot1, foot2)
}
}
///SVD 拟合直线
static func estimateLineSVD(from points:[simd_float3]) -> Line? {
if points.count < 2 {
return nil
}
var source:[Float] = Array(repeating: 0, count: points.count*3)
var position = simd_float3.zero
for point in points {
position += (point / Float(points.count))
}
for (row,point) in points.enumerated() {
source[row] = point.x - position.x
source[row+points.count] = point.y - position.y
source[row+2*points.count] = point.z - position.z
}
// source 中数据顺序为[x0,x1,x2.....y0,y1,y2.....z0,z1,z3....],竖向按列依次填充到 rowCount行*3列 的矩阵中
let ss = Matrix(source: source, rowCount: points.count, columnCount:3)
let svdResult = Matrix.svd(a: ss)
let vt = svdResult.vt
let offset = 0
let direction = simd_float3(vt[offset], vt[offset+vt.columnCount], vt[offset+2*vt.columnCount])
return Line(position: position, direction: direction)
}
static func pointToLineTest3() {
// let points = [
//// simd_float3.zero,
// simd_float3(-1, 0, 1000),
// simd_float3(3, 0.1, 1000.1),
// simd_float3(30, 5, 1000),
// simd_float3(-40, -1, 1000.2),
// ]
let points = [
simd_float3(-1, 0, -100),
simd_float3(30, 0.1, -100.1),
simd_float3(10, 10, 100),
simd_float3(-30, 5, 100),
simd_float3(40, -1, 100.2),
]
let line2 = estimateLineSVD(from: points)
print(line2 as Any)
}
}
| 37.429268 | 139 | 0.612277 |
89fc4bb9f0260106001e5d65a5a19f3fd7a460ef | 6,583 | //
// ScanVC.swift
// visafe
//
// Created by Cuong Nguyen on 7/27/21.
//
import UIKit
import ObjectMapper
import LocalAuthentication
import DeviceKit
public enum ScanDescriptionEnum: String {
case about = "KIỂM TRA BẢO MẬT"
case protect = "CHẾ ĐỘ BẢO VỆ"
case wifi = "BẢO VỆ WI-FI"
case protocoll = "PHƯƠNG THỨC BẢO VỆ"
case system = "HỆ ĐIỀU HÀNH"
case done = "Kiểm tra hoàn tất"
func getDescription() -> String {
switch self {
case .about:
return "Visafe giúp kiểm tra các nguy hại, mã độc, quảng cáo & theo dõi trên thiết bị của bạn."
case .protect:
return "Đang bật chế độ bảo vệ Visafe"
case .wifi:
return "Đang kiểm tra wifi"
case .protocoll:
return "Đang thiết lập các phương thức bảo vệ"
case .system:
return "Đang kiểm tra phiên bản hệ điều hành"
case .done:
guard let lastScan = CacheManager.shared.getLastScan() else {
return "Lần quét gần nhất vừa mới xong"
}
return "Lần quét gần nhất \(DateFormatter.timeAgoSinceDate(date: lastScan, currentDate: Date()))"
}
}
func getIcon() -> UIImage? {
switch self {
case .about:
return UIImage(named: "ic_scan_visafe")
case .protect:
return UIImage(named: "ic_scan_device")
case .wifi:
return UIImage(named: "ic_scan_wifi")
case .protocoll:
return UIImage(named: "ic_scan_ads")
case .system:
return UIImage(named: "ic_scan_tracking")
case .done:
return UIImage(named: "check_icon")
}
}
static func getAll() -> [ScanDescriptionEnum] {
return [.about, .protect, .wifi, .protocoll, .system, .done]
}
}
class ScanVC: BaseViewController {
var type: ScanDescriptionEnum = .about
@IBOutlet weak var contraintHeight: NSLayoutConstraint!
@IBOutlet weak var descriptionImage: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var imageViewHeight: NSLayoutConstraint!
@IBOutlet weak var imageViewWidth: NSLayoutConstraint!
@IBOutlet weak var desLabelBottom: NSLayoutConstraint!
@IBOutlet weak var errorStackView: UIStackView!
@IBOutlet weak var spacingView: UIView!
@IBOutlet weak var tableview: UITableView!
var scanSuccess: ((Bool, ScanDescriptionEnum) -> Void)?
var scanResult = [String]()
override func viewDidLoad() {
super.viewDidLoad()
configView()
tableview.registerCells(cells: [ScanResultCell.className])
tableview.mj_footer = nil
}
init(type: ScanDescriptionEnum) {
self.type = type
super.init(nibName: ScanVC.className, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
scan()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func configView() {
descriptionImage.image = type.getIcon()
titleLabel.text = type.rawValue
descriptionLabel.text = type.getDescription()
view.backgroundColor = UIColor.clear
contraintHeight.constant = kScreenHeight * 0.7
imageViewHeight.constant = type == .done ? 64: 178
imageViewWidth.constant = type == .done ? 64: 160
}
func scan() {
switch type {
case .protect:
let status = CacheManager.shared.getDohStatus() ?? false
scanSuccess?(DoHNative.shared.isEnabled && status, type)
case .wifi:
checkBotNet()
case .protocoll:
checkBiometric()
case .system:
getiOSVersion()
case .done:
CacheManager.shared.setScanIssueNumber(value: scanResult.count)
if !scanResult.isEmpty {
desLabelBottom.constant = 200
errorStackView.isHidden = false
spacingView.isHidden = false
tableview.dataSource = self
} else {
desLabelBottom.constant = 100
errorStackView.isHidden = true
}
default:
break
}
}
func checkBotNet() {
GroupWorker.checkBotNet {[weak self] (response, error, responseCode) in
guard let self = self else { return }
let botnetDetails = response?.detail ?? []
self.scanSuccess?(botnetDetails.isEmpty, self.type)
}
}
func checkBiometric(){
var error: NSError?
let authenticationContext = LAContext()
// check touch id, faceid enable
if authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
//touchid, faceId enable -> passcode enable
scanSuccess?(true, type)
} else {
//check passcode enable
if authenticationContext.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
scanSuccess?(true, type)
} else {
scanSuccess?(false, type)
}
}
}
func getiOSVersion() {
GroupWorker.getNewestiOSVersion(name: Device.identifier) {[weak self] (model, error, responseCode) in
guard let self = self else { return }
guard let version = model?.version else {
self.scanSuccess?(false, self.type)
return
}
let compare = UIDevice.current.systemVersion.versionCompare(version)
self.scanSuccess?(compare == .orderedSame || compare == .orderedDescending, self.type)
}
}
}
extension ScanVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scanResult.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ScanResultCell.className) as? ScanResultCell else {
return UITableViewCell()
}
cell.bindingData(value: scanResult[indexPath.row])
return cell
}
}
extension String {
func versionCompare(_ otherVersion: String) -> ComparisonResult {
return self.compare(otherVersion, options: .numeric)
}
}
| 32.751244 | 122 | 0.610512 |
e5f91f9c2ebffabe1d461acee7c4229a25b9687b | 2,214 | //
// Assertions.swift
// DL4S
//
// Created by Palle Klewitz on 28.02.19.
// Copyright (c) 2019 - Palle Klewitz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension FileHandle: TextOutputStream {
public func write(_ string: String) {
self.write(string.data(using: .utf8)!)
}
/// The standard output
///
/// This alias can be used as a print target.
public static var stdout: FileHandle {
get {
return FileHandle.standardOutput
}
set {
// noop
}
}
/// The standard error output
///
/// This alias can be used as a print target.
public static var stderr: FileHandle {
get {
return FileHandle.standardError
}
set {
// noop
}
}
}
func weakAssert(_ assertion: @autoclosure () -> Bool, message: String = "", line: Int = #line, function: String = #function, file: String = #file) {
#if DEBUG
if !assertion() {
print("Assertion failed at \(file):\(function):\(line) \(message.count > 0 ? ": \(message)" : "")", to: &FileHandle.stderr)
}
#endif
}
| 33.545455 | 148 | 0.654472 |
294e0174532eeccae3cca88c645e423f9f9356fe | 2,388 | //
// NDYoutubePlayer.swift
// NDYoutubeKit
//
// Created by user on 9/28/17.
// Copyright © 2017 Den. All rights reserved.
//
import Foundation
import AVKit
open class NDYoutubePlayer: AVPlayerLayer {
open var youtubePlayer: AVPlayer!
override public init() {
super.init()
}
public override init(layer: Any) {
super.init(layer: layer)
}
open func playVideo(indentifier: String, quality: NDYouTubeVideoQuality? = nil, isAutoPlay: Bool = true) {
if youtubePlayer != nil {
youtubePlayer.pause()
youtubePlayer.replaceCurrentItem(with: nil)
youtubePlayer = nil
}
NDYoutubeClient.shared.getVideoWithIdentifier(videoIdentifier: indentifier) { [weak self] (video, err) in
guard let video = video else { return }
guard let streamURLs = video.streamURLs else { return }
if let quality = quality {
if let videoString = streamURLs[quality.rawValue] {
self?.youtubePlayer = AVPlayer(url: URL(string: videoString as! String)!)
self?.player = self?.youtubePlayer
if isAutoPlay {
self?.youtubePlayer.play()
}
}
}
else if let videoString = streamURLs[NDYouTubeVideoQuality.NDYouTubeVideoQualityHD720.rawValue] ?? streamURLs[NDYouTubeVideoQuality.NDYouTubeVideoQualityMedium360.rawValue] ?? streamURLs[NDYouTubeVideoQuality.NDYouTubeVideoQualitySmall240.rawValue] {
self?.youtubePlayer = AVPlayer(url: URL(string: videoString as! String)!)
self?.player = self?.youtubePlayer
if isAutoPlay {
self?.youtubePlayer.play()
}
}
}
}
open func stop() {
if youtubePlayer != nil {
youtubePlayer.pause()
youtubePlayer.replaceCurrentItem(with: nil)
youtubePlayer = nil
}
}
open func play() {
if youtubePlayer != nil {
youtubePlayer.play()
}
}
open func pause() {
if youtubePlayer != nil {
youtubePlayer.pause()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 31.84 | 262 | 0.573702 |
d95357e6f22fd1e6ec6591a774fa672f4609f7a4 | 4,472 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TensorFlow
final class InitializerTests: XCTestCase {
func testInitializers() {
let scalar = Tensor<Float>(1)
let matrix: Tensor<Float> = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
let broadcastScalar = Tensor<Float>(broadcasting: 10, rank: 3)
let some4d = Tensor<Float>(shape: [2, 1, 2, 1], scalars: [2, 3, 4, 5])
XCTAssertEqual(ShapedArray(shape: [2, 1, 2, 1], scalars: [2, 3, 4, 5]), some4d.array)
XCTAssertEqual(ShapedArray(shape: [], scalars: [1]), scalar.array)
XCTAssertEqual(ShapedArray(shape: [2, 3], scalars: [1, 2, 3, 4, 5, 6]), matrix.array)
XCTAssertEqual(ShapedArray(shape: [1, 1, 1], scalars: [10]), broadcastScalar.array)
}
func testFactoryInitializers() {
let x = Tensor<Float>(ones: [1, 10])
XCTAssertEqual(ShapedArray(repeating: 1, shape: [1, 10]), x.array)
}
func testNumericInitializers() {
let x = Tensor<Float>(oneHotAtIndices: [0, 2, -1, 1], depth: 3)
XCTAssertEqual(ShapedArray(
shape: [4, 3],
scalars: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]), x.array)
}
func testScalarToTensorConversion() {
let tensor = Tensor<Float>(broadcasting: 42, rank: 4)
XCTAssertEqual([1, 1, 1, 1], tensor.shape)
XCTAssertEqual([42], tensor.scalars)
}
func testArrayConversion() {
let array3D = ShapedArray(repeating: 1.0, shape: [2, 3, 4])
let tensor3D = Tensor(array3D)
XCTAssertEqual(array3D, tensor3D.array)
}
func testDataTypeCast() {
let x = Tensor<Int32>(ones: [5, 5])
let ints = Tensor<Int64>(x)
let floats = Tensor<Float>(x)
let u32s = Tensor<UInt32>(floats)
XCTAssertEqual(ShapedArray(repeating: 1, shape: [5, 5]), ints.array)
XCTAssertEqual(ShapedArray(repeating: 1, shape: [5, 5]), floats.array)
XCTAssertEqual(ShapedArray(repeating: 1, shape: [5, 5]), u32s.array)
}
func testBoolToNumericCast() {
let bools = Tensor<Bool>(shape: [2, 2], scalars: [true, false, true, false])
let ints = Tensor<Int64>(bools)
let floats = Tensor<Float>(bools)
let i8s = Tensor<Int8>(bools)
XCTAssertEqual(ShapedArray(shape: [2, 2], scalars: [1, 0, 1, 0]), ints.array)
XCTAssertEqual(ShapedArray(shape: [2, 2], scalars: [1, 0, 1, 0]), floats.array)
XCTAssertEqual(ShapedArray(shape: [2, 2], scalars: [1, 0, 1, 0]), i8s.array)
}
func testOrthogonalShapesValues() {
for shape in [[10, 10], [10, 9, 8], [100, 5, 5], [50, 40], [3, 3, 32, 64]] {
// Check the shape.
var t = Tensor<Float>(orthogonal: TensorShape(shape))
XCTAssertEqual(shape, t.shape.dimensions)
// Check orthogonality by computing the inner product.
t = t.reshaped(to: [t.shape.dimensions.dropLast().reduce(1, *), t.shape[t.rank - 1]])
if t.shape[0] > t.shape[1] {
let eye = Raw.diag(diagonal: Tensor<Float>(ones: [t.shape[1]]))
assertEqual(eye, matmul(t.transposed(), t), accuracy: 1e-5)
} else {
let eye = Raw.diag(diagonal: Tensor<Float>(ones: [t.shape[0]]))
assertEqual(eye, matmul(t, t.transposed()), accuracy: 1e-5)
}
}
}
static var allTests = [
("testInitializers", testInitializers),
("testFactoryInitializers", testFactoryInitializers),
("testNumericInitializers", testNumericInitializers),
("testScalarToTensorConversion", testScalarToTensorConversion),
("testArrayConversion", testArrayConversion),
("testDataTypeCast", testDataTypeCast),
("testBoolToNumericCast", testBoolToNumericCast),
("testOrthogonalShapesValues", testOrthogonalShapesValues)
]
}
| 43.417476 | 97 | 0.617174 |
38deb279befeac9e4e087d57fb24ada78d52510b | 1,259 | //
// Copyright © FINN.no AS, Inc. All rights reserved.
//
public struct ContractActionViewModel {
public let identifier: String?
public let title: String?
public let subtitle: String?
public let description: String?
public let strings: [String]
public let buttonTitle: String
public let buttonUrl: URL
public let videoLink: VideoLink?
public init(
identifier: String?,
title: String? = nil,
subtitle: String? = nil,
description: String? = nil,
strings: [String],
buttonTitle: String,
buttonUrl: URL,
videoLink: VideoLink? = nil
) {
self.identifier = identifier
self.title = title
self.subtitle = subtitle
self.description = description
self.strings = strings
self.buttonTitle = buttonTitle
self.buttonUrl = buttonUrl
self.videoLink = videoLink
}
public struct VideoLink {
public let title: String
public let videoUrl: URL
public let thumbnailUrl: URL
public init(title: String, videoUrl: URL, thumbnailUrl: URL) {
self.title = title
self.videoUrl = videoUrl
self.thumbnailUrl = thumbnailUrl
}
}
}
| 26.787234 | 70 | 0.610008 |
01eec39ff37ef28a47e570ceb482e46db3e1f85d | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B{init(){{
}
class n{
{}enum b<T where a=b{
struct A{
class b{
let f=B
let a=
b
| 18.214286 | 87 | 0.717647 |
e537e8a7266e85eb8d5636d9194fde7a92f1c67d | 781 | //
// StateHistoryCollectionViewCell.swift
// Meet
//
// Created by Benjamin Encz on 12/1/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import UIKit
class StateHistoryCollectionViewCell: UICollectionViewCell {
var label: UILabel!
var text: String = "" {
didSet {
label.text = text
label.sizeToFit()
label.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
label = UILabel()
label.font = label.font.withSize(18)
addSubview(label)
backgroundColor = UIColor.red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 21.108108 | 77 | 0.604353 |
4afb1b1c987c211f04b62b88c3027adcf1a3f636 | 15,658 | import UIKit
import WebKit
import SnapKit
enum TapType {
case member(MemberModel)
case memberAvatarLongPress(MemberModel)
case reply(CommentModel)
case node(NodeModel)
case imageURL(String)
case image(UIImage)
case webpage(URL)
case topic(String)
case foreword(CommentModel)
}
class TopicDetailHeaderView: UIView {
enum HTMLTag: CaseIterable {
case h1, h2, h3, pre, bigger, small, subtle, topicContent
var key: String {
switch self {
case .h1: return "{h1FontSize}"
case .h2: return "{h2FontSize}"
case .h3: return "{h3FontSize}"
case .pre: return "{preFontSize}"
case .bigger: return "{biggerFontSize}"
case .small: return "{smallFontSize}"
case .subtle: return "{subtleFontSize}"
case .topicContent: return "{topicContentFontSize}"
}
}
var fontSize: Int {
switch self {
case .h1: return 16
case .h2: return 16
case .h3: return 16
case .pre: return 13
case .bigger: return 16
case .small: return 11
case .subtle: return 12
case .topicContent: return 13
}
}
}
struct Metric {
static let replyLabelHeight: CGFloat = 45
static let margin: CGFloat = 15
}
private lazy var topContainerView: UIView = {
let view = UIView()
return view
}()
private lazy var avatarView: UIImageView = {
let view = UIImageView()
view.isUserInteractionEnabled = true
view.setCornerRadius = 5
return view
}()
private lazy var usernameLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 15)
return view
}()
private lazy var timeLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 11)
view.textColor = UIColor.hex(0xCCCCCC)
return view
}()
private lazy var nodeLabel: UIInsetLabel = {
let view = UIInsetLabel()
view.font = UIFont.systemFont(ofSize: 13)
view.textColor = UIColor.hex(0x999999)
view.backgroundColor = UIColor.hex(0xf5f5f5)
view.contentInsets = UIEdgeInsets(top: 2, left: 3, bottom: 2, right: 3)
view.isUserInteractionEnabled = true
return view
}()
private lazy var titleLabel: UILabel = {
let view = UILabel()
view.numberOfLines = 0
view.font = UIFont.boldSystemFont(ofSize: 17)
view.clickCopyable = true
view.isUserInteractionEnabled = true
view.font = .preferredFont(forTextStyle: .headline)
if #available(iOS 10, *) {
view.adjustsFontForContentSizeCategory = true
}
return view
}()
private lazy var webView: WKWebView = {
let view = WKWebView()
view.scrollView.isScrollEnabled = false
view.isOpaque = false
view.navigationDelegate = self
view.scrollView.scrollsToTop = false
return view
}()
private lazy var replyLabelContainerView: UIView = {
let view = UIView()
view.backgroundColor = ThemeStyle.style.value.bgColor
return view
}()
private lazy var replyLabel: UIInsetLabel = {
let view = UIInsetLabel()
view.text = "全部回复"
view.contentInsetsLeft = Metric.margin
view.contentInsetsTop = Metric.margin
view.font = UIFont.systemFont(ofSize: 13)
view.backgroundColor = .clear//ThemeStyle.style.value.bgColor
view.textColor = #colorLiteral(red: 0.5333333333, green: 0.5333333333, blue: 0.5333333333, alpha: 1)
return view
}()
private var htmlHeight: CGFloat = 0 {
didSet {
updateWebViewHeight()
}
}
private var webViewConstraint: Constraint?
public var webLoadComplete: Action?
public var tapHandle: ((_ type: TapType) -> Void)?
public var userAvatar: UIImage? {
return avatarView.image
}
init() {
super.init(frame: CGRect(x: 0, y: 0, width: Constants.Metric.screenWidth, height: 130))
backgroundColor = .white
topContainerView.addSubviews(
avatarView,
usernameLabel,
timeLabel,
nodeLabel,
titleLabel
)
addSubviews(
topContainerView,
webView,
replyLabelContainerView
)
replyLabelContainerView.addSubview(replyLabel)
setupConstraints()
setupAction()
webView.scrollView.rx
.observe(CGSize.self, "contentSize")
.filterNil()
.distinctUntilChanged()
.filter { $0.height >= 100 }
.subscribeNext { [weak self] size in
self?.htmlHeight = size.height
}.disposed(by: rx.disposeBag)
NotificationCenter.default.rx
.notification(UIContentSizeCategory.didChangeNotification)
.subscribeNext { [weak self] _ in
self?.updateWebViewHeight()
}.disposed(by: rx.disposeBag)
}
private func updateWebViewHeight() {
webViewConstraint?.update(offset: htmlHeight)
height = titleLabel.bottom + htmlHeight + Metric.margin + Metric.replyLabelHeight
webLoadComplete?()
}
let avatarTapGesture = UITapGestureRecognizer()
let nodeTapGesture = UITapGestureRecognizer()
private func setupAction() {
// avatarView.addGestureRecognizer(avatarTapGesture)
//
// nodeLabel.addGestureRecognizer(nodeTapGesture)
//
// avatarTapGesture.rx
// .event
// .subscribeNext { [weak self] _ in
// guard let member = self?.topic?.member else { return }
// self?.tapHandle?(.member(member))
// }.disposed(by: rx.disposeBag)
//
// nodeTapGesture.rx
// .event
// .subscribeNext { [weak self] _ in
// guard let node = self?.topic?.node else { return }
// self?.tapHandle?(.node(node))
// }.disposed(by: rx.disposeBag)
ThemeStyle.style.asObservable()
.subscribeNext { [weak self] theme in
self?.backgroundColor = theme.cellBackgroundColor
self?.titleLabel.textColor = theme.titleColor
self?.replyLabelContainerView.backgroundColor = theme.bgColor
self?.usernameLabel.textColor = theme.titleColor
self?.nodeLabel.backgroundColor = theme == .day ? UIColor.hex(0xf5f5f5) : theme.bgColor
self?.timeLabel.textColor = theme.dateColor
}.disposed(by: rx.disposeBag)
UIMenuController.shared.menuItems = [UIMenuItem(title: "Base64 解码", action: #selector(self.base64Decode))]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupConstraints() {
topContainerView.snp.makeConstraints {
$0.top.equalToSuperview()
if #available(iOS 11.0, *) {
$0.left.equalTo(replyLabelContainerView.safeAreaLayoutGuide.snp.left)
$0.right.equalTo(replyLabelContainerView.safeAreaLayoutGuide.snp.right)
} else {
$0.left.right.equalToSuperview()
}
}
avatarView.snp.makeConstraints {
$0.left.top.equalToSuperview().inset(Metric.margin)
$0.size.equalTo(35)
}
usernameLabel.snp.makeConstraints {
$0.left.equalTo(avatarView.snp.right).offset(10)
$0.top.equalTo(avatarView).offset(1)
}
timeLabel.snp.makeConstraints {
$0.left.equalTo(usernameLabel)
$0.right.equalTo(nodeLabel).priority(.high)
$0.bottom.equalTo(avatarView).inset(1)
}
nodeLabel.snp.makeConstraints {
$0.top.right.equalToSuperview().inset(Metric.margin)
}
titleLabel.snp.makeConstraints {
$0.right.equalTo(timeLabel)
$0.left.equalTo(avatarView)
$0.top.equalTo(avatarView.snp.bottom).offset(Metric.margin)
}
webView.snp.makeConstraints {
$0.top.equalTo(titleLabel.snp.bottom).offset(Metric.margin)
$0.left.right.equalToSuperview()
webViewConstraint = $0.height.equalTo(0).constraint
}
replyLabelContainerView.snp.makeConstraints {
$0.top.equalTo(webView.snp.bottom)
$0.left.right.equalToSuperview()
$0.height.equalTo(Metric.replyLabelHeight)
}
replyLabel.snp.makeConstraints {
$0.bottom.top.equalToSuperview()
if #available(iOS 11.0, *) {
$0.left.equalTo(replyLabelContainerView.safeAreaLayoutGuide.snp.left)
$0.right.equalTo(replyLabelContainerView.safeAreaLayoutGuide.snp.right)
} else {
$0.left.right.equalToSuperview()
}
}
}
var topic: TopicModel? {
didSet {
guard let `topic` = topic else { return }
guard let user = topic.member else { return }
avatarView.setImage(urlString: user.avatarSrc, placeholder: #imageLiteral(resourceName: "avatarRect"))
usernameLabel.text = user.username
titleLabel.text = topic.title
timeLabel.text = topic.publicTime
timeLabel.isHidden = topic.publicTime.isEmpty
do {
if let filePath = Bundle.main.path(forResource: "style", ofType: "css"),
let themeFilePath = Bundle.main.path(forResource: ThemeStyle.style.value.cssFilename, ofType: "") {
var cssString = try String(contentsOfFile: filePath)
let scale = Preference.shared.webViewFontScale * 0.1 + 1.05
for tag in HTMLTag.allCases {
let fontpx = scale * Float(tag.fontSize)
cssString = cssString.replacingOccurrences(of: tag.key, with: "\(fontpx)px")
}
let themeCssString = try String(contentsOfFile: themeFilePath)
cssString += themeCssString
let head = "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"><style>\(cssString)</style></head>"
let body = "<body><div id=\"Wrapper\">\(topic.content)</div></body>"
let html = "<html>\(head)\(body)</html>"
webView.loadHTMLString(html, baseURL: URL(string: "https://"))
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
} catch {
HUD.showTest(error.localizedDescription)
log.error("CSS 加载失败")
}
guard let node = topic.node else { return }
nodeLabel.text = node.title
nodeLabel.isHidden = node.title.isEmpty
}
}
@objc func base64Decode() {
webView.evaluateJavaScript("window.getSelection().toString();") { res, err in
if let error = err {
HUD.showError(error)
}
guard let selectionText = (res as? String)?.trimmed else { return }
// let matchResult = selectionText.isMatch(regEx: "(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)")
// guard matchResult else {
// HUD.showError("所选内容不是 Base64")
// return
// }
guard let base64Data = Data(base64Encoded: selectionText),
let result = String(data: base64Data, encoding: .utf8) else {
HUD.showError("解码失败")
return
}
let alertC = UIAlertController(title: "Base64 解码结果", message: result, preferredStyle: .alert)
alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
alertC.addAction(UIAlertAction(title: "复制", style: .default, handler: { action in
UIPasteboard.general.string = result
HUD.showSuccess("已复制到剪切板")
}))
var currentVC = AppWindow.shared.window.rootViewController?.currentViewController()
if currentVC == nil {
currentVC = AppWindow.shared.window.rootViewController
}
currentVC?.present(alertC, animated: true, completion: nil)
}
}
var replyTitle: String = "全部回复" {
didSet {
replyLabel.text = replyTitle
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: touch.view)
// YYTextEffectWindow 导致无法处理点击事件, 使用 touch 处理
let avatarViewTap = avatarView.frame.contains(location)
if avatarViewTap, let member = topic?.member {
tapHandle?(.member(member))
return
}
let nodeLabelTap = nodeLabel.frame.contains(location)
if nodeLabelTap, let node = topic?.node {
tapHandle?(.node(node))
return
}
let titleLabelTap = titleLabel.frame.contains(location)
if titleLabelTap {
titleLabel.showCopyMenu()
}
}
}
extension TopicDetailHeaderView: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
// 定位到因 YYText 的 bug, 链接长按事件, 会导致白屏, 禁止链接 Touch Callout 事件
webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';")
webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] result, error in
guard let htmlHeight = result as? CGFloat else { return }
self?.htmlHeight = htmlHeight
}
let script = """
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; ++i) {
var img = imgs[i];
if (img.parentNode.tagName != "A") {
img.onclick = function () {
window.location.href = 'v2ex-image:' + this.src;
}
}
}
"""
webView.evaluateJavaScript(script, completionHandler: nil)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, url.scheme == "v2ex-image" {
let src = url.absoluteString.deleteOccurrences(target: "v2ex-image:")
tapHandle?(.imageURL(src))
decisionHandler(.cancel)
return
}
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
let urlString = url.absoluteString
log.info(url, urlString)
clickCommentLinkHandle(urlString: urlString)
decisionHandler(.cancel)
}
}
| 35.586364 | 184 | 0.572679 |
eb21c6cedf04e612544b82df45031ca8093e5b57 | 1,510 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 Apple 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 FMCore
/**
Defines expectations around whether an action or action group is required.
URL: http://hl7.org/fhir/action-required-behavior
ValueSet: http://hl7.org/fhir/ValueSet/action-required-behavior
*/
public enum ActionRequiredBehavior: String, FHIRPrimitiveType {
/// An action with this behavior must be included in the actions processed by the end user; the end user SHALL NOT
/// choose not to include this action.
case must = "must"
/// An action with this behavior may be included in the set of actions processed by the end user.
case could = "could"
/// An action with this behavior must be included in the set of actions processed by the end user, unless the end
/// user provides documentation as to why the action was not included.
case mustUnlessDocumented = "must-unless-documented"
}
| 36.829268 | 115 | 0.743046 |
ebc3f65b348a3e0a857fbfb153cdf57ced22e183 | 345 | //
// TraktWatchedSeason.swift
// TraktKit
//
// Created by Maximilian Litteral on 4/13/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct TraktWatchedSeason: Codable {
// Extended: Min
public let number: Int // Season number
public let episodes: [TraktWatchedEpisodes]
}
| 20.294118 | 62 | 0.707246 |
4b7ae5e8db94225e9cff66c98143fbbf1eef22f7 | 376 | import UIKit
public extension UIFont {
var bold: UIFont {
withTraits(traits: .traitBold)
}
var italic: UIFont {
withTraits(traits: .traitItalic)
}
// MARK: - Private
private func withTraits(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
UIFont(descriptor: fontDescriptor.withSymbolicTraits(traits)!, size: 0)
}
}
| 19.789474 | 80 | 0.651596 |
d926b9f4281b84a91eadaa6e7f4bbdbeae76edf8 | 2,272 | //
// Created by Max Desiatov on 01/10/2021.
//
@testable import Driver
import SnapshotTesting
import XCTest
final class JSCodegenTests: XCTestCase {
func testFuncDecl() {
// FIXME: `Bool` and `String` declarations should be picked up from stdlib
assertJSSnapshot(
"""
enum Bool {}
struct String {}
func f(condition: Bool) -> String {
if condition {
"true"
} else {
"false"
}
}
"""
)
assertJSSnapshot(
"""
enum Bool {}
struct String {}
let StringAlias: Type = String
func f(condition: Bool) -> StringAlias {
if condition {
"true"
} else {
"false"
}
}
"""
)
}
func testTypeFuncDecl() {
// FIXME: `Bool`, `String`, and `Int` declarations should be picked up from stdlib
assertJSSnapshot(
"""
enum Bool {}
struct String {}
struct Int {}
func stringOrInt(x: Bool) -> Type {
if x {
String
} else {
Int
}
}
"""
)
}
func testStructDecl() {
// FIXME: `Int` declaration should be picked up from stdlib
assertJSSnapshot(
"""
struct Int {}
struct Size {
let width: Int
let height: Int
func multiply(x: Int, y: Int) -> Int { x }
}
"""
)
assertJSSnapshot(
"""
struct Int {}
let IntAlias: Type = Int
struct Size {
let width: Int
let height: IntAlias
func multiply(x: IntAlias, y: Int) -> Int { x }
}
"""
)
}
func testStructLiteral() {
// FIXME: `Int` declaration should be picked up from stdlib
assertJSSnapshot(
"""
struct Int {}
struct S { let a: Int }
func f() -> S {
S {a: 42}
}
"""
)
}
func testTuple() {
assertJSSnapshot(
// FIXME: declaration should be picked up from stdlib
"""
struct Int32 {}
struct String {}
enum Bool {}
func f() -> (Int32, String, Bool) {
(42, "foo", false)
}
func f1() -> Int32 {
f().0
}
"""
)
}
}
| 17.889764 | 86 | 0.46875 |
621be373e59654947ce39205f0bf2593307a4799 | 3,598 | //
// UIView+utils.swift
// FBSnapshotTestCase
//
// Created by lzc1104 on 2018/4/26.
//
import Foundation
extension UIColor {
convenience init(hex : Int , alpha : CGFloat) {
let r = CGFloat((hex >> 16) & 0xff) / 255.0
let g = CGFloat(hex >> 8 & 0xff) / 255.0
let b = CGFloat(hex & 0xff) / 255.0
self.init(red: r, green: g, blue: b, alpha: alpha)
}
}
extension UIImage {
convenience init?(pkName: String) {
self.init(named: pkName, in: Bundle.privateBd, compatibleWith: nil)
}
}
extension Bundle {
private class _PrivateClass {
}
static var privateBd: Bundle {
let pbd = Bundle.init(for: _PrivateClass.self)
let url = pbd.url(forResource: "HuayingStatefulViewMachine", withExtension: "bundle")
let bd = Bundle.init(url: url!)
return bd!
}
}
extension UIView {
@discardableResult
func centerEqual(to target: UIView) -> UIView {
let constraint = NSLayoutConstraint.init(
item: self,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: target,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0
)
let constraint1 = NSLayoutConstraint.init(
item: self,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: target,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0
)
target.addConstraints([constraint] + [constraint1])
return target
}
@discardableResult
func heightCons(_ constant: CGFloat) -> UIView {
let heightConstraint = NSLayoutConstraint.init(
item: self,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: constant
)
self.addConstraint(heightConstraint)
return self
}
@discardableResult
func widthCons(_ constant: CGFloat) -> UIView {
let heightConstraint = NSLayoutConstraint.init(
item: self,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: constant
)
self.addConstraint(heightConstraint)
return self
}
@discardableResult
func equalAttribute(to target: UIView , attribute: NSLayoutAttribute) -> UIView {
let cons = NSLayoutConstraint.init(
item: self,
attribute: attribute,
relatedBy: NSLayoutRelation.equal,
toItem: target,
attribute: attribute,
multiplier: 1,
constant: 0
)
self.addConstraint(cons)
return self
}
@discardableResult
func equalEdge(to target: UIView) -> UIView {
return self.equalAttribute(to: target, attribute: NSLayoutAttribute.leading)
.equalAttribute(to: target, attribute: NSLayoutAttribute.trailing)
.equalAttribute(to: target, attribute: NSLayoutAttribute.top)
.equalAttribute(to: target, attribute: NSLayoutAttribute.bottom)
}
}
let _isiPoneX: Bool = UIScreen.main.bounds.height == 812
func isiPhoneX() -> Bool {
return _isiPoneX
}
| 28.784 | 93 | 0.595887 |
fb723fc83a1e96494a9b58cc22589f883e868f05 | 7,782 | //
// CompatibleAnimationView.swift
// Lottie_iOS
//
// Created by Tyler Hedrick on 3/6/19.
//
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst)
import UIKit
/// An Objective-C compatible wrapper around Lottie's Animation class.
/// Use in tandem with CompatibleAnimationView when using Lottie in Objective-C
@objc
public final class CompatibleAnimation: NSObject {
@objc
static func named(_ name: String) -> CompatibleAnimation {
return CompatibleAnimation(name: name)
}
@objc
public init(name: String, bundle: Bundle = Bundle.main) {
self.name = name
self.bundle = bundle
super.init()
}
internal var animation: Animation? {
return Animation.named(name, bundle: bundle)
}
// MARK: Private
private let name: String
private let bundle: Bundle
}
/// An Objective-C compatible wrapper around Lottie's AnimationView.
@objc
public final class CompatibleAnimationView: UIView {
@objc
init(compatibleAnimation: CompatibleAnimation) {
animationView = AnimationView(animation: compatibleAnimation.animation)
self.compatibleAnimation = compatibleAnimation
super.init(frame: .zero)
commonInit()
}
@objc
public override init(frame: CGRect) {
animationView = AnimationView()
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Public
@objc
public var compatibleAnimation: CompatibleAnimation? {
didSet {
animationView.animation = compatibleAnimation?.animation
}
}
@objc
public var loopAnimationCount: CGFloat = 0 {
didSet {
animationView.loopMode = loopAnimationCount == -1 ? .loop : .repeat(Float(loopAnimationCount))
}
}
@objc
public override var contentMode: UIView.ContentMode {
set { animationView.contentMode = newValue }
get { return animationView.contentMode }
}
@objc
public var shouldRasterizeWhenIdle: Bool {
set { animationView.shouldRasterizeWhenIdle = newValue }
get { return animationView.shouldRasterizeWhenIdle }
}
@objc
public var currentProgress: CGFloat {
set { animationView.currentProgress = newValue }
get { return animationView.currentProgress }
}
@objc
public var currentTime: TimeInterval {
set { animationView.currentTime = newValue }
get { return animationView.currentTime }
}
@objc
public var currentFrame: CGFloat {
set { animationView.currentFrame = newValue }
get { return animationView.currentFrame }
}
@objc
public var realtimeAnimationFrame: CGFloat {
return animationView.realtimeAnimationFrame
}
@objc
public var realtimeAnimationProgress: CGFloat {
return animationView.realtimeAnimationProgress
}
@objc
public var animationSpeed: CGFloat {
set { animationView.animationSpeed = newValue }
get { return animationView.animationSpeed }
}
@objc
public var respectAnimationFrameRate: Bool {
set { animationView.respectAnimationFrameRate = newValue }
get { return animationView.respectAnimationFrameRate }
}
@objc
public var isAnimationPlaying: Bool {
return animationView.isAnimationPlaying
}
@objc
public func play() {
play(completion: nil)
}
@objc
public func play(completion: ((Bool) -> Void)?) {
animationView.play(completion: completion)
}
@objc
public func play(
fromProgress: CGFloat,
toProgress: CGFloat,
completion: ((Bool) -> Void)? = nil)
{
animationView.play(
fromProgress: fromProgress,
toProgress: toProgress,
loopMode: nil,
completion: completion)
}
@objc
public func play(
fromFrame: CGFloat,
toFrame: CGFloat,
completion: ((Bool) -> Void)? = nil)
{
animationView.play(
fromFrame: fromFrame,
toFrame: toFrame,
loopMode: nil,
completion: completion)
}
@objc
public func play(
fromMarker: String,
toMarker: String,
completion: ((Bool) -> Void)? = nil)
{
animationView.play(
fromMarker: fromMarker,
toMarker: toMarker,
completion: completion)
}
@objc
public func stop() {
animationView.stop()
}
@objc
public func pause() {
animationView.pause()
}
@objc
public func reloadImages() {
animationView.reloadImages()
}
@objc
public func forceDisplayUpdate() {
animationView.forceDisplayUpdate()
}
@objc
public func getValue(
for keypath: CompatibleAnimationKeypath,
atFrame: CGFloat) -> Any?
{
return animationView.getValue(
for: keypath.animationKeypath,
atFrame: atFrame)
}
@objc
public func logHierarchyKeypaths() {
animationView.logHierarchyKeypaths()
}
@objc
public func setColorValue(_ color: UIColor, forKeypath keypath: CompatibleAnimationKeypath)
{
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
let colorSpace: CGColorSpace
if #available(iOS 9.3, *) {
colorSpace = CGColorSpace.init(name: CGColorSpace.displayP3) ?? CGColorSpaceCreateDeviceRGB()
} else {
colorSpace = CGColorSpaceCreateDeviceRGB()
}
let convertedColor = color.cgColor.converted(to: colorSpace, intent: .defaultIntent, options: nil)
if let components = convertedColor?.components, components.count == 4 {
red = components[0]
green = components[1]
blue = components[2]
alpha = components[3]
} else {
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
}
let valueProvider = ColorValueProvider(Color(r: Double(red), g: Double(green), b: Double(blue), a: Double(alpha)))
animationView.setValueProvider(valueProvider, keypath: keypath.animationKeypath)
}
@objc
public func getColorValue(for keypath: CompatibleAnimationKeypath, atFrame: CGFloat) -> UIColor?
{
let value = animationView.getValue(for: keypath.animationKeypath, atFrame: atFrame)
guard let colorValue = value as? Color else {
return nil;
}
return UIColor(red: CGFloat(colorValue.r), green: CGFloat(colorValue.g), blue: CGFloat(colorValue.b), alpha: CGFloat(colorValue.a))
}
@objc
public func addSubview(
_ subview: AnimationSubview,
forLayerAt keypath: CompatibleAnimationKeypath)
{
animationView.addSubview(
subview,
forLayerAt: keypath.animationKeypath)
}
@objc
public func convert(
rect: CGRect,
toLayerAt keypath: CompatibleAnimationKeypath?)
-> CGRect
{
return animationView.convert(
rect,
toLayerAt: keypath?.animationKeypath) ?? .zero
}
@objc
public func convert(
point: CGPoint,
toLayerAt keypath: CompatibleAnimationKeypath?)
-> CGPoint
{
return animationView.convert(
point,
toLayerAt: keypath?.animationKeypath) ?? .zero
}
@objc
public func progressTime(forMarker named: String) -> CGFloat {
return animationView.progressTime(forMarker: named) ?? 0
}
@objc
public func frameTime(forMarker named: String) -> CGFloat {
return animationView.frameTime(forMarker: named) ?? 0
}
// MARK: Private
private let animationView: AnimationView
private func commonInit() {
translatesAutoresizingMaskIntoConstraints = false
setUpViews()
}
private func setUpViews() {
animationView.translatesAutoresizingMaskIntoConstraints = false
addSubview(animationView)
animationView.topAnchor.constraint(equalTo: topAnchor).isActive = true
animationView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
animationView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
animationView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
#endif
| 24.31875 | 135 | 0.696865 |
8747e23f4556d99a6abbb922f62bcae195aa64df | 677 | final class TrafficButtonArea: AvailableArea {
override func isAreaAffectingView(_ other: UIView) -> Bool {
return !other.trafficButtonAreaAffectDirections.isEmpty
}
override func addAffectingView(_ other: UIView) {
let ov = other.trafficButtonAreaAffectView
let directions = ov.trafficButtonAreaAffectDirections
addConstraints(otherView: ov, directions: directions)
}
override func notifyObserver() {
MWMTrafficButtonViewController.updateAvailableArea(areaFrame)
}
}
extension UIView {
@objc var trafficButtonAreaAffectDirections: MWMAvailableAreaAffectDirections { return [] }
var trafficButtonAreaAffectView: UIView { return self }
}
| 30.772727 | 93 | 0.784343 |
8a5e33cd3998a33fd613e2382b4fc6b523c1af72 | 2,381 | //
// License.swift
//
//
// Created by Gray Campbell on 4/15/20.
//
import Foundation
// MARK: Properties & Initializers
/// A `License` that contains text.
public struct License: Equatable {
// MARK: Properties
/// The license text.
public let text: String
// MARK: Initializers
/// Initializes and returns a new `License`.
///
/// - Parameter text: The license text.
public init(text: String) {
self.text = text
}
}
// MARK: - Licenses
public extension License {
/// MIT License
static let MIT = License(text:
"""
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.
"""
)
/// Apache 2.0 License
static let apache2 = License(text:
"""
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.
"""
)
}
| 39.032787 | 468 | 0.688366 |
fee4a7a47a69ca56976224324a50915f0f031c00 | 2,438 | //
// ColorObservationTests.swift
// ColorSet_iOSTests
//
// Created by Kazuya Ueoka on 2019/04/21.
//
import XCTest
@testable import ColorSet_iOS
final class ColorObservationTests: XCTestCase {
var backgroundColor: ColorObservable<UIColor>!
var textColor: ColorObservable<UIColor>!
override func setUp() {
super.setUp()
backgroundColor = .init(.white)
textColor = .init(.black)
}
func testEqual() {
XCTContext.runActivity(named: "difference") { (_) in
let observationBag = ColorObservationBag()
let observationBackground = backgroundColor.subscribe { (_) in }
let observationText = textColor.subscribe { (_) in }
observationBag.add(observationBackground)
observationBag.add(observationText)
XCTAssertEqual(observationBackground, observationBag.observations.first)
XCTAssertNotEqual(observationText, observationBag.observations.first)
}
XCTContext.runActivity(named: "same") { (_) in
let observationBackground1 = backgroundColor.subscribe { (_) in }
let view = UIView()
let observationBackground2 = backgroundColor.bind(to: view, keyPath: \.backgroundColor)
XCTAssertNotEqual(observationBackground1, observationBackground2)
}
}
func testAppendTo() {
let observationBag = ColorObservationBag()
XCTAssertEqual(observationBag.observations.count, 0)
backgroundColor.subscribe { (_) in }.append(to: observationBag)
XCTAssertEqual(observationBag.observations.count, 1)
let view = UIView()
backgroundColor.bind(to: view, keyPath: \.backgroundColor).append(to: observationBag)
XCTAssertEqual(observationBag.observations.count, 2)
}
func testUnregister() {
let observationBag = ColorObservationBag()
let view = UIView()
let observation = backgroundColor.bind(to: view, keyPath: \.backgroundColor)
observationBag.add(observation)
XCTAssertEqual(view.backgroundColor, .white)
backgroundColor.accept(.red)
XCTAssertEqual(view.backgroundColor, .red)
backgroundColor.accept(.blue)
XCTAssertEqual(view.backgroundColor, .blue)
// perform unregister
observation.unregister()
backgroundColor.accept(.yellow)
XCTAssertEqual(view.backgroundColor, .blue)
}
}
| 35.852941 | 99 | 0.673503 |
38f226288c98a3df5fca96ff29054ca0406b82a7 | 10,153 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
// MARK: InferenceViewControllerDelegate Method Declarations
protocol InferenceViewControllerDelegate {
/**
This method is called when the user changes the stepper value to update number of threads used for inference.
*/
func didChangeThreadCount(to count: Int)
}
/**This is used to represent the display name of a gesture and whether or not it is part of the classes on which the model is trained.
*/
struct GestureDisplay {
let name: String
let isEnabled: Bool
}
class InferenceViewController: UIViewController {
// MARK: Information to display
private enum InferenceInfo: Int, CaseIterable {
case Resolution
case Crop
case InferenceTime
func displayString() -> String {
var toReturn = ""
switch self {
case .Resolution:
toReturn = "Resolution"
case .Crop:
toReturn = "Crop"
case .InferenceTime:
toReturn = "Inference Time"
}
return toReturn
}
}
// MARK: Storyboard Outlets
@IBOutlet weak var gestureCollectionViewHeight: NSLayoutConstraint!
@IBOutlet weak var stepperView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var threadStepper: UIStepper!
@IBOutlet weak var stepperValueLabel: UILabel!
@IBOutlet weak var gestureCollectionView: UICollectionView!
@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
// MARK: Constants
private var normalCellHeight: CGFloat {
return lableHeight + labeltopSpacing * 2
}
private let lableHeight: CGFloat = 17.0
private let labeltopSpacing: CGFloat = 5.0
private let tableViewCollectionViewVerticalSpacing: CGFloat = 27.0
private let separatorCellHeight: CGFloat = 42.0
private let bottomSpacing: CGFloat = 21.0
private let minThreadCount = 1
private let bottomSheetButtonDisplayHeight: CGFloat = 44.0
private let infoTextColor = UIColor.black
private let lightTextInfoColor = UIColor(displayP3Red: 117.0/255.0, green: 117.0/255.0, blue: 117.0/255.0, alpha: 1.0)
private let infoFont = UIFont.systemFont(ofSize: 14.0, weight: .regular)
private let highlightedFont = UIFont.systemFont(ofSize: 14.0, weight: .medium)
private let collectionViewPadding: CGFloat = 15.0
private let heightPadding: CGFloat = 1.0
private let itemsInARow: CGFloat = 4.0
private let imageInset: CGFloat = 8.0
private let stepperSuperViewHeight: CGFloat = 53.0
var gestures: [GestureDisplay] = []
var result: Result?
var collectionViewHeight: CGFloat {
get {
let collectionViewWidth = self.view.bounds.size.width - (2 * collectionViewPadding)
let itemWidth = (collectionViewWidth - ((itemsInARow - 1) * collectionViewPadding)) / itemsInARow
return (itemWidth * 2.0) + collectionViewPadding + heightPadding
}
}
// MARK: Instance Variables
var inferenceResult: Result? = nil
var wantedInputWidth: Int = 0
var wantedInputHeight: Int = 0
var resolution: CGSize = CGSize.zero
var maxResults: Int = 0
var threadCountLimit: Int = 0
var currentThreadCount: Int = 0
private var highlightedRow = -1
// MARK: Delegate
var delegate: InferenceViewControllerDelegate?
// MARK: Computed properties
var collapsedHeight: CGFloat {
return collectionViewHeight + bottomSheetButtonDisplayHeight + tableViewCollectionViewVerticalSpacing
}
private var tableViewHeight: CGFloat {
return CGFloat(InferenceInfo.allCases.count - 1) * normalCellHeight + lableHeight + separatorCellHeight + labeltopSpacing
}
override func viewDidLoad() {
super.viewDidLoad()
// Set up stepper
threadStepper.isUserInteractionEnabled = true
threadStepper.maximumValue = Double(threadCountLimit)
threadStepper.minimumValue = Double(minThreadCount)
threadStepper.value = Double(currentThreadCount)
gestureCollectionView.reloadData()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
gestureCollectionViewHeight.constant = collectionViewHeight
tableViewHeightConstraint.constant = tableViewHeight
}
func expandedHeight() -> CGFloat {
return collapsedHeight + tableViewHeight + stepperSuperViewHeight
}
// MARK: Gesture Highlight Methods
/**
Displays the gestures specified in the parameter.
*/
func displayGestures(gestures: [GestureDisplay]) {
self.gestures = gestures
highlightGesture(with: -1)
}
/**
Refreshes the results in collectionview by highlighting currently identified gesture.
*/
func refreshResults() {
highlightIdentifiedGesture()
self.tableView.reloadData()
}
/**Highlights the currently identified gesture by mapping the name of top inference with the gestures that are displayed.
*/
private func highlightIdentifiedGesture() {
guard let inferences = result?.inferences, inferences.count > 0 else {
return
}
guard let index = self.gestures.index(where: {$0.name.stringByTrimmingWhiteSpace() == inferences[0].className}) else {
return
}
highlightGesture(with: index)
}
/**Highlights the currently identified gesture.
*/
func highlightGesture(with index: Int) {
self.highlightedRow = index
self.gestureCollectionView.reloadData()
}
// MARK: Buttion Actions
/**
Delegate the change of number of threads to View Controller and change the stepper display.
*/
@IBAction func onClickThreadStepper(_ sender: Any) {
delegate?.didChangeThreadCount(to: Int(threadStepper.value))
currentThreadCount = Int(threadStepper.value)
stepperValueLabel.text = "\(currentThreadCount)"
}
}
// MARK: UITableView Data Source
extension InferenceViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return InferenceInfo.allCases.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let height = indexPath.row == InferenceInfo.allCases.count - 1 ? (separatorCellHeight + labeltopSpacing + lableHeight) : normalCellHeight
return height
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "INFO_CELL") as! InfoCell
var fieldName = ""
var info = ""
let tuple = displayStringsForInferenceInfo(atRow: indexPath.row)
fieldName = tuple.0
info = tuple.1
cell.fieldNameLabel.font = infoFont
cell.fieldNameLabel.textColor = infoTextColor
cell.fieldNameLabel.text = fieldName
cell.infoLabel.text = info
return cell
}
/**
This method formats the display of additional information relating to the inferences.
*/
func displayStringsForInferenceInfo(atRow row: Int) -> (String, String) {
var fieldName: String = ""
var info: String = ""
guard let inferenceInfo = InferenceInfo(rawValue: row) else {
return (fieldName, info)
}
fieldName = inferenceInfo.displayString()
switch inferenceInfo {
case .Resolution:
info = "\(Int(resolution.width))x\(Int(resolution.height))"
case .Crop:
info = "\(wantedInputWidth)x\(wantedInputHeight)"
case .InferenceTime:
guard let finalResults = result else {
info = "0ms"
break
}
info = String(format: "%.2fms", finalResults.inferenceTime)
}
return(fieldName, info)
}
}
// MARK: UICollectionView Data Source and Delegate
extension InferenceViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gestures.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GESTURE_CELL", for: indexPath) as! GestureCollectionViewCell
let gesture = gestures[indexPath.item]
var selectionImage: UIImage?
let imageName = gesture.name.lowercased().replacingOccurrences(of: " ", with: "_")
cell.iconImageView.image = UIImage(named: imageName)
cell.nameLabel.text = gesture.name.uppercased().replacingOccurrences(of: " ", with: "\n")
// Shows gestures which are not part of the trained set as disabled.
cell.alpha = gesture.isEnabled ? 1.0 : 0.3
// Highlights gesture currently identified.
if indexPath.item == highlightedRow {
selectionImage = UIImage(named: "selection_base")?.resizableImage(withCapInsets: UIEdgeInsets(top: imageInset, left: imageInset, bottom: imageInset, right: imageInset), resizingMode: .stretch)
}
else {
selectionImage = UIImage(named: "selection_base_default")?.resizableImage(withCapInsets: UIEdgeInsets(top: imageInset, left: imageInset, bottom: imageInset, right: imageInset), resizingMode: .stretch)
}
cell.selectionImageView.image = selectionImage
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = self.view.bounds.size.width - 2 * collectionViewPadding
let itemWidth = (collectionViewWidth - ((itemsInARow - 1) * collectionViewPadding)) / itemsInARow
let size = CGSize(width: itemWidth, height: itemWidth)
return size
}
}
| 31.827586 | 206 | 0.732394 |
29d07ff588a851c5013ffa0b1e62bf88e078656d | 4,453 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
#if compiler(>=5.5) && canImport(_Concurrency)
import SotoCore
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Rbin {
// MARK: Async API Calls
/// Creates a Recycle Bin retention rule. For more information, see Create Recycle Bin retention rules in the Amazon EC2 User Guide.
public func createRule(_ input: CreateRuleRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateRuleResponse {
return try await self.client.execute(operation: "CreateRule", path: "/rules", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a Recycle Bin retention rule. For more information, see Delete Recycle Bin retention rules in the Amazon EC2 User Guide.
public func deleteRule(_ input: DeleteRuleRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteRuleResponse {
return try await self.client.execute(operation: "DeleteRule", path: "/rules/{Identifier}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets information about a Recycle Bin retention rule.
public func getRule(_ input: GetRuleRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetRuleResponse {
return try await self.client.execute(operation: "GetRule", path: "/rules/{Identifier}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the Recycle Bin retention rules in the Region.
public func listRules(_ input: ListRulesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListRulesResponse {
return try await self.client.execute(operation: "ListRules", path: "/list-rules", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the tags assigned a specific resource.
public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTagsForResourceResponse {
return try await self.client.execute(operation: "ListTagsForResource", path: "/tags/{ResourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Assigns tags to the specified resource.
public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> TagResourceResponse {
return try await self.client.execute(operation: "TagResource", path: "/tags/{ResourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Unassigns a tag from a resource.
public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UntagResourceResponse {
return try await self.client.execute(operation: "UntagResource", path: "/tags/{ResourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates an existing Recycle Bin retention rule. For more information, see Update Recycle Bin retention rules in the Amazon EC2 User Guide.
public func updateRule(_ input: UpdateRuleRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateRuleResponse {
return try await self.client.execute(operation: "UpdateRule", path: "/rules/{Identifier}", httpMethod: .PATCH, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
#endif // compiler(>=5.5) && canImport(_Concurrency)
| 65.485294 | 198 | 0.709409 |
33c00e1b1998d613c5a2984270359fd2049124ed | 2,612 | //
// Reader.swift
// WebServer
//
// Created by Florian Kugler on 09-02-2019.
//
import Foundation
import Base
import NIOWrapper
import HTML
import Database
import Promise
extension Reader: NIOWrapper.Response where Result: NIOWrapper.Response {
public static func write(_ string: String, status: HTTPResponseStatus, headers: [String : String]) -> Reader<Value, Result> {
return .const(.write(string, status: status, headers: headers))
}
public static func write(_ data: Data, status: HTTPResponseStatus, headers: [String : String]) -> Reader<Value, Result> {
return .const(.write(data, status: status, headers: headers))
}
public static func writeFile(path: String, gzipped: String?, maxAge: UInt64?) -> Reader<Value, Result> {
return .const(.writeFile(path: path, gzipped: gzipped, maxAge: maxAge))
}
public static func redirect(path: String, headers: [String : String]) -> Reader<Value, Result> {
return .const(.redirect(path: path, headers: headers))
}
public static func onComplete<A>(promise: Promise<A>, do cont: @escaping (A) -> Reader<Value, Result>) -> Reader<Value, Result> {
return Reader { value in .onComplete(promise: promise, do: { x in
cont(x).run(value)
})}
}
public static func withPostData(do cont: @escaping (Data) -> Reader<Value, Result>) -> Reader<Value, Result> {
return Reader { value in .withPostData(do: { cont($0).run(value) }) }
}
}
extension Reader: Response where Result: Response {}
extension Reader: ResponseRequiringEnvironment where Result: Response, Value: RequestEnvironment {
public typealias Env = Value
public static func withSession(_ cont: @escaping (Env.S?) -> Reader<Value, Result>) -> Reader<Value, Result> {
return Reader { value in
cont(value.session).run(value)
}
}
public static func write(html: Node<Env>, status: HTTPResponseStatus = .ok) -> Reader<Value, Result> {
return Reader { (value: Value) -> Result in
return Result.write(html: html.ast(input: value), status: status)
}
}
public static func withCSRF(_ cont: @escaping (CSRFToken) -> Reader) -> Reader {
return Reader { (value: Value) in
return cont(value.csrf).run(value)
}
}
public static func execute<A>(_ query: Query<A>, _ cont: @escaping (Either<A, Error>) -> Reader<Value, Result>) -> Reader<Value, Result> {
return Reader { env in
return cont(env.execute(query)).run(env)
}
}
}
| 36.277778 | 142 | 0.638974 |
0ad881de5dd4341a9870d49839bc901e7658eb48 | 649 | //
// ProfileTableViewCell.swift
// AnywhereFitness
//
// Created by Niranjan Kumar on 11/19/19.
// Copyright © 2019 NarJesse. All rights reserved.
//
import UIKit
class ProfileTableViewCell: UITableViewCell {
@IBOutlet weak var className: UILabel!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var level: 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
}
}
| 19.666667 | 65 | 0.654854 |
6a0433fea4065840e7b18a0f8f4f5a84a709dfbd | 4,192 | //
// PinchGestureTransformViewController.swift
// animations
//
// Created by Karthik Kumar on 01/02/18.
// Copyright © 2018 Karthik Kumar. All rights reserved.
//
import UIKit
class PinchGestureTransformViewController: UIViewController {
var childView = UIView()
var layer: CALayer {
return childView.layer
}
override func loadView() {
view = UIView()
view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addSubviews()
setupLayer()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapView))
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(didPinchView))
childView.addGestureRecognizer(tapGesture)
childView.addGestureRecognizer(pinchGesture)
}
@objc
func didTapView(_ sender: UITapGestureRecognizer) {
layer.shadowOpacity = layer.shadowOpacity == 0.7 ? 0.3 : 0.7
}
@objc
func didPinchView(_ gestureRecognizer: UIPinchGestureRecognizer) {
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
let offset: CGFloat = gestureRecognizer.scale < 1 ? 2.0 : -2.0
let oldFrame = layer.frame
let oldOrigin = oldFrame.origin
let newFrame = CGRect(x: oldOrigin.x + offset,
y: oldOrigin.y + offset,
width: oldFrame.width + (offset * -2.0),
height: oldFrame.height + (offset * -2.0))
if newFrame.width >= 100 && newFrame.width <= 300 {
layer.borderWidth -= offset
layer.cornerRadius += offset / 2
layer.frame = newFrame
}
}
}
private func addSubviews() {
view.addSubview(childView)
childView.backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
childView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: childView, attribute: .centerY, relatedBy: .equal,
toItem: view, attribute: .centerY, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: childView, attribute: .centerX, relatedBy: .equal,
toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: childView, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300))
view.addConstraint(NSLayoutConstraint(item: childView, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300))
}
private func setupLayer() {
layer.backgroundColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
layer.borderWidth = 100
layer.borderColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
layer.shadowOpacity = 0.7
layer.shadowRadius = 10.0
layer.contents = UIImage(named: "star")?.cgImage
layer.contentsGravity = kCAGravityCenter
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 37.765766 | 119 | 0.599952 |
0a68a8e1c4c53b05cbfa6209761fbab6683e9075 | 756 | //
// UIResponder+Device.swift
//
//
// Created by 0xZala on 9/14/20.
//
import Foundation
#if os(iOS)
import UIKit
extension UIResponder {
public var orientation: UIDeviceOrientation {
UIDevice.current.orientation
}
public var interface: UIUserInterfaceIdiom {
UIDevice.current.userInterfaceIdiom
}
public var isIPad: Bool {
UIDevice.current.userInterfaceIdiom == .pad
}
public var isIPhone: Bool {
UIDevice.current.userInterfaceIdiom == .phone
}
public var orientationIsIPhonePortrait: Bool {
orientation == .portrait && isIPhone
}
public var orientationIsIPhoneLandscape: Bool {
orientation.isLandscape && isIPhone
}
}
#endif
| 19.894737 | 53 | 0.649471 |
870ed3e127460e6d106432554cd32f043b1421ff | 2,310 | //
// SceneDelegate.swift
// SwiftExtensionsExamples
//
// Created by Szymon Gęsicki on 19/07/2021.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.584906 | 147 | 0.715152 |
abdc8848974ae79275120be7d5d3b284d78c7f8e | 642 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "JSONSchema",
platforms: [
.iOS(.v11),
.macOS(.v10_13),
],
products: [
.library(name: "JSONSchema", targets: ["JSONSchema"]),
],
dependencies: [
.package(url: "https://github.com/kylef/PathKit.git", .upToNextMajor(from: "1.0.0")),
.package(url: "https://github.com/kylef/Spectre.git", .revision("d02129a9af77729de049d328dd61e530b6f2bb2b"))
],
targets: [
.target(name: "JSONSchema", dependencies: [], path: "Sources"),
.testTarget(name: "JSONSchemaTests", dependencies: ["JSONSchema", "Spectre", "PathKit"]),
]
)
| 27.913043 | 112 | 0.652648 |
90f601e0a6a4776aad93cabf74efa872bb64ffd2 | 5,506 | //
// Path+Project.swift
// BezierKit
//
// Created by Holmes Futrell on 11/23/20.
// Copyright © 2020 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
public extension Path {
private typealias ComponentTuple = (component: PathComponent, index: Int, upperBound: CGFloat)
private typealias Candidate = (point: CGPoint, location: IndexedPathLocation)
private func searchForClosestLocation(to point: CGPoint, maximumDistance: CGFloat, requireBest: Bool) -> (point: CGPoint, location: IndexedPathLocation)? {
// sort the components by proximity to avoid searching distant components later on
let tuples: [ComponentTuple] = self.components.enumerated().map { i, component in
let boundingBox = component.boundingBox
let upper = boundingBox.upperBoundOfDistance(to: point)
return (component: component, index: i, upperBound: upper)
}.sorted(by: { $0.upperBound < $1.upperBound })
// iterate through each component and search for closest point
var bestSoFar: Candidate?
var maximumDistance = maximumDistance
for next in tuples {
guard let projection = next.component.searchForClosestLocation(to: point,
maximumDistance: maximumDistance,
requireBest: requireBest) else {
continue
}
let projectionDistance = distance(point, projection.point)
assert(projectionDistance <= maximumDistance)
let candidate = (point: projection.point,
location: IndexedPathLocation(componentIndex: next.index,
locationInComponent: projection.location))
maximumDistance = projectionDistance
bestSoFar = candidate
}
// return the best answer
if let best = bestSoFar {
return (point: best.point, location: best.location)
}
return nil
}
func project(_ point: CGPoint) -> (point: CGPoint, location: IndexedPathLocation)? {
return self.searchForClosestLocation(to: point, maximumDistance: .infinity, requireBest: true)
}
@objc(point:isWithinDistanceOfBoundary:) func pointIsWithinDistanceOfBoundary(_ point: CGPoint, distance: CGFloat) -> Bool {
return self.searchForClosestLocation(to: point, maximumDistance: distance, requireBest: false) != nil
}
}
public extension PathComponent {
private func anyLocation(in node: BoundingBoxHierarchy.Node) -> IndexedPathComponentLocation {
switch node.type {
case .leaf(let elementIndex):
return IndexedPathComponentLocation(elementIndex: elementIndex, t: 0)
case .internal(let startingElementIndex, _):
return IndexedPathComponentLocation(elementIndex: startingElementIndex, t: 0)
}
}
fileprivate func searchForClosestLocation(to point: CGPoint, maximumDistance: CGFloat, requireBest: Bool) -> (point: CGPoint, location: IndexedPathComponentLocation)? {
var bestSoFar: IndexedPathComponentLocation?
var maximumDistance: CGFloat = maximumDistance
self.bvh.visit { node, _ in
guard requireBest == true || bestSoFar == nil else {
return false // we're done already
}
let boundingBox = node.boundingBox
let lowerBound = boundingBox.lowerBoundOfDistance(to: point)
guard lowerBound <= maximumDistance else {
return false // nothing in this node can be within maximum distance
}
if requireBest == false {
let upperBound = boundingBox.upperBoundOfDistance(to: point)
if upperBound <= maximumDistance {
maximumDistance = upperBound // restrict the search to this new upper bound
bestSoFar = self.anyLocation(in: node)
return false
}
}
if case .leaf(let elementIndex) = node.type {
let curve = self.element(at: elementIndex)
let projection = curve.project(point)
let distanceToCurve = distance(point, projection.point)
if distanceToCurve <= maximumDistance {
maximumDistance = distanceToCurve
bestSoFar = IndexedPathComponentLocation(elementIndex: elementIndex, t: projection.t)
}
}
return true // visit children (if they exist)
}
if let bestSoFar = bestSoFar {
return (point: self.point(at: bestSoFar), location: bestSoFar)
}
return nil
}
func project(_ point: CGPoint) -> (point: CGPoint, location: IndexedPathComponentLocation) {
guard let result = self.searchForClosestLocation(to: point, maximumDistance: .infinity, requireBest: true) else {
assertionFailure("expected non-empty result")
return (point: self.startingPoint, self.startingIndexedLocation)
}
return result
}
@objc(point:isWithinDistanceOfBoundary:) func pointIsWithinDistanceOfBoundary(_ point: CGPoint, distance: CGFloat) -> Bool {
return self.searchForClosestLocation(to: point, maximumDistance: distance, requireBest: false) != nil
}
}
| 49.603604 | 172 | 0.629313 |
20ee97b55a6a268ce295f82d87078a332b5087ad | 10,823 | //
// Created by Shin Yamamoto on 2018/09/26.
// Copyright © 2018 Shin Yamamoto. All rights reserved.
//
import UIKit
/// A view that presents a surface interface in a floating panel.
public class FloatingPanelSurfaceView: UIView {
/// A GrabberHandleView object displayed at the top of the surface view.
///
/// To use a custom grabber handle, hide this and then add the custom one
/// to the surface view at appropriate coordinates.
public let grabberHandle: GrabberHandleView = GrabberHandleView()
/// Offset of the grabber handle from the top
public var grabberTopPadding: CGFloat = 6.0 { didSet {
setNeedsUpdateConstraints()
} }
/// The height of the grabber bar area
public var topGrabberBarHeight: CGFloat {
return grabberTopPadding * 2 + grabberHandleHeight
}
/// Grabber view width and height
public var grabberHandleWidth: CGFloat = 36.0 { didSet {
setNeedsUpdateConstraints()
} }
public var grabberHandleHeight: CGFloat = 5.0 { didSet {
setNeedsUpdateConstraints()
} }
/// A root view of a content view controller
public weak var contentView: UIView!
/// The content insets specifying the insets around the content view.
public var contentInsets: UIEdgeInsets = .zero {
didSet {
// Needs update constraints
self.setNeedsUpdateConstraints()
}
}
private var color: UIColor? = .white { didSet { setNeedsLayout() } }
var bottomOverflow: CGFloat = 0.0 // Must not call setNeedsLayout()
public override var backgroundColor: UIColor? {
get { return color }
set { color = newValue }
}
/// The radius to use when drawing top rounded corners.
///
/// `self.contentView` is masked with the top rounded corners automatically on iOS 11 and later.
/// On iOS 10, they are not automatically masked because of a UIVisualEffectView issue. See https://forums.developer.apple.com/thread/50854
public var cornerRadius: CGFloat {
set { containerView.layer.cornerRadius = newValue; setNeedsLayout() }
get { return containerView.layer.cornerRadius }
}
/// A Boolean indicating whether the surface shadow is displayed.
public var shadowHidden: Bool = false { didSet { setNeedsLayout() } }
/// The color of the surface shadow.
public var shadowColor: UIColor = .black { didSet { setNeedsLayout() } }
/// The offset (in points) of the surface shadow.
public var shadowOffset: CGSize = CGSize(width: 0.0, height: 1.0) { didSet { setNeedsLayout() } }
/// The opacity of the surface shadow.
public var shadowOpacity: Float = 0.2 { didSet { setNeedsLayout() } }
/// The blur radius (in points) used to render the surface shadow.
public var shadowRadius: CGFloat = 3 { didSet { setNeedsLayout() } }
/// The width of the surface border.
public var borderColor: UIColor? { didSet { setNeedsLayout() } }
/// The color of the surface border.
public var borderWidth: CGFloat = 0.0 { didSet { setNeedsLayout() } }
/// The margins to use when laying out the container view wrapping content.
public var containerMargins: UIEdgeInsets = .zero { didSet {
setNeedsUpdateConstraints()
} }
/// The view presents an actual surface shape.
///
/// It renders the background color, border line and top rounded corners,
/// specified by other properties. The reason why they're not be applied to
/// a content view directly is because it avoids any side-effects to the
/// content view.
public let containerView: UIView = UIView()
@available(*, unavailable, renamed: "containerView")
public var backgroundView: UIView!
private lazy var containerViewTopConstraint = containerView.topAnchor.constraint(equalTo: topAnchor, constant: containerMargins.top)
private lazy var containerViewHeightConstraint = containerView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 1.0)
private lazy var containerViewLeftConstraint = containerView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0.0)
private lazy var containerViewRightConstraint = containerView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0.0)
/// The content view top constraint
private var contentViewTopConstraint: NSLayoutConstraint?
/// The content view left constraint
private var contentViewLeftConstraint: NSLayoutConstraint?
/// The content right constraint
private var contentViewRightConstraint: NSLayoutConstraint?
/// The content height constraint
private var contentViewHeightConstraint: NSLayoutConstraint?
private lazy var grabberHandleWidthConstraint = grabberHandle.widthAnchor.constraint(equalToConstant: grabberHandleWidth)
private lazy var grabberHandleHeightConstraint = grabberHandle.heightAnchor.constraint(equalToConstant: grabberHandleHeight)
private lazy var grabberHandleTopConstraint = grabberHandle.topAnchor.constraint(equalTo: topAnchor, constant: grabberTopPadding)
public override class var requiresConstraintBasedLayout: Bool { return true }
override init(frame: CGRect) {
super.init(frame: frame)
addSubViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubViews()
}
private func addSubViews() {
super.backgroundColor = .clear
self.clipsToBounds = false
addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
containerViewTopConstraint,
containerViewLeftConstraint,
containerViewRightConstraint,
containerViewHeightConstraint,
])
addSubview(grabberHandle)
grabberHandle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
grabberHandleWidthConstraint,
grabberHandleHeightConstraint,
grabberHandleTopConstraint,
grabberHandle.centerXAnchor.constraint(equalTo: centerXAnchor),
])
}
public override func updateConstraints() {
containerViewTopConstraint.constant = containerMargins.top
containerViewLeftConstraint.constant = containerMargins.left
containerViewRightConstraint.constant = -containerMargins.right
containerViewHeightConstraint.constant = (containerMargins.bottom == 0) ? bottomOverflow : -(containerMargins.top + containerMargins.bottom)
contentViewTopConstraint?.constant = containerMargins.top + contentInsets.top
contentViewLeftConstraint?.constant = containerMargins.left + contentInsets.left
contentViewRightConstraint?.constant = containerMargins.right + contentInsets.right
contentViewHeightConstraint?.constant = -(containerMargins.top + containerMargins.bottom + contentInsets.top + contentInsets.bottom)
grabberHandleTopConstraint.constant = grabberTopPadding
grabberHandleWidthConstraint.constant = grabberHandleWidth
grabberHandleHeightConstraint.constant = grabberHandleHeight
super.updateConstraints()
}
public override func layoutSubviews() {
super.layoutSubviews()
log.debug("surface view frame = \(frame)")
containerView.backgroundColor = color
updateShadow()
updateCornerRadius()
updateBorder()
}
private func updateShadow() {
if shadowHidden == false {
if #available(iOS 11, *) {
// For clear background. See also, https://github.com/SCENEE/FloatingPanel/pull/51.
layer.shadowColor = shadowColor.cgColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = shadowRadius
} else {
// Can't update `layer.shadow*` directly because of a UIVisualEffectView issue in iOS 10, https://forums.developer.apple.com/thread/50854
// Instead, a user should display shadow appropriately.
}
}
}
private func updateCornerRadius() {
guard containerView.layer.cornerRadius != 0.0 else {
containerView.layer.masksToBounds = false
return
}
containerView.layer.masksToBounds = true
guard containerMargins.bottom == 0 else { return }
if #available(iOS 11, *) {
// Don't use `contentView.clipToBounds` because it prevents content view from expanding the height of a subview of it
// for the bottom overflow like Auto Layout settings of UIVisualEffectView in Main.storyboard of Example/Maps.
// Because the bottom of contentView must be fit to the bottom of a screen to work the `safeLayoutGuide` of a content VC.
containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
} else {
// Can't use `containerView.layer.mask` because of a UIVisualEffectView issue in iOS 10, https://forums.developer.apple.com/thread/50854
// Instead, a user should display rounding corners appropriately.
}
}
private func updateBorder() {
containerView.layer.borderColor = borderColor?.cgColor
containerView.layer.borderWidth = borderWidth
}
func add(contentView: UIView) {
containerView.addSubview(contentView)
self.contentView = contentView
/* contentView.frame = bounds */ // MUST NOT: Because the top safe area inset of a content VC will be incorrect.
contentView.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = contentView.topAnchor.constraint(equalTo: topAnchor, constant: containerMargins.top + contentInsets.top)
let leftConstraint = contentView.leftAnchor.constraint(equalTo: leftAnchor, constant: containerMargins.left + contentInsets.left)
let rightConstraint = rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: containerMargins.right + contentInsets.right)
let heightPadding = containerMargins.top + containerMargins.bottom + contentInsets.top + contentInsets.bottom
let heightConstraint = contentView.heightAnchor.constraint(equalTo: heightAnchor, constant: -heightPadding)
heightConstraint.priority = UILayoutPriority(999)
NSLayoutConstraint.activate([
topConstraint,
leftConstraint,
rightConstraint,
heightConstraint,
])
self.contentViewTopConstraint = topConstraint
self.contentViewLeftConstraint = leftConstraint
self.contentViewRightConstraint = rightConstraint
self.contentViewHeightConstraint = heightConstraint
}
}
| 44.356557 | 153 | 0.700545 |
f4012fb4d65590acc9dc5f232879b0706e32e622 | 327 | //
import Cocoa
let pb = NSPasteboard.general
if let string = pb.string(forType: NSPasteboard.PasteboardType.string) {
pb.declareTypes([NSPasteboard.PasteboardType.html], owner: nil)
pb.setString(string, forType: NSPasteboard.PasteboardType.html)
} else {
print("Could not read string data from pasteboard")
exit(1)
}
| 27.25 | 72 | 0.761468 |
231fc93314062b7e4d76060b776645c46dddda03 | 23,852 | //
// TPumpSettingsDatumTests.swift
// TidepoolKitTests
//
// Created by Darin Krauss on 11/11/19.
// Copyright © 2019 Tidepool Project. All rights reserved.
//
import XCTest
import TidepoolKit
class TPumpSettingsDatumTests: XCTestCase {
static let pumpSettings = TPumpSettingsDatum(
time: Date.test,
activeScheduleName: "Activated",
automatedDelivery: true,
basal: TPumpSettingsDatumBasalTests.basal,
basalRateSchedule: [TPumpSettingsDatumBasalRateStartTests.basalRateStart, TPumpSettingsDatumBasalRateStartTests.basalRateStart],
basalRateSchedules: [
"zero": [],
"one": [TPumpSettingsDatumBasalRateStartTests.basalRateStart],
"two": [TPumpSettingsDatumBasalRateStartTests.basalRateStart, TPumpSettingsDatumBasalRateStartTests.basalRateStart]
],
bloodGlucoseSuspendThreshold: 123.45,
bloodGlucoseTargetPhysicalActivity: TBloodGlucoseTargetTests.target,
bloodGlucoseTargetPreprandial: TBloodGlucoseTargetTests.target,
bloodGlucoseTargetSchedule: [TBloodGlucoseStartTargetTests.startTarget, TBloodGlucoseStartTargetTests.startTarget],
bloodGlucoseTargetSchedules: [
"zero": [],
"one": [TBloodGlucoseStartTargetTests.startTarget],
"two": [TBloodGlucoseStartTargetTests.startTarget, TBloodGlucoseStartTargetTests.startTarget]
],
bolus: TPumpSettingsDatumBolusTests.bolus,
carbohydrateRatioSchedule: [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart],
carbohydrateRatioSchedules: [
"zero": [],
"one": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart],
"two": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart]
],
display: TPumpSettingsDatumDisplayTests.display,
insulinModel: TPumpSettingsDatumInsulinModelTests.insulinModel,
insulinSensitivitySchedule: [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart],
insulinSensitivitySchedules: [
"zero": [],
"one": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart],
"two": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart]
],
manufacturers: ["Alfa", "Romeo"],
model: "Spider",
scheduleTimeZoneOffset: -28800,
serialNumber: "1234567890",
units: TPumpSettingsDatumUnitsTests.units
)
static let pumpSettingsJSONDictionary: [String: Any] = [
"type": "pumpSettings",
"time": Date.testJSONString,
"activeSchedule": "Activated",
"automatedDelivery": true,
"basal": TPumpSettingsDatumBasalTests.basalJSONDictionary,
"basalSchedule": [TPumpSettingsDatumBasalRateStartTests.basalRateStartJSONDictionary, TPumpSettingsDatumBasalRateStartTests.basalRateStartJSONDictionary],
"basalSchedules": [
"zero": [],
"one": [TPumpSettingsDatumBasalRateStartTests.basalRateStartJSONDictionary],
"two": [TPumpSettingsDatumBasalRateStartTests.basalRateStartJSONDictionary, TPumpSettingsDatumBasalRateStartTests.basalRateStartJSONDictionary]
],
"bgSuspendThreshold": 123.45,
"bgTargetPhysicalActivity": TBloodGlucoseTargetTests.targetJSONDictionary,
"bgTargetPreprandial": TBloodGlucoseTargetTests.targetJSONDictionary,
"bgTarget": [TBloodGlucoseStartTargetTests.startTargetJSONDictionary, TBloodGlucoseStartTargetTests.startTargetJSONDictionary],
"bgTargets": [
"zero": [],
"one": [TBloodGlucoseStartTargetTests.startTargetJSONDictionary],
"two": [TBloodGlucoseStartTargetTests.startTargetJSONDictionary, TBloodGlucoseStartTargetTests.startTargetJSONDictionary]
],
"bolus": TPumpSettingsDatumBolusTests.bolusJSONDictionary,
"carbRatio": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStartJSONDictionary, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStartJSONDictionary],
"carbRatios": [
"zero": [],
"one": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStartJSONDictionary],
"two": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStartJSONDictionary, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStartJSONDictionary]
],
"display": TPumpSettingsDatumDisplayTests.displayJSONDictionary,
"insulinModel": TPumpSettingsDatumInsulinModelTests.insulinModelJSONDictionary,
"insulinSensitivity": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStartJSONDictionary, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStartJSONDictionary],
"insulinSensitivities": [
"zero": [],
"one": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStartJSONDictionary],
"two": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStartJSONDictionary, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStartJSONDictionary]
],
"manufacturers": ["Alfa", "Romeo"],
"model": "Spider",
"scheduleTimeZoneOffset": -480,
"serialNumber": "1234567890",
"units": TPumpSettingsDatumUnitsTests.unitsJSONDictionary
]
func testInitializer() {
let pumpSettings = TPumpSettingsDatumTests.pumpSettings
XCTAssertEqual(pumpSettings.activeScheduleName, "Activated")
XCTAssertEqual(pumpSettings.automatedDelivery, true)
XCTAssertEqual(pumpSettings.basal, TPumpSettingsDatumBasalTests.basal)
XCTAssertEqual(pumpSettings.basalRateSchedule, [TPumpSettingsDatumBasalRateStartTests.basalRateStart, TPumpSettingsDatumBasalRateStartTests.basalRateStart])
XCTAssertEqual(pumpSettings.basalRateSchedules, [
"zero": [],
"one": [TPumpSettingsDatumBasalRateStartTests.basalRateStart],
"two": [TPumpSettingsDatumBasalRateStartTests.basalRateStart, TPumpSettingsDatumBasalRateStartTests.basalRateStart]
])
XCTAssertEqual(pumpSettings.bloodGlucoseSuspendThreshold, 123.45)
XCTAssertEqual(pumpSettings.bloodGlucoseTargetPhysicalActivity, TBloodGlucoseTargetTests.target)
XCTAssertEqual(pumpSettings.bloodGlucoseTargetPreprandial, TBloodGlucoseTargetTests.target)
XCTAssertEqual(pumpSettings.bloodGlucoseTargetSchedule, [TBloodGlucoseStartTargetTests.startTarget, TBloodGlucoseStartTargetTests.startTarget])
XCTAssertEqual(pumpSettings.bloodGlucoseTargetSchedules, [
"zero": [],
"one": [TBloodGlucoseStartTargetTests.startTarget],
"two": [TBloodGlucoseStartTargetTests.startTarget, TBloodGlucoseStartTargetTests.startTarget]
])
XCTAssertEqual(pumpSettings.bolus, TPumpSettingsDatumBolusTests.bolus)
XCTAssertEqual(pumpSettings.carbohydrateRatioSchedule, [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart])
XCTAssertEqual(pumpSettings.carbohydrateRatioSchedules, [
"zero": [],
"one": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart],
"two": [TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart]
])
XCTAssertEqual(pumpSettings.display, TPumpSettingsDatumDisplayTests.display)
XCTAssertEqual(pumpSettings.insulinModel, TPumpSettingsDatumInsulinModelTests.insulinModel)
XCTAssertEqual(pumpSettings.insulinSensitivitySchedule, [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart])
XCTAssertEqual(pumpSettings.insulinSensitivitySchedules, [
"zero": [],
"one": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart],
"two": [TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart]
])
XCTAssertEqual(pumpSettings.manufacturers, ["Alfa", "Romeo"])
XCTAssertEqual(pumpSettings.model, "Spider")
XCTAssertEqual(pumpSettings.scheduleTimeZoneOffset, -28800)
XCTAssertEqual(pumpSettings.serialNumber, "1234567890")
XCTAssertEqual(pumpSettings.units, TPumpSettingsDatumUnitsTests.units)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumTests.pumpSettings, TPumpSettingsDatumTests.pumpSettingsJSONDictionary)
}
}
class TPumpSettingsDatumBasalTests: XCTestCase {
static let basal = TPumpSettingsDatum.Basal(
rateMaximum: TPumpSettingsDatumBasalRateMaximumTests.rateMaximum,
temporary: TPumpSettingsDatumBasalTemporaryTests.temporary
)
static let basalJSONDictionary: [String: Any] = [
"rateMaximum": TPumpSettingsDatumBasalRateMaximumTests.rateMaximumJSONDictionary,
"temporary": TPumpSettingsDatumBasalTemporaryTests.temporaryJSONDictionary
]
func testInitializer() {
let basal = TPumpSettingsDatumBasalTests.basal
XCTAssertEqual(basal.rateMaximum, TPumpSettingsDatumBasalRateMaximumTests.rateMaximum)
XCTAssertEqual(basal.temporary, TPumpSettingsDatumBasalTemporaryTests.temporary)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBasalTests.basal, TPumpSettingsDatumBasalTests.basalJSONDictionary)
}
}
class TPumpSettingsDatumBasalRateMaximumTests: XCTestCase {
static let rateMaximum = TPumpSettingsDatum.Basal.RateMaximum(1.23, .unitsPerHour)
static let rateMaximumJSONDictionary: [String: Any] = [
"value": 1.23,
"units": "Units/hour"
]
func testInitializer() {
let rateMaximum = TPumpSettingsDatumBasalRateMaximumTests.rateMaximum
XCTAssertEqual(rateMaximum.value, 1.23)
XCTAssertEqual(rateMaximum.units, .unitsPerHour)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBasalRateMaximumTests.rateMaximum, TPumpSettingsDatumBasalRateMaximumTests.rateMaximumJSONDictionary)
}
}
class TPumpSettingsDatumBasalRateMaximumUnitsTests: XCTestCase {
func testUnits() {
XCTAssertEqual(TPumpSettingsDatum.Basal.RateMaximum.Units.unitsPerHour.rawValue, "Units/hour")
}
}
class TPumpSettingsDatumBasalTemporaryTests: XCTestCase {
static let temporary = TPumpSettingsDatum.Basal.Temporary(.unitsPerHour)
static let temporaryJSONDictionary: [String: Any] = [
"type": "Units/hour",
]
func testInitializer() {
let temporary = TPumpSettingsDatumBasalTemporaryTests.temporary
XCTAssertEqual(temporary.type, .unitsPerHour)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBasalTemporaryTests.temporary, TPumpSettingsDatumBasalTemporaryTests.temporaryJSONDictionary)
}
}
class TPumpSettingsDatumBasalTemporaryTemporaryTypeTests: XCTestCase {
func testTemporaryType() {
XCTAssertEqual(TPumpSettingsDatum.Basal.Temporary.TemporaryType.off.rawValue, "off")
XCTAssertEqual(TPumpSettingsDatum.Basal.Temporary.TemporaryType.percent.rawValue, "percent")
XCTAssertEqual(TPumpSettingsDatum.Basal.Temporary.TemporaryType.unitsPerHour.rawValue, "Units/hour")
}
}
class TPumpSettingsDatumBasalRateStartTests: XCTestCase {
static let basalRateStart = TPumpSettingsDatum.BasalRateStart(start: 12345.678, rate: 45.67)
static let basalRateStartJSONDictionary: [String: Any] = [
"start": 12345678,
"rate": 45.67
]
func testInitializer() {
let basalRateStart = TPumpSettingsDatumBasalRateStartTests.basalRateStart
XCTAssertEqual(basalRateStart.start, 12345.678)
XCTAssertEqual(basalRateStart.rate, 45.67)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBasalRateStartTests.basalRateStart, TPumpSettingsDatumBasalRateStartTests.basalRateStartJSONDictionary)
}
}
class TPumpSettingsDatumBolusTests: XCTestCase {
static let bolus = TPumpSettingsDatum.Bolus(
amountMaximum: TPumpSettingsDatumBolusAmountMaximumTests.amountMaximum,
calculator: TPumpSettingsDatumBolusCalculatorTests.calculator,
extended: TPumpSettingsDatumBolusExtendedTests.extended
)
static let bolusJSONDictionary: [String: Any] = [
"amountMaximum": TPumpSettingsDatumBolusAmountMaximumTests.amountMaximumJSONDictionary,
"calculator": TPumpSettingsDatumBolusCalculatorTests.calculatorJSONDictionary,
"extended": TPumpSettingsDatumBolusExtendedTests.extendedJSONDictionary
]
func testInitializer() {
let bolus = TPumpSettingsDatumBolusTests.bolus
XCTAssertEqual(bolus.amountMaximum, TPumpSettingsDatumBolusAmountMaximumTests.amountMaximum)
XCTAssertEqual(bolus.calculator, TPumpSettingsDatumBolusCalculatorTests.calculator)
XCTAssertEqual(bolus.extended, TPumpSettingsDatumBolusExtendedTests.extended)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBolusTests.bolus, TPumpSettingsDatumBolusTests.bolusJSONDictionary)
}
}
class TPumpSettingsDatumBolusAmountMaximumTests: XCTestCase {
static let amountMaximum = TPumpSettingsDatum.Bolus.AmountMaximum(1.23, .units)
static let amountMaximumJSONDictionary: [String: Any] = [
"value": 1.23,
"units": "Units"
]
func testInitializer() {
let amountMaximum = TPumpSettingsDatumBolusAmountMaximumTests.amountMaximum
XCTAssertEqual(amountMaximum.value, 1.23)
XCTAssertEqual(amountMaximum.units, .units)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBolusAmountMaximumTests.amountMaximum, TPumpSettingsDatumBolusAmountMaximumTests.amountMaximumJSONDictionary)
}
}
class TPumpSettingsDatumBolusCalculatorTests: XCTestCase {
static let calculator = TPumpSettingsDatum.Bolus.Calculator(enabled: true, insulin: TPumpSettingsDatumBolusCalculatorInsulinTests.insulin)
static let calculatorJSONDictionary: [String: Any] = [
"enabled": true,
"insulin": TPumpSettingsDatumBolusCalculatorInsulinTests.insulinJSONDictionary
]
func testInitializer() {
let calculator = TPumpSettingsDatumBolusCalculatorTests.calculator
XCTAssertEqual(calculator.enabled, true)
XCTAssertEqual(calculator.insulin, TPumpSettingsDatumBolusCalculatorInsulinTests.insulin)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBolusCalculatorTests.calculator, TPumpSettingsDatumBolusCalculatorTests.calculatorJSONDictionary)
}
}
class TPumpSettingsDatumBolusCalculatorInsulinTests: XCTestCase {
static let insulin = TPumpSettingsDatum.Bolus.Calculator.Insulin(1.23, .hours)
static let insulinJSONDictionary: [String: Any] = [
"duration": 1.23,
"units": "hours"
]
func testInitializer() {
let insulin = TPumpSettingsDatumBolusCalculatorInsulinTests.insulin
XCTAssertEqual(insulin.duration, 1.23)
XCTAssertEqual(insulin.units, .hours)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBolusCalculatorInsulinTests.insulin, TPumpSettingsDatumBolusCalculatorInsulinTests.insulinJSONDictionary)
}
}
class TPumpSettingsDatumBolusCalculatorInsulinUnitsTests: XCTestCase {
func testUnits() {
XCTAssertEqual(TPumpSettingsDatum.Bolus.Calculator.Insulin.Units.hours.rawValue, "hours")
XCTAssertEqual(TPumpSettingsDatum.Bolus.Calculator.Insulin.Units.minutes.rawValue, "minutes")
XCTAssertEqual(TPumpSettingsDatum.Bolus.Calculator.Insulin.Units.seconds.rawValue, "seconds")
}
}
class TPumpSettingsDatumBolusExtendedTests: XCTestCase {
static let extended = TPumpSettingsDatum.Bolus.Extended(enabled: true)
static let extendedJSONDictionary: [String: Any] = [
"enabled": true,
]
func testInitializer() {
let extended = TPumpSettingsDatumBolusExtendedTests.extended
XCTAssertEqual(extended.enabled, true)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumBolusExtendedTests.extended, TPumpSettingsDatumBolusExtendedTests.extendedJSONDictionary)
}
}
class TPumpSettingsDatumCarbohydrateRatioStartTests: XCTestCase {
static let carbohydrateRatioStart = TPumpSettingsDatum.CarbohydrateRatioStart(start: 12345.678, amount: 45.67)
static let carbohydrateRatioStartJSONDictionary: [String: Any] = [
"start": 12345678,
"amount": 45.67
]
func testInitializer() {
let carbohydrateRatioStart = TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart
XCTAssertEqual(carbohydrateRatioStart.start, 12345.678)
XCTAssertEqual(carbohydrateRatioStart.amount, 45.67)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStart, TPumpSettingsDatumCarbohydrateRatioStartTests.carbohydrateRatioStartJSONDictionary)
}
}
class TPumpSettingsDatumDisplayTests: XCTestCase {
static let display = TPumpSettingsDatum.Display(bloodGlucose: TPumpSettingsDatumDisplayBloodGlucoseTests.bloodGlucose)
static let displayJSONDictionary: [String: Any] = [
"bloodGlucose": TPumpSettingsDatumDisplayBloodGlucoseTests.bloodGlucoseJSONDictionary,
]
func testInitializer() {
let display = TPumpSettingsDatumDisplayTests.display
XCTAssertEqual(display.bloodGlucose, TPumpSettingsDatumDisplayBloodGlucoseTests.bloodGlucose)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumDisplayTests.display, TPumpSettingsDatumDisplayTests.displayJSONDictionary)
}
}
class TPumpSettingsDatumDisplayBloodGlucoseTests: XCTestCase {
static let bloodGlucose = TPumpSettingsDatum.Display.BloodGlucose(.milligramsPerDeciliter)
static let bloodGlucoseJSONDictionary: [String: Any] = [
"units": "mg/dL",
]
func testInitializer() {
let bloodGlucose = TPumpSettingsDatumDisplayBloodGlucoseTests.bloodGlucose
XCTAssertEqual(bloodGlucose.units, .milligramsPerDeciliter)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumDisplayBloodGlucoseTests.bloodGlucose, TPumpSettingsDatumDisplayBloodGlucoseTests.bloodGlucoseJSONDictionary)
}
}
class TPumpSettingsDatumInsulinModelTests: XCTestCase {
static let insulinModel = TPumpSettingsDatum.InsulinModel(modelType: .rapidAdult, actionDuration: 21600, actionPeakOffset: 3600)
static let insulinModelJSONDictionary: [String: Any] = [
"modelType": "rapidAdult",
"actionDuration": 21600,
"actionPeakOffset": 3600
]
func testInitializer() {
let insulinModel = TPumpSettingsDatumInsulinModelTests.insulinModel
XCTAssertEqual(insulinModel.modelType, .rapidAdult)
XCTAssertEqual(insulinModel.actionDuration, 21600)
XCTAssertEqual(insulinModel.actionPeakOffset, 3600)
}
func testInitializerWithModelTypeOther() {
let insulinModel = TPumpSettingsDatum.InsulinModel(modelType: .other, modelTypeOther: "whatever")
XCTAssertEqual(insulinModel.modelType, .other)
XCTAssertEqual(insulinModel.modelTypeOther, "whatever")
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumInsulinModelTests.insulinModel, TPumpSettingsDatumInsulinModelTests.insulinModelJSONDictionary)
}
func testCodableAsJSONWithModelTypeOther() {
let insulinModel = TPumpSettingsDatum.InsulinModel(modelType: .other, modelTypeOther: "whatever")
let insulinModelJSONDictionary: [String: Any] = [
"modelType": "other",
"modelTypeOther": "whatever"
]
XCTAssertCodableAsJSON(insulinModel, insulinModelJSONDictionary)
}
}
class TPumpSettingsDatumInsulinModelModelTypeTests: XCTestCase {
func testUnits() {
XCTAssertEqual(TPumpSettingsDatum.InsulinModel.ModelType.fiasp.rawValue, "fiasp")
XCTAssertEqual(TPumpSettingsDatum.InsulinModel.ModelType.other.rawValue, "other")
XCTAssertEqual(TPumpSettingsDatum.InsulinModel.ModelType.rapidAdult.rawValue, "rapidAdult")
XCTAssertEqual(TPumpSettingsDatum.InsulinModel.ModelType.rapidChild.rawValue, "rapidChild")
XCTAssertEqual(TPumpSettingsDatum.InsulinModel.ModelType.walsh.rawValue, "walsh")
}
}
class TPumpSettingsDatumInsulinSensitivityStartTests: XCTestCase {
static let insulinSensitivityStart = TPumpSettingsDatum.InsulinSensitivityStart(start: 12345.678, amount: 45.67)
static let insulinSensitivityStartJSONDictionary: [String: Any] = [
"start": 12345678,
"amount": 45.67
]
func testInitializer() {
let insulinSensitivityStart = TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart
XCTAssertEqual(insulinSensitivityStart.start, 12345.678)
XCTAssertEqual(insulinSensitivityStart.amount, 45.67)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStart, TPumpSettingsDatumInsulinSensitivityStartTests.insulinSensitivityStartJSONDictionary)
}
}
class TPumpSettingsDatumUnitsTests: XCTestCase {
static let units = TPumpSettingsDatum.Units(bloodGlucose: .milligramsPerDeciliter, carbohydrate: .grams, insulin: .units)
static let unitsJSONDictionary: [String: Any] = [
"bg": "mg/dL",
"carb": "grams",
"insulin": "Units"
]
func testInitializer() {
let units = TPumpSettingsDatumUnitsTests.units
XCTAssertEqual(units.bloodGlucose, .milligramsPerDeciliter)
XCTAssertEqual(units.carbohydrate, .grams)
XCTAssertEqual(units.insulin, .units)
}
func testCodableAsJSON() {
XCTAssertCodableAsJSON(TPumpSettingsDatumUnitsTests.units, TPumpSettingsDatumUnitsTests.unitsJSONDictionary)
}
}
extension TPumpSettingsDatum {
func isEqual(to other: TPumpSettingsDatum) -> Bool {
return super.isEqual(to: other) &&
self.activeScheduleName == other.activeScheduleName &&
self.basal == other.basal &&
self.basalRateSchedule == other.basalRateSchedule &&
self.basalRateSchedules == other.basalRateSchedules &&
self.bloodGlucoseTargetSchedule == other.bloodGlucoseTargetSchedule &&
self.bloodGlucoseTargetSchedules == other.bloodGlucoseTargetSchedules &&
self.bolus == other.bolus &&
self.carbohydrateRatioSchedule == other.carbohydrateRatioSchedule &&
self.carbohydrateRatioSchedules == other.carbohydrateRatioSchedules &&
self.display == other.display &&
self.insulinSensitivitySchedule == other.insulinSensitivitySchedule &&
self.insulinSensitivitySchedules == other.insulinSensitivitySchedules &&
self.manufacturers == other.manufacturers &&
self.model == other.model &&
self.serialNumber == other.serialNumber &&
self.units == other.units
}
}
| 48.977413 | 209 | 0.756079 |
5be5388ffe039e64d79b1ca2007a6a5235c7ddc6 | 1,136 | // 用于处理后台服务器同一个字段返回数据类型可变的情况
import Foundation
///跨类型解析方式
// 一个含有int,string的类,可用于解析后台返回类型不确定的字段。即:把int\string解析成TStrInt且解析后TStrInt的int和string都有值
//----- 使用时如果报未初始化的错误,而且找不到原因时,可以尝试先修复model以外的错误,也许这个错误就会消失。。。。 这是编译器提示错误的原因
struct StrInt: Codable {
var int:Int {
didSet {
let stringValue = String(int)
if stringValue != string {
string = stringValue
}
}
}
var string:String {
didSet {
if let intValue = Int(string), intValue != int {
int = intValue
}
}
}
init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
if let stringValue = try? singleValueContainer.decode(String.self)
{
string = stringValue
int = Int(stringValue) ?? 0
} else if let intValue = try? singleValueContainer.decode(Int.self)
{
int = intValue
string = String(intValue);
} else
{
int = 0
string = ""
}
}
}
| 25.818182 | 86 | 0.539613 |
6998a3dc8fb8fb40038fdec8edc02c77f012fbd9 | 806 | import Foundation
/// A TV network.
public struct Network: Identifiable, Decodable, Equatable, Hashable, LogoURLProviding {
/// Network identifier.
public let id: Int
/// Network name.
public let name: String
/// Network logo path.
public let logoPath: URL?
/// Network origin country.
public let originCountry: String?
/// Creates a new `Network`.
///
/// - Parameters:
/// - id: Network identifier.
/// - name: Network name.
/// - logoPath: Network logo path.
/// - originCountry: Network origin country.
public init(id: Int, name: String, logoPath: URL? = nil, originCountry: String? = nil) {
self.id = id
self.name = name
self.logoPath = logoPath
self.originCountry = originCountry
}
}
| 26.866667 | 92 | 0.610422 |
09e64d25bf4bbdbb78862dc12bb42244e7a712e1 | 1,705 | //
// WJXibUseDemoViewController.swift
// WJPageView
//
// Created by 陈威杰 on 2018/9/4.
// Copyright © 2018年 W.J Chen. All rights reserved.
//
import UIKit
class WJXibUseDemoViewController: UIViewController {
@IBOutlet weak var titleBarView: WJPageTitleBarView!
@IBOutlet weak var pageContentView: WJPageContainerView!
@IBOutlet weak var topEdgeContraint: NSLayoutConstraint!
private lazy var config: WJPageViewConfig = {
let config = WJPageViewConfig()
config.titleBarBgColor = .white
config.indecatorBottomOffset = 2
config.titleEdgeMargin = 15
config.indicatorWidth = 20
config.indicatorLineHeight = 4
config.isScaleTransformEnable = true
return config
}()
override func viewDidLoad() {
super.viewDidLoad()
// 禁止自动调整内边距
automaticallyAdjustsScrollViewInsets = false
topEdgeContraint.constant = kNavigationBarHeight
let titles = ["音乐", "视频", "推荐", "智能家居", "军事", "社会", "人气段子", "手机"]
titleBarView.titles = titles
titleBarView.config = config
titleBarView.titleBarSetup() // 调用该方法完成设置
let childVCs: [UIViewController] = titles.map { _ in
let vc = UIViewController()
vc.view.backgroundColor = UIColor.randomColor
return vc
}
pageContentView.config = config
pageContentView.childViewControllers = childVCs
pageContentView.pageSetup() // 调用该方法完成设置
// 相互设置代理为对方即可完成其两者的逻辑交互
titleBarView.delegate = pageContentView
pageContentView.delegate = titleBarView
}
}
| 27.063492 | 73 | 0.629912 |
eb1bf3144d4ea9550feb1b8d132a6ffe3c4189f1 | 1,303 | //
// NavControllerTransitions.swift
// ReceiptsSorted
//
// Created by Maksim on 14/07/2020.
// Copyright © 2020 Maksim. All rights reserved.
//
import UIKit
/// Class responsible for Navigation controller transitions
class NavControllerTransitions: NSObject {
private let circularTransition = CircularTransition()
private let animationCentre: CGPoint
init(animationCentre: CGPoint) {
self.animationCentre = animationCentre
}
}
// MARK: - UINavigationControllerDelegate, UIViewControllerTransitioningDelegate
extension NavControllerTransitions: UINavigationControllerDelegate, UIViewControllerTransitioningDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if ( (toVC is CameraViewController && fromVC is ViewController) ||
(toVC is ViewController && fromVC is CameraViewController)) {
circularTransition.transitionMode = (operation == .push) ? .present : .pop
circularTransition.startingPoint = animationCentre
return circularTransition
}
return nil
}
}
| 32.575 | 247 | 0.734459 |
4a59b54ae746f3b149be8f5082817350adaa506c | 1,433 | //
// VideoCell.swift
// Flipflop
//
// Created by Jahid Hassan on 3/26/19.
// Copyright © 2019 Jahid Hassan. All rights reserved.
//
import UIKit
import ASPVideoPlayer
class VideoCell: UICollectionViewCell {
@IBOutlet weak var playerView: ASPVideoPlayerView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addObserver()
}
override init(frame: CGRect) {
super.init(frame: frame)
addObserver()
}
public var videoUrl: URL! {
didSet {
playerView.videoURL = videoUrl
}
}
override func awakeFromNib() {
super.awakeFromNib()
configPlayer()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func addObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(clearPlayer),
name: HomeWillDisappear,
object: nil)
}
private func configPlayer() {
playerView.shouldLoop = true
playerView.startPlayingWhenReady = true
playerView.gravity = .aspectFill
}
@objc private func clearPlayer() {
playerView.startPlayingWhenReady = false
playerView.stopVideo()
playerView.videoURL = nil
}
}
| 23.883333 | 80 | 0.558269 |
d9a5148b97d4e89333eaee33053a3cde40bb8737 | 8,419 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The view displaying the game scene, including the 2D overlay.
*/
import simd
import SceneKit
import SpriteKit
class GameView: SCNView {
// MARK: 2D Overlay
private let overlayNode = SKNode()
private let congratulationsGroupNode = SKNode()
private let collectedPearlCountLabel = SKLabelNode(fontNamed: "Chalkduster")
private var collectedFlowerSprites = [SKSpriteNode]()
#if os(iOS) || os(tvOS)
override func awakeFromNib() {
super.awakeFromNib()
setup2DOverlay()
}
override func layoutSubviews() {
super.layoutSubviews()
layout2DOverlay()
}
#elseif os(OSX)
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
setup2DOverlay()
}
override func setFrameSize(newSize: NSSize) {
super.setFrameSize(newSize)
layout2DOverlay()
}
#endif
private func layout2DOverlay() {
overlayNode.position = CGPointMake(0.0, bounds.size.height)
congratulationsGroupNode.position = CGPointMake(bounds.size.width * 0.5, bounds.size.height * 0.5)
congratulationsGroupNode.xScale = 1.0
congratulationsGroupNode.yScale = 1.0
let currentBbox = congratulationsGroupNode.calculateAccumulatedFrame()
let margin = CGFloat(25.0)
let maximumAllowedBbox = CGRectInset(bounds, margin, margin)
let top = CGRectGetMaxY(currentBbox) - congratulationsGroupNode.position.y
let bottom = congratulationsGroupNode.position.y - CGRectGetMinY(currentBbox)
let maxTopAllowed = CGRectGetMaxY(maximumAllowedBbox) - congratulationsGroupNode.position.y
let maxBottomAllowed = congratulationsGroupNode.position.y - CGRectGetMinY(maximumAllowedBbox)
let left = congratulationsGroupNode.position.x - CGRectGetMinX(currentBbox)
let right = CGRectGetMaxX(currentBbox) - congratulationsGroupNode.position.x
let maxLeftAllowed = congratulationsGroupNode.position.x - CGRectGetMinX(maximumAllowedBbox)
let maxRightAllowed = CGRectGetMaxX(maximumAllowedBbox) - congratulationsGroupNode.position.x
let topScale = top > maxTopAllowed ? maxTopAllowed / top : 1
let bottomScale = bottom > maxBottomAllowed ? maxBottomAllowed / bottom : 1
let leftScale = left > maxLeftAllowed ? maxLeftAllowed / left : 1
let rightScale = right > maxRightAllowed ? maxRightAllowed / right : 1
let scale = min(topScale, min(bottomScale, min(leftScale, rightScale)))
congratulationsGroupNode.xScale = scale
congratulationsGroupNode.yScale = scale
}
private func setup2DOverlay() {
let w = bounds.size.width
let h = bounds.size.height
// Setup the game overlays using SpriteKit.
let skScene = SKScene(size: CGSize(width: w, height: h))
skScene.scaleMode = .ResizeFill
skScene.addChild(overlayNode)
overlayNode.position = CGPoint(x: 0.0, y: h)
// The Max icon.
overlayNode.addChild(SKSpriteNode(imageNamed: "MaxIcon.png", position: CGPoint(x: 50, y:-50), scale: 0.5))
// The flowers.
for i in 0..<3 {
collectedFlowerSprites.append(SKSpriteNode(imageNamed: "FlowerEmpty.png", position: CGPoint(x: 110 + i * 40, y:-50), scale: 0.25))
overlayNode.addChild(collectedFlowerSprites[i])
}
// The pearl icon and count.
overlayNode.addChild(SKSpriteNode(imageNamed: "ItemsPearl.png", position: CGPointMake(110, -100), scale: 0.5))
collectedPearlCountLabel.text = "x0"
collectedPearlCountLabel.position = CGPointMake(152, -113)
overlayNode.addChild(collectedPearlCountLabel)
// The virtual D-pad
#if os(iOS)
let virtualDPadBounds = virtualDPadBoundsInScene()
let dpadSprite = SKSpriteNode(imageNamed: "dpad.png", position: virtualDPadBounds.origin, scale: 1.0)
dpadSprite.anchorPoint = CGPointMake(0.0, 0.0)
dpadSprite.size = virtualDPadBounds.size
skScene.addChild(dpadSprite)
#endif
// Assign the SpriteKit overlay to the SceneKit view.
overlaySKScene = skScene
skScene.userInteractionEnabled = false
}
var collectedPearlsCount = 0 {
didSet {
if collectedPearlsCount == 10 {
collectedPearlCountLabel.position = CGPointMake(158, collectedPearlCountLabel.position.y)
}
collectedPearlCountLabel.text = "x\(collectedPearlsCount)"
}
}
var collectedFlowersCount = 0 {
didSet {
collectedFlowerSprites[collectedFlowersCount - 1].texture = SKTexture(imageNamed: "FlowerFull.png")
}
}
// MARK: Congratulating the Player
func showEndScreen() {
// Congratulation title
let congratulationsNode = SKSpriteNode(imageNamed: "congratulations.png")
// Max image
let characterNode = SKSpriteNode(imageNamed: "congratulations_pandaMax.png")
characterNode.position = CGPointMake(0.0, -220.0)
characterNode.anchorPoint = CGPointMake(0.5, 0.0)
congratulationsGroupNode.addChild(characterNode)
congratulationsGroupNode.addChild(congratulationsNode)
let overlayScene = overlaySKScene!
overlayScene.addChild(congratulationsGroupNode)
// Layout the overlay
layout2DOverlay()
// Animate
(congratulationsNode.alpha, congratulationsNode.xScale, congratulationsNode.yScale) = (0.0, 0.0, 0.0)
congratulationsNode.runAction(SKAction.group([
SKAction.fadeInWithDuration(0.25),
SKAction.sequence([SKAction.scaleTo(1.22, duration: 0.25), SKAction.scaleTo(1.0, duration: 0.1)])]))
(characterNode.alpha, characterNode.xScale, characterNode.yScale) = (0.0, 0.0, 0.0)
characterNode.runAction(SKAction.sequence([
SKAction.waitForDuration(0.5),
SKAction.group([
SKAction.fadeInWithDuration(0.5),
SKAction.sequence([SKAction.scaleTo(1.22, duration: 0.25), SKAction.scaleTo(1.0, duration: 0.1)])])]))
congratulationsGroupNode.position = CGPointMake(bounds.size.width * 0.5, bounds.size.height * 0.5);
}
// MARK: Mouse and Keyboard Events
#if os(OSX)
var eventsDelegate: KeyboardAndMouseEventsDelegate?
override func mouseDown(theEvent: NSEvent) {
guard let eventsDelegate = eventsDelegate where eventsDelegate.mouseDown(self, theEvent: theEvent) else {
super.mouseDown(theEvent)
return
}
}
override func mouseDragged(theEvent: NSEvent) {
guard let eventsDelegate = eventsDelegate where eventsDelegate.mouseDragged(self, theEvent: theEvent) else {
super.mouseDragged(theEvent)
return
}
}
override func mouseUp(theEvent: NSEvent) {
guard let eventsDelegate = eventsDelegate where eventsDelegate.mouseUp(self, theEvent: theEvent) else {
super.mouseUp(theEvent)
return
}
}
override func keyDown(theEvent: NSEvent) {
guard let eventsDelegate = eventsDelegate where eventsDelegate.keyDown(self, theEvent: theEvent) else {
super.keyDown(theEvent)
return
}
}
override func keyUp(theEvent: NSEvent) {
guard let eventsDelegate = eventsDelegate where eventsDelegate.keyUp(self, theEvent: theEvent) else {
super.keyUp(theEvent)
return
}
}
#endif
// MARK: Virtual D-pad
#if os(iOS)
private func virtualDPadBoundsInScene() -> CGRect {
return CGRectMake(10.0, 10.0, 150.0, 150.0)
}
func virtualDPadBounds() -> CGRect {
var virtualDPadBounds = virtualDPadBoundsInScene()
virtualDPadBounds.origin.y = bounds.size.height - virtualDPadBounds.size.height + virtualDPadBounds.origin.y
return virtualDPadBounds
}
#endif
}
| 35.978632 | 142 | 0.642713 |
e280a6ae548f700ebe5ca68cbed59ca333d5175d | 1,289 | // Copyright 2020 Carton contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if canImport(Combine)
import Combine
#else
import OpenCombine
#endif
import TSCBasic
import TSCUtility
struct Progress {
let step: Int
let total: Int
let text: String
}
extension Publisher where Output == Progress {
func handle(
with progressAnimation: ProgressAnimationProtocol
) -> Publishers.HandleEvents<Self> {
handleEvents(
receiveOutput: {
progressAnimation.update(step: $0.step, total: $0.total, text: $0.text)
},
receiveCompletion: {
switch $0 {
case .finished:
progressAnimation.complete(success: true)
case .failure:
progressAnimation.complete(success: false)
}
}
)
}
}
| 26.854167 | 79 | 0.696664 |
6a711d8f0207f5327eaa7756954df0bbc093c1d9 | 4,502 | //
// CanvasViewController.swift
// Canvas
//
// Created by Israel Andrade on 3/14/18.
// Copyright © 2018 Israel Andrade. All rights reserved.
//
import UIKit
class CanvasViewController: UIViewController {
var trayOriginalCenter: CGPoint!
var trayDownOffset: CGFloat!
var trayUp: CGPoint!
var trayDown: CGPoint!
var newlyCreatedFace: UIImageView!
var newlyCreatedFaceOriginalCenter: CGPoint!
var panGesture = UIPanGestureRecognizer()
@IBOutlet weak var trayView: UIView!
override func viewDidLoad() {
trayDownOffset = 200
trayUp = trayView.center // The initial position of the tray
trayDown = CGPoint(x: trayView.center.x ,y: trayView.center.y + trayDownOffset) // The position of the tray transposed down
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didPanTray(_ sender: UIPanGestureRecognizer) {
let location = sender.location(in: view)
let velocity = sender.velocity(in: view)
let translation = sender.translation(in: view)
if sender.state == .began {
print("Gesture began")
trayOriginalCenter = trayView.center
} else if sender.state == .changed {
print("Gesture is changing")
trayView.center = CGPoint(x: trayOriginalCenter.x, y: trayOriginalCenter.y + translation.y)
} else if sender.state == .ended {
if velocity.y > 0 {
UIView.animate(withDuration: 0.3) {
self.trayView.center = self.trayDown
}
} else {
UIView.animate(withDuration: 0.3) {
self.trayView.center = self.trayUp
}
}
print("Gesture ended")
}
}
@IBAction func didPanFace(_ sender: UIPanGestureRecognizer) {
let location = sender.location(in: view)
let velocity = sender.velocity(in: view)
let translation = sender.translation(in: view)
if sender.state == .began {
print("Gesture began")
var imageView = sender.view as! UIImageView
newlyCreatedFace = UIImageView(image: imageView.image)
view.addSubview(newlyCreatedFace)
newlyCreatedFace.center = imageView.center
newlyCreatedFace.center.y += trayView.frame.origin.y
newlyCreatedFaceOriginalCenter = newlyCreatedFace.center
let gestureRecognizer = UIPanGestureRecognizer(target:self, action:#selector(CanvasViewController.didPanFace(sender:)))
newlyCreatedFace.addGestureRecognizer(gestureRecognizer)
newlyCreatedFace.isUserInteractionEnabled = true
} else if sender.state == .changed {
print("Gesture is changing")
newlyCreatedFace.center = CGPoint(x: newlyCreatedFaceOriginalCenter.x + translation.x, y: newlyCreatedFaceOriginalCenter.y + translation.y)
} else if sender.state == .ended {
print("Gesture ended")
}
}
@objc func didPanFace(sender: UIPanGestureRecognizer) {
let location = sender.location(in: view)
let velocity = sender.velocity(in: view)
let translation = sender.translation(in: view)
if sender.state == .began {
print("Gesture began")
newlyCreatedFace = sender.view as! UIImageView // to get the face that we panned on.
newlyCreatedFaceOriginalCenter = newlyCreatedFace.center // so we can offset by translation later.
} else if sender.state == .changed {
print("Gesture is changing")
newlyCreatedFace.center = CGPoint(x: newlyCreatedFaceOriginalCenter.x + translation.x, y: newlyCreatedFaceOriginalCenter.y + translation.y)
} else if sender.state == .ended {
print("Gesture ended")
}
}
/*
// 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.
}
*/
}
| 37.206612 | 151 | 0.627943 |
2164a1bdc65504705109b465e15628b515b684d4 | 1,331 | //
// AppDelegate.swift
// JBCut Helper
//
// Created by 任金波 on 2019/8/14.
// Copyright © 2019 任金波. All rights reserved.
//
/*
Thanks for the login item method for below link
http://martiancraft.com/blog/2015/01/login-items/
https://medium.com/@hoishing/adding-login-items-for-macos-7d76458f6495
*/
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
/*
That’s it for the Helper application…
its sole job is to find out the path for the main application,
launch it, and then terminate itself.
*/
func applicationDidFinishLaunching(_ aNotification: Notification) {
let runningApps = NSWorkspace.shared.runningApplications
let isRunning = runningApps.contains {
$0.bundleIdentifier == "com.jimbo.JBCut"
}
if !isRunning {
var path = Bundle.main.bundlePath as NSString
for _ in 1...4 {
path = path.deletingLastPathComponent as NSString
}
NSWorkspace.shared.launchApplication(path as String)
}
NSApp.terminate(nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 25.596154 | 71 | 0.640872 |
f7203077b94cfe9672fd452bcd60345ef7a2457b | 149 | // whatdid?
enum OpenReason {
case manual
case scheduled
var description: String {
return String(describing: self)
}
}
| 13.545455 | 39 | 0.604027 |
0830f86d403a33446e11f15f6ccf0e2d26dc8a73 | 1,553 | //
// VideoPlayerProtocol.swift
// App
//
// Created by ragingo on 2021/06/04.
//
import Combine
import Foundation
import QuartzCore
import CoreImage
enum VideoLoadStatus {
case unknown
case readyToPlay
case failed
}
enum VideoPlayStatus {
case paused
case buffering
case playing
}
protocol VideoPlayerProtocol: AnyObject {
var layer: CALayer { get }
var isLiveStreaming: Bool { get }
var isPlaying: Bool { get }
var isBuffering: Bool { get }
var rate: Float { get set }
var loadStatusSubject: PassthroughSubject<VideoLoadStatus, Never> { get }
var playStatusSubject: PassthroughSubject<VideoPlayStatus, Never> { get }
var durationSubject: PassthroughSubject<Double, Never> { get }
var positionSubject: PassthroughSubject<Double, Never> { get }
var isPlaybackLikelyToKeepUpSubject: PassthroughSubject<Bool, Never> { get }
var isSeekingSubject: PassthroughSubject<Bool, Never> { get }
var loadedBufferRangeSubject: PassthroughSubject<(Double, Double), Never> { get }
var generatedImageSubject: PassthroughSubject<(Double, CGImage), Never> { get }
var bandwidthsSubject: PassthroughSubject<[Int], Never> { get }
func prepare()
func invalidate()
func open(urlString: String) async
func play()
func pause()
func seek(seconds: Double)
func requestGenerateImage(time: Double, size: CGSize)
func cancelImageGenerationRequests()
func changePreferredPeakBitRate(value: Int)
func addFilter(filter: CIFilter)
func clearFilters()
}
| 28.759259 | 85 | 0.720541 |
2fb3a4a15a698843d95ab3acac20f9665e786514 | 4,477 | //
// Operation.swift
// ARKExtensions
//
// Created by ark dan on 1/3/17.
// Copyright © 2017 arkdan. All rights reserved.
//
import Foundation
/// OOperations are asynchronous.
open class OOperation: Operation {
public typealias Execution = (_ finished: @escaping () -> Void) -> Void
fileprivate var privateCompletionBlock: ((OOperation) -> Void)?
/// provide either 'execution' block, or override func execute(). The block takes priority.
open var execution: Execution?
public init(block: @escaping Execution) {
super.init()
execution = block
}
public override init() {
super.init()
}
/// always true. These thigs are asynchronous.
override public final var isAsynchronous: Bool {
return true
}
private var _executing = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
didChangeValue(forKey: "isExecuting")
}
}
override public final var isExecuting: Bool {
return _executing
}
private var _finished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
didChangeValue(forKey: "isFinished")
}
}
override public final var isFinished: Bool {
return _finished
}
override public final func start() {
if isCancelled {
finish()
return
}
_executing = true
if let execution = self.execution {
execution(finish)
} else {
execute()
}
}
open func execute() {
fatalError("Must override execute() or provide 'execution' block")
}
public final func finish() {
_executing = false
_finished = true
privateCompletionBlock?(self)
}
}
open class OOperationQueue: OperationQueue {
// need a alternative operations count, because Operation.operationCount is sometimes carries
// irrelevant values due to concurrent nature of the queue.
private var ccount = 0
/// called each time all operations are completed.
public var whenEmpty: (() -> Void)?
public convenience init(maxConcurrent: Int) {
self.init()
maxConcurrentOperationCount = maxConcurrent
}
/*
override init() {
super.init()
addObserver(self, forKeyPath: #keyPath(operations), options: [.new, .old], context: nil)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let kkeyPath = keyPath, kkeyPath == #keyPath(operations) else {
return
}
let old = change![.oldKey] as! [Operation]
let new = change![.newKey] as! [Operation]
print("queue count \(operationCount) \(old.count)->\(new.count)")
if let kkeyPath = keyPath, kkeyPath == #keyPath(operations),
let cchange = change,
let old = cchange[.oldKey] as? [Operation], let new = cchange[.newKey] as? [Operation],
new.count == 0, old.count == 1 {
self.whenEmpty?()
print("trigger")
}
}
*/
/// Supports OOperations only
override open func addOperation(_ operation: Operation) {
guard let op = operation as? OOperation else {
fatalError("This class only works with OOperation objects")
}
ccount += 1
super.addOperation(op)
op.privateCompletionBlock = { [weak self] operation in
guard let sself = self else {
return
}
sself.ccount -= 1
if sself.ccount == 0 {
sself.whenEmpty?()
}
}
}
public func addExecution(_ execution: @escaping OOperation.Execution) {
addOperation(OOperation(block: execution))
}
/// Not supported.
///
/// Use addExecution instead. I can't report progress on block operation, which is the main goal of this class
override open func addOperation(_ block: @escaping () -> Void) {
fatalError("")
}
/// Not supported. OOperationQueue is there to report progress on async execution
override open func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool) {
fatalError("Not supported. OOperationQueue is there to report progress on async execution")
}
}
| 26.64881 | 156 | 0.599732 |
e25d30b5f930c1547e21ca5647bd8b52711144fd | 561 | //
// TokenCellViewModel.swift
// OMGShop
//
// Created by Mederic Petit on 14/11/17.
// Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved.
//
import OmiseGO
class TokenCellViewModel: BaseViewModel {
var tokenSymbol: String = "-"
var tokenAmount: String = "0"
var isSelected: Bool = false
private var balance: Balance!
init(balance: Balance, isSelected: Bool) {
self.tokenSymbol = balance.token.symbol
self.tokenAmount = balance.displayAmount(withPrecision: 3)
self.isSelected = isSelected
}
}
| 23.375 | 66 | 0.677362 |
dd9470837da469ffe571bf927e1d379812f368b4 | 248 | //
// SectionHeader.swift
// NogiMusic
//
// Created by 横山 新 on 2018/04/25.
// Copyright © 2018年 横山 新. All rights reserved.
//
import UIKit
final class SectionHeader: UICollectionReusableView {
@IBOutlet weak var sectionLabel: UILabel!
}
| 17.714286 | 53 | 0.705645 |
fb162099e2de6f09fb7d8c46515de33057883aec | 694 | //
// MQTTManager.swift
// IOTrace
//
// Created by Jagni Bezerra on 07/12/2018.
// Copyright © 2018 IBM. All rights reserved.
//
import Foundation
import CocoaMQTT
let mqttClient = CocoaMQTT(clientID: IOTPCredentials.clientID,
host: IOTPCredentials.host, port: UInt16(IOTPCredentials.mqttPort!))
var trackedDevice = IOTPDevice()
class MQTTManager {
static func sendLostCommand(value: Bool, device: IOTPDevice = IOTPDevice()){
let topic = "iot-2/type/\(device.type)/id/\(device.id)/cmd/lost/fmt/json"
let message = CocoaMQTTMessage(topic: topic, string: "{value: \(value ? "true" : "false")}")
mqttClient.publish(message)
}
}
| 27.76 | 100 | 0.668588 |
d5ff0f4e9342a0ca3bc76a19e01c6d3db068f150 | 10,255 | //
// UPennBiometricsAuthService.swift
// Penn Chart Live
//
// Created by Rashad Abdul-Salam on 3/12/19.
// Copyright © 2019 University of Pennsylvania Health System. All rights reserved.
//
import Foundation
import LocalAuthentication
import UIKit
class UPennBiometricsAuthService {
enum BiometricType {
case None
case TouchID
case FaceID
}
private var biometricsOptInBeforeRegisteredKey = UPennNameSpacer.makeKey("biometricsOptInBeforeRegistered")
private var context = LAContext()
/**
Bool indicating whether opt-in for biometrics before registering == 'yes'
*/
var enabledBiometricsBeforeRegistered : Bool {
guard let optIn = self.biometricsOptInBeforeRegistered else {
return false
}
return optIn == "yes"
}
/**
UserDefaults key for biometricsOptInBeforeRegistered
*/
private var biometricsEnabledKey = UPennNameSpacer.makeKey("biometricsEnabled")
let touchIDOptInTitle = "Use Touch ID for login in the future?".localize
let touchIDOptInMessage = "Touch ID makes Login more convenient. These Settings can be updated in the Account section.".localize
let touchIDConfirmed = "Use Touch ID".localize
let touchIDDeclined = "No Thanks".localize
var delegate: UPennBiometricsDelegate?
var biometricType: BiometricType {
get {
var error: NSError?
guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
print(error?.localizedDescription ?? "")
return .None
}
if #available(iOS 11.0, *) {
switch context.biometryType {
case .none:
return .None
case .touchID:
return .TouchID
case .faceID:
return .FaceID
}
} else {
return .None
}
}
}
/**
Text for enabling Touch ID vs. Face ID depending on context
*/
var toggleTitleText : String {
return self.makeBiometricsPrependedMessage("Enable", defaultText: "Biometrics Unavailable")
}
/**
Messaging text for turning off 'Remember Me' in Touch ID vs. Face ID context
*/
var biometricOptOutMessage : String {
return self.makeBiometricsPrependedMessage("Turning off 'Remember Me' will disable", defaultText: self.biometricsFallbackMessage)
}
init(biometricsDelegate: UPennBiometricsDelegate?=nil) {
self.delegate = biometricsDelegate
}
/**
Bool indicating the current device has biometrics capabilities
*/
var biometricsAvailable: Bool {
return self.context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
}
/**
Bool indicating biometrics are available, and user has opted-in to use them for login
*/
var biometricsEnabled : Bool {
guard let enabled = UserDefaults.standard.value(forKey: self.biometricsEnabledKey) as? Bool else { return false }
return enabled && self.biometricsAvailable
}
/**
Toggle image for Touch ID or Face ID switch
*/
var biometricToggleImage : UIImage {
switch self.biometricType {
case .FaceID: return #imageLiteral(resourceName: "face_ID_Penn")
default: return #imageLiteral(resourceName: "touchID")
}
}
/**
Conditionally trigger registration for either Face ID or Touch ID
*/
func registerForBiometricAuthentication() {
if self.biometricsAvailable {
if self.enabledBiometricsBeforeRegistered {
self.setEnabledBiometricsBeforeRegisteredNo()
}
switch self.biometricType {
case .FaceID:
self.delegate?.registerForFaceIDAuthentication()
case .TouchID:
self.delegate?.registerForTouchIDAuthentication()
case .None:
self.delegate?.biometricsDidError(with: nil, shouldContinue: true)
}
} else {
self.delegate?.biometricsDidError(with: nil, shouldContinue: true)
}
}
/**
Convenience method to set biometricsOptInBeforeRegistered to 'no'
*/
func completeTouchIDRegistration() {
self.setEnabledBiometricsBeforeRegisteredNo()
}
/**
Sets Bool in UserDefaults indicating whether biometric authentication is enabled
*/
func toggleBiometrics(_ enabled: Bool) {
UserDefaults.standard.set(enabled, forKey: self.biometricsEnabledKey)
// Check if biometricsOptInBeforeRegistered is set, if not set to 'Yes'
guard let _ = self.biometricsOptInBeforeRegistered else {
self.setEnabledBiometricsBeforeRegisteredYes()
return
}
}
/**
Conditionally attempt authenticating user with biometrics
*/
func attemptBiometricsAuthentication() {
// Ensure biometrics registered and enabled
if self.biometricsEnabled && !self.enabledBiometricsBeforeRegistered {
self.utilizeBiometricAuthentication()
}
}
/**
Authenticate user using biometrics
- parameter turnOnBiometrics: Bool that indicates whether delegate object should turn on biometrics settings
*/
func utilizeBiometricAuthentication(turnOnBiometrics: Bool = false) {
self.context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
localizedReason: self.biometricsLoginMessage) { (success, evaluateError) in
// Set enableBiometricsBeforeRegistered to 'No'
self.setEnabledBiometricsBeforeRegisteredNo()
if success {
DispatchQueue.main.async {
self.delegate?.biometricsSuccessfullyAuthenticated(turnOnBiometrics: turnOnBiometrics)
}
} else {
var message: String?=nil
switch evaluateError {
case LAError.authenticationFailed?:
message = self.biometricsFailedMessage
case LAError.userCancel?, LAError.userFallback?: break
default:
message = self.biometricsFallbackMessage
}
DispatchQueue.main.async {
self.delegate?.biometricsDidError(with: message, shouldContinue: turnOnBiometrics)
}
}
}
// Reset context to always prompt for login credentials
self.context = LAContext()
}
}
private extension UPennBiometricsAuthService {
/**
Optional String allowing for 3 states for opting-in to use biometrics before registering: 'yes', 'no', nil
*/
var biometricsOptInBeforeRegistered : String? { return UserDefaults.standard.string(forKey: self.biometricsOptInBeforeRegisteredKey)
}
/**
Message for failed biometric login
*/
var biometricsFailedMessage : String { return "There was a problem verifying your identity.".localize }
/**
Message indicating biometric login in-progress
*/
var biometricsLoginMessage : String {
return self.makeBiometricsPrependedMessage("Logging in with", defaultText: self.biometricsFallbackMessage)
}
/**
Fallback message indicating biometrics not authorized on device
*/
var biometricsFallbackMessage : String {
let baseText = "not authorized for use."
return self.makeBiometricsAppendedMessage(baseText, defaultText: "Biometrics \(baseText)")
}
/**
Message indicating biometrics unavailable on device
*/
var biometricsUnavailableMessage : String {
return self.makeBiometricsAppendedMessage("is not available on this device.", defaultText: self.biometricsFallbackMessage)
}
/**
Convenience method for making custom, context-based phrases appended at the end of a message
- parameters:
- baseText: Phrase that will go at the end of the message
- defaultText: Phrase that will appear if biometrics unavailable
*/
func makeBiometricsAppendedMessage(_ baseText: String, defaultText: String) -> String {
switch biometricType {
case .TouchID: return "Touch ID \(baseText)".localize
case .FaceID: return "Face ID \(baseText)".localize
default: return defaultText
}
}
/**
Convenience method for making custom, context-based phrases prepended at the beginning of a message
- parameters:
- baseText: Phrase that will go at the beginning of the message
- defaultText: Phrase that will appear if biometrics unavailable
*/
func makeBiometricsPrependedMessage(_ baseText: String, defaultText: String) -> String {
switch self.biometricType {
case .TouchID: return "\(baseText) Touch ID".localize
case .FaceID: return "\(baseText) Face ID".localize
default: return defaultText
}
}
/**
Sets biometricsOptInBeforeRegistered to 'yes' in UserDefaults
*/
func setEnabledBiometricsBeforeRegisteredYes() {
UserDefaults.standard.set("yes", forKey: self.biometricsOptInBeforeRegisteredKey)
}
/**
Sets biometricsOptInBeforeRegistered to 'no' in UserDefaults
*/
func setEnabledBiometricsBeforeRegisteredNo() {
UserDefaults.standard.set("no", forKey: self.biometricsOptInBeforeRegisteredKey)
}
}
| 37.702206 | 137 | 0.606241 |
752c6d4fe38b096d9f701c4a0c13209dc75a7eda | 168 | //
// TypographyColors.swift
// TypographyKit
//
// Created by Ross Butler on 6/26/19.
//
import Foundation
typealias TypographyColors = [String: TypographyColor]
| 15.272727 | 54 | 0.72619 |
f7f0ab83d5770a8924650857b1d1e07fd4306c35 | 1,204 | import Foundation
import ObjectiveC.runtime
public struct AssociatedObject {
/**
Gets the Obj-C reference for the instance object within the UIView extension.
- Parameter base: Base object.
- Parameter key: Memory key pointer.
- Parameter initializer: Object initializer.
- Returns: The associated reference for the initializer object.
*/
public static func get<T: Any>(base: Any, key: UnsafePointer<UInt8>, initializer: () -> T) -> T {
if let v = objc_getAssociatedObject(base, key) as? T {
return v
}
let v = initializer()
objc_setAssociatedObject(base, key, v, .OBJC_ASSOCIATION_RETAIN)
return v
}
/**
Sets the Obj-C reference for the instance object within the UIView extension.
- Parameter base: Base object.
- Parameter key: Memory key pointer.
- Parameter value: The object instance to set for the associated object.
- Returns: The associated reference for the initializer object.
*/
public static func set<T: Any>(base: Any, key: UnsafePointer<UInt8>, value: T) {
objc_setAssociatedObject(base, key, value, .OBJC_ASSOCIATION_RETAIN)
}
}
| 36.484848 | 101 | 0.664452 |
48d879cce042d108df0a6a150dd1ff47f760b8c3 | 1,342 | //
// GADBannerViewController.swift
// YourKitchen
//
// Created by Markus Moltke on 12/06/2020.
// Copyright © 2020 Markus Moltke. All rights reserved.
//
import Foundation
import GoogleMobileAds
import SwiftUI
import UIKit
struct GADBannerViewController: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
let view = GADBannerView(adSize: kGADAdSizeBanner)
let viewController = UIViewController()
#if DEBUG
// let nativeAdvancedVideo = "ca-app-pub-3940256099942544/2521693316"
let adUnitID = "ca-app-pub-3940256099942544/2934735716"
#else
let adUnitID = "ca-app-pub-5947064851146376/7264689535"
#endif
view.adUnitID = adUnitID
view.rootViewController = viewController
viewController.view.addSubview(view)
viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
let request = GADRequest()
let extras = GADExtras()
if (UserDefaults.standard.bool(forKey: "adConsent")) {
extras.additionalParameters = ["npa": "1"]
}
request.register(extras)
view.load(request)
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
| 31.952381 | 90 | 0.678838 |
393b73a551ce4d39c6efd999cd05e58a8fb63799 | 4,467 | //
// Line.swift
// LineChart
//
// Created by András Samu on 2019. 08. 30..
// Copyright © 2019. András Samu. All rights reserved.
//
import SwiftUI
public struct Line: View {
@ObservedObject var data: ChartData
@Binding var frame: CGRect
@Binding var touchLocation: CGPoint
@Binding var showIndicator: Bool
@Binding var minDataValue: Double?
@Binding var maxDataValue: Double?
@State private var showFull: Bool = false
@State var showBackground: Bool = true
var gradient: GradientColor = GradientColor(start: Colors.GradientPurple, end: Colors.GradientNeonBlue)
var index:Int = 0
let padding:CGFloat = 30
var curvedLines: Bool = true
var stepWidth: CGFloat {
if data.points.count < 2 {
return 0
}
return frame.size.width / CGFloat(data.points.count-1)
}
var stepHeight: CGFloat {
var min: Double?
var max: Double?
let points = self.data.onlyPoints()
if minDataValue != nil && maxDataValue != nil {
min = minDataValue!
max = maxDataValue!
}else if let minPoint = points.min(), let maxPoint = points.max(), minPoint != maxPoint {
min = minPoint
max = maxPoint
}else {
return 0
}
if let min = min, let max = max, min != max {
if (min <= 0){
return (frame.size.height-padding) / CGFloat(max - min)
}else{
return (frame.size.height-padding) / CGFloat(max - min)
}
}
return 0
}
var path: Path {
let points = self.data.onlyPoints()
return curvedLines ? Path.quadCurvedPathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight), globalOffset: minDataValue) : Path.linePathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight))
}
var closedPath: Path {
let points = self.data.onlyPoints()
return curvedLines ? Path.quadClosedCurvedPathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight), globalOffset: minDataValue) : Path.closedLinePathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight))
}
public var body: some View {
ZStack {
if(self.showFull && self.showBackground){
self.closedPath
.fill(LinearGradient(gradient: Gradient(colors: [Colors.GradientUpperBlue, .white]), startPoint: .bottom, endPoint: .top))
.offset(x: 0, y: 10.0)
.rotationEffect(.degrees(180), anchor: .center)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
.transition(.opacity)
.animation(.easeIn(duration: 1.6))
}
self.path
.trim(from: 0, to: self.showFull ? 1:0)
.stroke(LinearGradient(gradient: gradient.getGradient(), startPoint: .leading, endPoint: .trailing) ,style: StrokeStyle(lineWidth: 3, lineJoin: .round))
.offset(x: 0, y: 10.0)
.rotationEffect(.degrees(180), anchor: .center)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
.animation(Animation.easeOut(duration: 1.2).delay(Double(self.index)*0.4))
.onAppear {
self.showFull = true
}
.onDisappear {
self.showFull = false
}
.drawingGroup()
if(self.showIndicator) {
IndicatorPoint()
.position(self.getClosestPointOnPath(touchLocation: self.touchLocation))
.rotationEffect(.degrees(180), anchor: .center)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
.offset(x: 0, y: -10.0)
}
}
}
func getClosestPointOnPath(touchLocation: CGPoint) -> CGPoint {
let closest = self.path.point(to: touchLocation.x)
return closest
}
}
struct Line_Previews: PreviewProvider {
static var previews: some View {
GeometryReader{ geometry in
Line(data: ChartData(points: [12,-230,10,54]), frame: .constant(geometry.frame(in: .local)), touchLocation: .constant(CGPoint(x: 100, y: 12)), showIndicator: .constant(true), minDataValue: .constant(nil), maxDataValue: .constant(nil))
}.frame(width: 320, height: 160)
}
}
| 40.609091 | 246 | 0.579584 |
692b3b67b7b2d696d050f05bc098d10558d23351 | 2,176 | //
// AppDelegate.swift
// CocoaToggles
//
// Created by isabellyfd on 10/18/2019.
// Copyright (c) 2019 isabellyfd. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.297872 | 285 | 0.755055 |
5d77dfc0e45ca7e535fb809d896dc79e4925268a | 277 | //
// ProfileData.swift
// GVImageLoader_Example
//
// Created by Venkat on 14/04/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
struct ProfileData: Decodable {
// MARK: Properties
let id: String?
let user: User?
}
| 13.85 | 52 | 0.646209 |
e8c833c2e5f32bcf4a19245f8f0d6abd8296b03d | 7,016 | //
// AudioKit+SafeConnections.swift
// AudioKit
//
// Created by Jeff Cooper on 4/20/18.
// Copyright © 2018 AudioKit. All rights reserved.
//
import Foundation
/// This extension makes connect calls shorter, and safer by attaching nodes if not already attached.
extension AudioKit {
// Attaches nodes if node.engine == nil
private static func safeAttach(_ nodes: [AVAudioNode]) {
_ = nodes.filter { $0.engine == nil }.map { engine.attach($0) }
}
// AVAudioMixer will crash if engine is started and connection is made to a bus exceeding mixer's
// numberOfInputs. The crash only happens when using the AVAudioEngine function that connects a node to an array
// of AVAudioConnectionPoints and the mixer is one of those points. When AVAudioEngine uses a different function
// that connects a node's output to a single AVAudioMixerNode, the mixer's inputs are incremented to accommodate
// the new connection. So the workaround is to create dummy nodes, make a connections to the mixer using the
// function that makes the mixer create new inputs, then remove the dummy nodes so that there is an available
// bus to connect to.
//
private static func checkMixerInputs(_ connectionPoints: [AVAudioConnectionPoint]) {
if !engine.isRunning { return }
for connection in connectionPoints {
if let mixer = connection.node as? AVAudioMixerNode,
connection.bus >= mixer.numberOfInputs {
var dummyNodes = [AVAudioNode]()
while connection.bus >= mixer.numberOfInputs {
let dummyNode = AVAudioUnitSampler()
dummyNode.setOutput(to: mixer)
dummyNodes.append(dummyNode)
}
for dummyNode in dummyNodes {
dummyNode.disconnectOutput()
}
}
}
}
// If an AVAudioMixerNode's output connection is made while engine is running, and there are no input connections
// on the mixer, subsequent connections made to the mixer will silently fail. A workaround is to connect a dummy
// node to the mixer prior to making a connection, then removing the dummy node after the connection has been made.
//
private static func addDummyOnEmptyMixer(_ node: AVAudioNode) -> AVAudioNode? {
// Only an issue if engine is running, node is a mixer, and mixer has no inputs
guard let mixer = node as? AVAudioMixerNode,
engine.isRunning,
!engine.mixerHasInputs(mixer: mixer) else {
return nil
}
let dummy = AVAudioUnitSampler()
engine.attach(dummy)
engine.connect(dummy, to: mixer, format: AudioKit.format)
return dummy
}
@objc public static func connect(_ sourceNode: AVAudioNode,
to destNodes: [AVAudioConnectionPoint],
fromBus sourceBus: AVAudioNodeBus,
format: AVAudioFormat?) {
let connectionsWithNodes = destNodes.filter { $0.node != nil }
safeAttach([sourceNode] + connectionsWithNodes.map { $0.node! })
// See addDummyOnEmptyMixer for dummyNode explanation.
let dummyNode = addDummyOnEmptyMixer(sourceNode)
checkMixerInputs(connectionsWithNodes)
engine.connect(sourceNode, to: connectionsWithNodes, fromBus: sourceBus, format: format)
dummyNode?.disconnectOutput()
}
@objc public static func connect(_ node1: AVAudioNode,
to node2: AVAudioNode,
fromBus bus1: AVAudioNodeBus,
toBus bus2: AVAudioNodeBus,
format: AVAudioFormat?) {
safeAttach([node1, node2])
// See addDummyOnEmptyMixer for dummyNode explanation.
let dummyNode = addDummyOnEmptyMixer(node1)
engine.connect(node1, to: node2, fromBus: bus1, toBus: bus2, format: format)
dummyNode?.disconnectOutput()
}
@objc public static func connect(_ node1: AVAudioNode, to node2: AVAudioNode, format: AVAudioFormat?) {
connect(node1, to: node2, fromBus: 0, toBus: 0, format: format)
}
//Convenience
@objc public static func detach(nodes: [AVAudioNode]) {
for node in nodes {
engine.detach(node)
}
}
/// Render output to an AVAudioFile for a duration.
///
/// NOTE: This will NOT render AKSequencer content;
/// MIDI content will need to be recorded in real time
///
/// - Parameters:
/// - audioFile: An file initialized for writing
/// - duration: Duration to render, in seconds
/// - prerender: A closure called before rendering starts, use this to start players, set initial parameters, etc...
///
@available(iOS 11, macOS 10.13, tvOS 11, *)
@objc public static func renderToFile(_ audioFile: AVAudioFile, duration: Double, prerender: (() -> Void)? = nil) throws {
try engine.renderToFile(audioFile, duration: duration, prerender: prerender)
}
@available(iOS 11, macOS 10.13, tvOS 11, *)
public static func printConnections() {
let nodes: [AVAudioNode] = {
var nodes = Set<AVAudioNode>()
func addInputs(_ node: AVAudioNode) {
nodes.insert(node)
node.inputConnections().filter { $0.node != nil }.forEach { addInputs($0.node!) }
}
addInputs(engine.outputNode)
return Array(nodes)
}()
func nodeDescription(_ id: Int, _ node: AVAudioNode) -> String {
return "(\(id)]\(node.auAudioUnit.audioUnitName ?? String(describing: node))"
}
func formatDescription(_ format: AVAudioFormat) -> String {
guard let description = format.description.components(separatedBy: ": ").dropFirst().first else { return format.description }
return "<" + description
}
let padLength = nodes.reduce(0) { max($0, nodeDescription(nodes.count, $1).count) }
func padded(_ string: String) -> String {
return string.count >= padLength ? string : string + String(repeating: " ", count: padLength - string.count)
}
nodes.enumerated().forEach { (id, node) in
let outputs: [(id: Int, node: AVAudioNode, bus: Int)] = node.connectionPoints.compactMap {
guard let node = $0.node, let id = nodes.index(of: node) else { return nil }
return (id, node, $0.bus)
}
let srcDescritption = padded(nodeDescription(id, node))
let format = formatDescription(node.outputFormat(forBus: 0))
outputs.forEach {
let dstDescription = nodeDescription($0.id, $0.node)
print("\(srcDescritption) \(format) -> \(dstDescription)) bus: \($0.bus)")
}
}
}
}
| 42.26506 | 138 | 0.61431 |
5db60fb899852ba5dec472cb31dcc005465350a9 | 1,401 | //
// NewsCoordinator.swift
// XCoordinator_Example
//
// Created by Paul Kraft on 28.07.18.
// Copyright © 2018 QuickBird Studios. All rights reserved.
//
import XCoordinator
enum NewsRoute: Route {
case news
case newsDetail(News)
case close
}
class NewsCoordinator: NavigationCoordinator<NewsRoute> {
// MARK: - Init
init() {
super.init(initialRoute: .news)
}
// MARK: - Overrides
override func prepareTransition(for route: NewsRoute) -> NavigationTransition {
switch route {
case .news:
let viewController = NewsViewController.instantiateFromNib()
let service = MockNewsService()
let viewModel = NewsViewModelImpl(newsService: service, coordinator: anyRouter)
viewController.bind(to: viewModel)
return .push(viewController)
case .newsDetail(let news):
let viewController = NewsDetailViewController.instantiateFromNib()
let viewModel = NewsDetailViewModelImpl(news: news)
viewController.bind(to: viewModel)
let animation: Animation
if #available(iOS 10.0, *) {
animation = .swirl
} else {
animation = .scale
}
return .push(viewController, animation: animation)
case .close:
return .dismissToRoot()
}
}
}
| 27.470588 | 91 | 0.61242 |
1a3762b6ca5b2ac0fd1a70336fc32952d33d76cf | 8,577 | // Copyright (c) 2022 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 AuthenticationServices
import Combine
import Network
// This protocol is added to aid testing (of DownloadService). It is not
// currently necessarily complete. It should probably be revisited,
// and rethought at a later stage. I'll put // TODO: here so that we might
// find it again.
protocol UserModelController {
var objectDidChange: ObservableObjectPublisher { get }
var user: User? { get }
var client: RWAPI { get }
}
// Conforming to NSObject, so that we can conform to ASWebAuthenticationPresentationContextProviding
final class SessionController: NSObject, UserModelController, ObservablePrePostFactoObject {
private var subscriptions = Set<AnyCancellable>()
// Managing the state of the current session
@Published private(set) var sessionState: SessionState = .unknown
@Published private(set) var userState: UserState = .notLoggedIn
@Published private(set) var permissionState: PermissionState = .notLoaded
// MARK: - ObservablePrePostFactoObject, UserModelController
let objectDidChange = ObservableObjectPublisher()
// MARK: - ObservablePrePostFactoObject
@PublishedPrePostFacto var user: User? {
didSet {
if let user = user {
userState = .loggedIn
if user.permissions == nil {
permissionState = .notLoaded
fetchPermissionsIfNeeded()
} else {
permissionState = .loaded(lastRefreshedDate)
}
} else {
userState = .notLoggedIn
permissionState = .notLoaded
}
}
}
private(set) var client: RWAPI
// MARK: -
private let guardpost: Guardpost
private let connectionMonitor = NWPathMonitor()
private(set) var permissionsService: PermissionsService
var isLoggedIn: Bool {
userState == .loggedIn
}
var hasPermissions: Bool {
if case .loaded = permissionState {
return true
}
return false
}
var hasPermissionToUseApp: Bool {
user?.hasPermissionToUseApp ?? false
}
var hasCurrentDownloadPermissions: Bool {
guard user?.canDownload == true else { return false }
if
case .loaded(let date) = permissionState,
let permissionsLastConfirmedDate = date,
Date.now.timeIntervalSince(permissionsLastConfirmedDate) < .videoPlaybackOfflinePermissionsCheckPeriod
{
return true
}
return false
}
// MARK: - Initializers
init(guardpost: Guardpost) {
dispatchPrecondition(condition: .onQueue(.main))
self.guardpost = guardpost
let user = User.backdoor ?? guardpost.currentUser
client = RWAPI(authToken: user?.token ?? "")
permissionsService = PermissionsService(client: client)
super.init()
self.user = user
prepareSubscriptions()
}
// MARK: - Internal
func login() {
guard userState != .loggingIn else { return }
userState = .loggingIn
guardpost.presentationContextDelegate = self
if isLoggedIn {
if !hasPermissions {
fetchPermissions()
}
} else {
guardpost.login { [weak self] result in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
switch result {
case .failure(let error):
self.userState = .notLoggedIn
self.permissionState = .notLoaded
Failure
.login(from: Self.self, reason: error.localizedDescription)
.log()
case .success(let user):
self.user = user
Event
.login(from: Self.self)
.log()
self.fetchPermissions()
}
}
}
}
}
func fetchPermissionsIfNeeded() {
// Request persmission if an app launch has happened or if it's been over 24 hours since the last permission request once the app enters the foreground
guard shouldRefresh || !hasPermissions else { return }
fetchPermissions()
}
func fetchPermissions() {
// If there's no connection, use the persisted permissions
// The re-fetch/re-store will be done the next time they open the app
guard sessionState == .online else { return }
// Don't repeatedly make the same request
if case .loading = permissionState {
return
}
// No point in requesting permissions when there's no user
guard isLoggedIn else { return }
permissionState = .loading
permissionsService.permissions { result in
DispatchQueue.main.async {
switch result {
case .failure(let error):
enum Permissions {}
Failure
.fetch(from: Permissions.self, reason: error.localizedDescription)
.log()
self.permissionState = .error
case .success(let permissions):
// Check that we have a logged in user. Otherwise this is pointless
guard let user = self.user else { return }
// Update the date that we retrieved the permissions
self.saveOrReplaceRefreshableUpdateDate()
// Update the user
self.user = user.with(permissions: permissions)
// Ensure guardpost is aware, and hence the keychain is updated
self.guardpost.updateUser(with: self.user)
}
}
}
}
func logout() {
guardpost.logout()
userState = .notLoggedIn
permissionState = .notLoaded
user = nil
}
private func prepareSubscriptions() {
$user.sink { [weak self] user in
guard let self = self else { return }
self.client = RWAPI(authToken: user?.token ?? "")
self.permissionsService = PermissionsService(client: self.client)
}
.store(in: &subscriptions)
connectionMonitor.pathUpdateHandler = { [weak self] path in
guard let self = self else { return }
let newState: SessionState = path.status == .satisfied ? .online : .offline
if newState != self.sessionState {
self.objectWillChange.send()
self.sessionState = newState
self.objectDidChange.send()
}
self.fetchPermissionsIfNeeded()
}
connectionMonitor.start(queue: .main)
}
}
// MARK: - Refreshable
extension SessionController: Refreshable {
var refreshableCheckTimeSpan: RefreshableTimeSpan { .short }
}
// MARK: - ASWebAuthenticationPresentationContextProviding
extension SessionController: ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
UIApplication.shared.windows.first!
}
}
// MARK: - Content Access Permissions
extension SessionController {
func canPlay(content: Ownable) -> Bool {
// Can always play free content
if content.free {
return true
}
// If the content isn't free then we must have a user
guard let user = user else { return false }
return content.professional ? user.canStreamPro : user.canStream
}
}
| 32.244361 | 155 | 0.677626 |
db231dc698d4a672d5b422d5ad88316917e84c89 | 1,251 | //
// TumblrFeedUITests.swift
// TumblrFeedUITests
//
// Created by Brandon Paw on 11/18/17.
// Copyright © 2017 Brandon Paw. All rights reserved.
//
import XCTest
class TumblrFeedUITests: XCTestCase {
override func setUp() {
super.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.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.810811 | 182 | 0.664269 |
72176df6695844a2346def6308a4fd8622392d4c | 1,922 |
import UIKit
import WebKit
import RxSwift
import RxCocoa
import SnapKit
class Web_VC: UIViewController {
private var closeButton = UIButton()
private var webView = WebView()
private var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.layout()
self.bind()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
}
extension Web_VC {
private func setup() {
self.view.backgroundColor = .white
self.closeButton.setTitle("close", for: .normal)
self.closeButton.setTitleColor(.black, for: .normal)
self.view.addSubview(self.closeButton)
self.webView.backgroundColor = .lightGray
self.webView.load(URLRequest(url: URL(string: "https://naver.com")!))
self.view.addSubview(self.webView)
}
private func layout() {
self.closeButton.snp.makeConstraints { maker in
maker.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(16.0)
maker.leading.equalToSuperview().offset(16.0)
}
self.webView.snp.makeConstraints { maker in
maker.top.equalTo(self.closeButton.snp.bottom).offset(16.0)
maker.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottomMargin)
maker.leading.trailing.equalToSuperview()
}
}
private func bind() {
self.closeButton.rx.tap
.throttle(.milliseconds(500), scheduler: MainScheduler.instance)
.bind { [weak self] _ in
self?.onClose()
}
.disposed(by: self.disposeBag)
}
}
extension Web_VC {
}
extension Web_VC {
private func onClose() {
self.dismiss(animated: true, completion: nil)
}
}
| 22.611765 | 81 | 0.630593 |
e281d05b98866897aab96899326797f2697d8802 | 9,986 | import Commandant
import Foundation
import SourceKittenFramework
import SwiftLintFramework
typealias File = String
typealias Arguments = [String]
enum CompilerInvocations {
case buildLog(compilerInvocations: [String])
case compilationDatabase(compileCommands: [File: Arguments])
func arguments(forFile path: String?) -> [String] {
return path.flatMap { path in
switch self {
case let .buildLog(compilerInvocations):
return CompilerArgumentsExtractor
.compilerArgumentsForFile(path, compilerInvocations: compilerInvocations)
case let .compilationDatabase(compileCommands):
return compileCommands[path]
}
} ?? []
}
}
enum LintOrAnalyzeModeWithCompilerArguments {
case lint
case analyze(allCompilerInvocations: CompilerInvocations)
}
private func resolveParamsFiles(args: [String]) -> [String] {
return args.reduce(into: []) { (allArgs: inout [String], arg: String) -> Void in
if arg.hasPrefix("@"), let contents = try? String(contentsOfFile: String(arg.dropFirst())) {
allArgs.append(contentsOf: resolveParamsFiles(args: contents.split(separator: "\n").map(String.init)))
} else {
allArgs.append(arg)
}
}
}
struct LintableFilesVisitor {
let paths: [String]
let action: String
let useSTDIN: Bool
let quiet: Bool
let useScriptInputFiles: Bool
let forceExclude: Bool
let useExcludingByPrefix: Bool
let cache: LinterCache?
let parallel: Bool
let allowZeroLintableFiles: Bool
let mode: LintOrAnalyzeModeWithCompilerArguments
let block: (CollectedLinter) -> Void
init(paths: [String], action: String, useSTDIN: Bool,
quiet: Bool, useScriptInputFiles: Bool, forceExclude: Bool, useExcludingByPrefix: Bool,
cache: LinterCache?, parallel: Bool,
allowZeroLintableFiles: Bool, block: @escaping (CollectedLinter) -> Void) {
self.paths = resolveParamsFiles(args: paths)
self.action = action
self.useSTDIN = useSTDIN
self.quiet = quiet
self.useScriptInputFiles = useScriptInputFiles
self.forceExclude = forceExclude
self.useExcludingByPrefix = useExcludingByPrefix
self.cache = cache
self.parallel = parallel
self.mode = .lint
self.allowZeroLintableFiles = allowZeroLintableFiles
self.block = block
}
private init(paths: [String], action: String, useSTDIN: Bool, quiet: Bool,
useScriptInputFiles: Bool, forceExclude: Bool, useExcludingByPrefix: Bool,
cache: LinterCache?, compilerInvocations: CompilerInvocations?,
allowZeroLintableFiles: Bool, block: @escaping (CollectedLinter) -> Void) {
self.paths = resolveParamsFiles(args: paths)
self.action = action
self.useSTDIN = useSTDIN
self.quiet = quiet
self.useScriptInputFiles = useScriptInputFiles
self.forceExclude = forceExclude
self.useExcludingByPrefix = useExcludingByPrefix
self.cache = cache
self.parallel = true
if let compilerInvocations = compilerInvocations {
self.mode = .analyze(allCompilerInvocations: compilerInvocations)
} else {
self.mode = .lint
}
self.block = block
self.allowZeroLintableFiles = allowZeroLintableFiles
}
static func create(_ options: LintOrAnalyzeOptions,
cache: LinterCache?,
allowZeroLintableFiles: Bool,
block: @escaping (CollectedLinter) -> Void)
-> Result<LintableFilesVisitor, CommandantError<()>> {
let compilerInvocations: CompilerInvocations?
if options.mode == .lint {
compilerInvocations = nil
} else {
switch loadCompilerInvocations(options) {
case let .success(invocations):
compilerInvocations = invocations
case let .failure(error):
return .failure(error)
}
}
let visitor = LintableFilesVisitor(paths: options.paths, action: options.verb.bridge().capitalized,
useSTDIN: options.useSTDIN, quiet: options.quiet,
useScriptInputFiles: options.useScriptInputFiles,
forceExclude: options.forceExclude,
useExcludingByPrefix: options.useExcludingByPrefix,
cache: cache,
compilerInvocations: compilerInvocations,
allowZeroLintableFiles: allowZeroLintableFiles, block: block)
return .success(visitor)
}
func shouldSkipFile(atPath path: String?) -> Bool {
switch self.mode {
case .lint:
return false
case let .analyze(compilerInvocations):
let compilerArguments = compilerInvocations.arguments(forFile: path)
return compilerArguments.isEmpty
}
}
func linter(forFile file: SwiftLintFile, configuration: Configuration) -> Linter {
switch self.mode {
case .lint:
return Linter(file: file, configuration: configuration, cache: cache)
case let .analyze(compilerInvocations):
let compilerArguments = compilerInvocations.arguments(forFile: file.path)
return Linter(file: file, configuration: configuration, compilerArguments: compilerArguments)
}
}
private static func loadCompilerInvocations(_ options: LintOrAnalyzeOptions)
-> Result<CompilerInvocations, CommandantError<()>> {
if !options.compilerLogPath.isEmpty {
let path = options.compilerLogPath
guard let compilerInvocations = self.loadLogCompilerInvocations(path) else {
return .failure(
.usageError(description: "Could not read compiler log at path: '\(path)'")
)
}
return .success(.buildLog(compilerInvocations: compilerInvocations))
} else if !options.compileCommands.isEmpty {
let path = options.compileCommands
switch self.loadCompileCommands(path) {
case .success(let compileCommands):
return .success(.compilationDatabase(compileCommands: compileCommands))
case .failure(let error):
return .failure(
.usageError(
description: "Could not read compilation database at path: '\(path)' \(error.description)"
)
)
}
}
return .failure(.usageError(description: "Could not read compiler invocations"))
}
private static func loadLogCompilerInvocations(_ path: String) -> [String]? {
if let data = FileManager.default.contents(atPath: path),
let logContents = String(data: data, encoding: .utf8) {
if logContents.isEmpty {
return nil
}
return CompilerArgumentsExtractor.allCompilerInvocations(compilerLogs: logContents)
}
return nil
}
private static func loadCompileCommands(_ path: String) -> Result<[File: Arguments], CompileCommandsLoadError> {
guard let jsonContents = FileManager.default.contents(atPath: path) else {
return .failure(.nonExistentFile(path))
}
guard let object = try? JSONSerialization.jsonObject(with: jsonContents),
let compileDB = object as? [[String: Any]] else {
return .failure(.malformedCommands(path))
}
// Convert the compilation database to a dictionary, with source files as keys and compiler arguments as values.
//
// Compilation databases are an array of dictionaries. Each dict has "file" and "arguments" keys.
var commands = [File: Arguments]()
for (index, entry) in compileDB.enumerated() {
guard let file = entry["file"] as? String else {
return .failure(.malformedFile(path, index))
}
guard var arguments = entry["arguments"] as? [String] else {
return .failure(.malformedArguments(path, index))
}
guard arguments.contains(file) else {
return .failure(.missingFileInArguments(path, index, arguments))
}
// Compilation databases include the compiler, but it's left out when sending to SourceKit.
if arguments.first == "swiftc" {
arguments.removeFirst()
}
commands[file] = CompilerArgumentsExtractor.filterCompilerArguments(arguments)
}
return .success(commands)
}
}
private enum CompileCommandsLoadError: Error {
case nonExistentFile(String)
case malformedCommands(String)
case malformedFile(String, Int)
case malformedArguments(String, Int)
case missingFileInArguments(String, Int, [String])
var description: String {
switch self {
case let .nonExistentFile(path):
return "Could not read compile commands file at '\(path)'"
case let .malformedCommands(path):
return "Compile commands file at '\(path)' isn't in the correct format"
case let .malformedFile(path, index):
return "Missing or invalid (must be a string) 'file' key in \(path) at index \(index)"
case let .malformedArguments(path, index):
return "Missing or invalid (must be an array of strings) 'arguments' key in \(path) at index \(index)"
case let .missingFileInArguments(path, index, arguments):
return "Entry in \(path) at index \(index) has 'arguments' which do not contain the 'file': \(arguments)"
}
}
}
| 40.759184 | 120 | 0.620369 |
226d692944b728b15c633e4f65ea4e2848288807 | 405 | //
// IdentifiableClass.swift
// OmniBLE
//
// Created by Nathan Racklyeft on 2/9/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
protocol IdentifiableClass: AnyObject {
static var className: String { get }
}
extension IdentifiableClass {
static var className: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
| 18.409091 | 73 | 0.698765 |
de1be478d277fd7ce0ed04d26afdec1baf40525a | 327 | //
// ViewController.swift
// Example_01
//
// Created by Aleksandr Sychev on 18/11/2019.
// Copyright © 2019 Aleksandr Sychev. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 15.571429 | 59 | 0.70948 |
2f5bad900143b10d5b3e93711388561cefa1f970 | 9,739 | //
// AppleUtils.swift
// Segment
//
// Created by Brandon Sneed on 2/26/21.
//
import Foundation
// MARK: - iOS, tvOS, Catalyst
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
import SystemConfiguration
import UIKit
#if !os(tvOS)
import WebKit
#endif
internal class iOSVendorSystem: VendorSystem {
private let device = UIDevice.current
override var manufacturer: String {
return "Apple"
}
override var type: String {
#if os(iOS)
return "ios"
#elseif os(tvOS)
return "tvos"
#elseif targetEnvironment(macCatalyst)
return "macos"
#else
return "unknown"
#endif
}
override var model: String {
// eg. "iPhone5,1"
return deviceModel()
}
override var name: String {
// eg. "iPod Touch"
return device.model
}
override var identifierForVendor: String? {
return device.identifierForVendor?.uuidString
}
override var systemName: String {
return device.systemName
}
override var systemVersion: String {
device.systemVersion
}
override var screenSize: ScreenSize {
let screenSize = UIScreen.main.bounds.size
return ScreenSize(width: Double(screenSize.width), height: Double(screenSize.height))
}
override var userAgent: String? {
#if !os(tvOS)
var userAgent: String?
if Thread.isMainThread {
userAgent = WKWebView().value(forKey: "userAgent") as? String
} else {
DispatchQueue.main.sync {
userAgent = WKWebView().value(forKey: "userAgent") as? String
}
}
return userAgent
#else
// webkit isn't on tvos
return "unknown"
#endif
}
override var connection: ConnectionStatus {
return connectionStatus()
}
override var requiredPlugins: [PlatformPlugin] {
return [iOSLifecycleMonitor(), DeviceToken()]
}
private func deviceModel() -> String {
var name: [Int32] = [CTL_HW, HW_MACHINE]
var size: Int = 2
sysctl(&name, 2, nil, &size, nil, 0)
var hw_machine = [CChar](repeating: 0, count: Int(size))
sysctl(&name, 2, &hw_machine, &size, nil, 0)
let model = String(cString: hw_machine)
return model
}
}
#endif
// MARK: - watchOS
#if os(watchOS)
import WatchKit
import Network
internal class watchOSVendorSystem: VendorSystem {
private let device = WKInterfaceDevice.current()
override var manufacturer: String {
return "Apple"
}
override var type: String {
return "watchos"
}
override var model: String {
return deviceModel()
}
override var name: String {
return device.model
}
override var identifierForVendor: String? {
return device.identifierForVendor?.uuidString
}
override var systemName: String {
return device.systemName
}
override var systemVersion: String {
device.systemVersion
}
override var screenSize: ScreenSize {
let screenSize = device.screenBounds.size
return ScreenSize(width: Double(screenSize.width), height: Double(screenSize.height))
}
override var userAgent: String? {
return nil
}
override var connection: ConnectionStatus {
let path = NWPathMonitor().currentPath
let interfaces = path.availableInterfaces
var cellular = false
var wifi = false
for interface in interfaces {
if interface.type == .cellular {
cellular = true
} else if interface.type == .wifi {
wifi = true
}
}
if cellular {
return ConnectionStatus.online(.cellular)
} else if wifi {
return ConnectionStatus.online(.wifi)
}
return ConnectionStatus.unknown
}
override var requiredPlugins: [PlatformPlugin] {
return [watchOSLifecycleMonitor()]
}
private func deviceModel() -> String {
var name: [Int32] = [CTL_HW, HW_MACHINE]
var size: Int = 2
sysctl(&name, 2, nil, &size, nil, 0)
var hw_machine = [CChar](repeating: 0, count: Int(size))
sysctl(&name, 2, &hw_machine, &size, nil, 0)
let model = String(cString: hw_machine)
return model
}
}
#endif
// MARK: - macOS
#if os(macOS)
import Cocoa
import WebKit
internal class MacOSVendorSystem: VendorSystem {
private let device = ProcessInfo.processInfo
override var manufacturer: String {
return "Apple"
}
override var type: String {
return "macos"
}
override var model: String {
return deviceModel()
}
override var name: String {
return device.hostName
}
override var identifierForVendor: String? {
// apple suggested to use this for receipt validation
// in MAS, works for this too.
return macAddress(bsd: "en0")
}
override var systemName: String {
return device.operatingSystemVersionString
}
override var systemVersion: String {
return String(format: "%ld.%ld.%ld",
device.operatingSystemVersion.majorVersion,
device.operatingSystemVersion.minorVersion,
device.operatingSystemVersion.patchVersion)
}
override var screenSize: ScreenSize {
let screenSize = NSScreen.main?.frame.size ?? CGSize(width: 0, height: 0)
return ScreenSize(width: Double(screenSize.width), height: Double(screenSize.height))
}
override var userAgent: String? {
var userAgent: String?
if Thread.isMainThread {
userAgent = WKWebView().value(forKey: "userAgent") as? String
} else {
DispatchQueue.main.sync {
userAgent = WKWebView().value(forKey: "userAgent") as? String
}
}
return userAgent
}
override var connection: ConnectionStatus {
return connectionStatus()
}
override var requiredPlugins: [PlatformPlugin] {
return [macOSLifecycleMonitor(), DeviceToken()]
}
private func deviceModel() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
private func macAddress(bsd : String) -> String? {
let MAC_ADDRESS_LENGTH = 6
let separator = ":"
var length : size_t = 0
var buffer : [CChar]
let bsdIndex = Int32(if_nametoindex(bsd))
if bsdIndex == 0 {
return nil
}
let bsdData = Data(bsd.utf8)
var managementInfoBase = [CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, bsdIndex]
if sysctl(&managementInfoBase, 6, nil, &length, nil, 0) < 0 {
return nil;
}
buffer = [CChar](unsafeUninitializedCapacity: length, initializingWith: {buffer, initializedCount in
for x in 0..<length { buffer[x] = 0 }
initializedCount = length
})
if sysctl(&managementInfoBase, 6, &buffer, &length, nil, 0) < 0 {
return nil;
}
let infoData = Data(bytes: buffer, count: length)
let indexAfterMsghdr = MemoryLayout<if_msghdr>.stride + 1
let rangeOfToken = infoData[indexAfterMsghdr...].range(of: bsdData)!
let lower = rangeOfToken.upperBound
let upper = lower + MAC_ADDRESS_LENGTH
let macAddressData = infoData[lower..<upper]
let addressBytes = macAddressData.map { String(format:"%02x", $0) }
return addressBytes.joined(separator: separator)
}
}
#endif
// MARK: - Reachability
#if os(iOS) || os(tvOS) || os(macOS) || targetEnvironment(macCatalyst)
#if os(macOS)
import SystemConfiguration
#endif
extension ConnectionStatus {
init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
#if !os(macOS)
let isCellular = flags.contains(.isWWAN)
#endif
if !connectionRequired && isReachable {
#if !os(macOS)
if isCellular {
self = .online(.cellular)
} else {
self = .online(.wifi)
}
#else
self = .online(.wifi)
#endif
} else {
self = .offline
}
}
}
internal func connectionStatus() -> ConnectionStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}) else {
return .unknown
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .unknown
}
return ConnectionStatus(reachabilityFlags: flags)
}
#endif
| 26.536785 | 108 | 0.597597 |
9156606f87706321d289af7b2b6354ca5899486d | 1,792 | //
// ApduUtils.swift
// apduKit
// All the APDU cheat codes on planet earth.
// Created by Iain Munro on 27/08/2018.
// Copyright © 2018 UL-TS. All rights reserved.
//
import Foundation
public struct TLVInfo {
///Tag
var tag: int
///Length of the TLV structure
var length: short
///At what offset the actual data (value) starts
var dataOffset: int
}
public class ApduUtils {
/**
* Parses a TLV structure and returns the tag, length and dataOffset
* @param data TLV data
* @return TLVInfo containing TLV information
*/
func parseTLV(bytes data: [byte]) -> TLVInfo? {
if data.count < Constants.BYTE_OFFSET_TILL_LENGTH {
return nil
}
var dataOffset = Constants.BYTE_OFFSET_TILL_LENGTH
let tag = Int(data[0])
var lengthBytes = [data[1]]
//Check if the length value exceeds 255
var bits = ConversionUtils.byteToBits(byte: data[1])
//If the first bit is 1, this tells us that the value is higher than 255.
//If its 1, just read the byte.
if bits[0] == 1 {
bits[0] = 0//Skip the firt bit. Then read the bits after.
let lengthValueSize = int(ConversionUtils.bitsToByte(bits: bits))
let lengthEndOffset = int(Constants.BYTE_OFFSET_TILL_LENGTH) + lengthValueSize
if data.count < lengthEndOffset {
return nil
}
lengthBytes = Array(data[Int(Constants.BYTE_OFFSET_TILL_LENGTH)...Int(lengthEndOffset)])
dataOffset = Int(lengthEndOffset)
}
guard let length = try? ConversionUtils.fromBytesToShort(lengthBytes) else { return nil }
return TLVInfo(tag: int(tag), length: short(length), dataOffset: int(dataOffset))
}
}
| 33.811321 | 100 | 0.629464 |
268d513901ce463ba1219745d7e854a70ecfd03a | 1,458 | //
// PhoneCodeSendViewModel.swift
// WalletCore
//
// Created by Lyubomir Marinov on 12.08.18.
// Copyright © 2018 Lykke. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public class PhoneCodeVerifyViewModel {
// IN:
/// Trigger to call for networking
public let checkCodeTrigger = PublishSubject<Void>()
/// Store the sms code to be verified
public let codeInputSubject = PublishSubject<String>()
// OUT:
/// Received access token
public let accessTokenObservable: Observable<String?>
/// Loading view model
public let loadingViewModel: LoadingViewModel
/// Errors occured
public let errors: Observable<[AnyHashable: Any]>
private let disposeBag = DisposeBag()
public init(authManager: LWRxAuthManager = LWRxAuthManager.instance) {
let verifySmsCodeRequest = checkCodeTrigger.asObservable()
.withLatestFrom(codeInputSubject.asObservable())
.flatMapLatest { authManager.phoneCodeVerify.request(withParams: $0) }
.shareReplay(1)
self.accessTokenObservable = verifySmsCodeRequest
.filterSuccess()
.map { $0.accessToken }
self.loadingViewModel = LoadingViewModel([
verifySmsCodeRequest.isLoading()])
self.errors = Observable.merge([
verifySmsCodeRequest.filterError()
])
}
}
| 27.509434 | 82 | 0.648834 |
fe6fc11d702d6d10c31bfd1199b6d860253a8941 | 339 | //
// DoubleExtension.swift
// SwiftExtensions
//
// Created by Klemen Kosir on 17. 12. 16.
// Copyright © 2016 Klemen Kosir. All rights reserved.
//
import Foundation
public extension Double {
var degreesToRadians : Double {
return self * M_PI / 180.0
}
var radiansToDegrees : Double {
return self * 180.0 / M_PI
}
}
| 14.73913 | 55 | 0.669617 |
905612c6ed9dc33ebb9902a74511fc7fedac6f2c | 2,012 | //
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
/// Builds ``AuthorizationRequirement``s.
@resultBuilder
public enum AuthorizationRequirementsBuilder<Element: Authenticatable> {
/// Builds the ``AuthorizationRequirements`` component for a single ``AuthorizationRequirement`` expression.
public static func buildExpression<Requirement: AuthorizationRequirement>(_ expression: Requirement) -> AuthorizationRequirements<Element>
where Requirement.Element == Element {
AuthorizationRequirements(expression)
}
/// Builds a block of ``AuthorizationRequirements`` components.
public static func buildBlock(_ components: AuthorizationRequirements<Element>...) -> AuthorizationRequirements<Element> {
AuthorizationRequirements(components)
}
/// Builds the first of a ``AuthorizationRequirements`` either block.
public static func buildEither(first component: AuthorizationRequirements<Element>) -> AuthorizationRequirements<Element> {
component
}
/// Builds the second of a ``AuthorizationRequirements`` either block.
public static func buildEither(second component: AuthorizationRequirements<Element>) -> AuthorizationRequirements<Element> {
component
}
/// Builds an array of ``AuthorizationRequirements``.
public static func buildArray(_ components: [AuthorizationRequirements<Element>]) -> AuthorizationRequirements<Element> {
AuthorizationRequirements(components)
}
/// Builds an optional ``AuthorizationRequirements``.
public static func buildOptional(_ component: AuthorizationRequirements<Element>?) -> AuthorizationRequirements<Element> {
if let component = component {
return AuthorizationRequirements(component)
}
return AuthorizationRequirements()
}
}
| 43.73913 | 142 | 0.744533 |
f8f8ff94c0ecb3f6561b383d38e16a4534727dd4 | 479 | import Cocoa
import GRDBCipher
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
let dbQueue = DatabaseQueue()
// Make sure FTS5 is enabled
try! dbQueue.write { db in
try db.create(virtualTable: "document", using: FTS5()) { t in
t.column("content")
}
}
}
}
| 25.210526 | 73 | 0.620042 |
691b484c77b57415921a8d6d65951e3e74bcf164 | 4,425 | import SnapshotTesting
import XCTest
import RxSwift
import RxBlocking
@testable import BabylonDemo
final class DetailViewControllerSnapshotTests: XCTestCase {
final class DetailNetworkControllerMock: DetailNetworkControllerProtocol {
let session: URLSession
let taskKit: DetailTaskKitProtocol
var expectedUser = User(id: 1, username: "dd", name: "")
var expectedComments = [Comment]()
convenience init(expectedUser: User, expectedComments: [Comment]) {
self.init(with: DetailTaskKit(), in: .shared)
self.expectedUser = expectedUser
self.expectedComments = expectedComments
}
init(with taskKit: DetailTaskKitProtocol = DetailTaskKit(), in session: URLSession = .shared) {
self.taskKit = taskKit
self.session = session
}
init(with session: URLSession = .shared) {
self.taskKit = DetailTaskKit()
self.session = session
}
func fetchUsers(withId: Int) -> Observable<User> {
return .just(expectedUser)
}
func fetchComments(forPostId: Int) -> Observable<[Comment]> {
return .just(expectedComments)
}
}
var sut: DetailViewController!
var model: DetailViewModel!
var persistanceController: PersistanceController!
override func setUp() {
super.setUp()
record = false
}
override func tearDown() {
persistanceController.remove(User.self)
persistanceController.remove(Comment.self)
model = nil
sut = nil
super.tearDown()
}
func testWithEmptyDetails() {
// Arrange
let post = Post(userId: 1, id: 2, title: "", body: "")
let user = User(id: 1, username: "username", name: "name")
let comments = [Comment]()
sut = setUpSut(post: post, user: user, comments: comments)
let sutInNavigationController = sut.embededInNavigationController
// Act & Assert
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhoneSe))
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhone8))
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhoneX))
}
func testWithDetails() {
// Arrange
let post = Post(userId: 1, id: 2, title: "title", body: "body")
let user = User(id: 1, username: "username", name: "name")
let comments = [
Comment(id: 1, postId: 1),
Comment(id: 2, postId: 1)
]
sut = setUpSut(post: post, user: user, comments: comments)
let sutInNavigationController = sut.embededInNavigationController
// Act & Assert
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhoneSe))
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhone8))
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhoneX))
}
func testWithLongDetails() {
// Arrange
let post = Post(userId: 1, id: 2, title: "title", body: "body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body body ")
let user = User(id: 1, username: "username", name: "name")
let comments = [
Comment(id: 1, postId: 1),
Comment(id: 2, postId: 1)
]
sut = setUpSut(post: post, user: user, comments: comments)
let sutInNavigationController = sut.embededInNavigationController
// Act & Assert
assertSnapshot(matching: sutInNavigationController, as: .image(on: .iPhoneX))
}
}
private extension DetailViewControllerSnapshotTests {
func setUpSut(post: Post, user: User, comments: [Comment]) -> DetailViewController {
let networkController = DetailNetworkControllerMock(expectedUser: user, expectedComments: comments)
persistanceController = PersistanceController(userDefaults: .test)
model = DetailViewModel(with: post, networkController: networkController, persistanceController: persistanceController)
return DetailViewController(viewModel: model)
}
}
| 36.270492 | 392 | 0.653333 |
462e030fed8eb13244e5c9cc46a16a9f66c0bd8e | 1,040 | // Created by Eric Marchand on 07/06/2017.
// Copyright © 2017 Eric Marchand. All rights reserved.
//
import Foundation
extension MomModel: XMLConvertible {
public var xml: String {
var output = "<model type=\"\(type)\" documentVersion=\"\(documentVersion)\""
output += " lastSavedToolsVersion=\"\(lastSavedToolsVersion)\" systemVersion=\"\(systemVersion)\""
output += " minimumToolsVersion=\"\(minimumToolsVersion)\" sourceLanguage=\"\(language)\""
output += " userDefinedModelVersionIdentifier=\"\(userDefinedModelVersionIdentifier)\">\n"
for entity in entities {
output += entity.xml
output += "\n"
}
if elements.isEmpty {
output += "<elements/>"
} else {
output += " <elements>\n"
for element in elements {
output += element.xml
output += "\n"
}
output += " </elements>\n"
}
output += "</model>\n"
return output
}
}
| 29.714286 | 106 | 0.553846 |
7aac442c5cd05636f117c729952f9becc8936b9a | 3,809 | //
// WDPhotoSeletorCollectionViewCell.swift
// WDPhotoSelector-Swift
//
// Created by wudan on 2019/4/20.
// Copyright © 2019 com.wudan. All rights reserved.
//
import UIKit
import FLAnimatedImage
// MARK: - 相册Cell
class WDPhotoSeletorCollectionViewCell: UICollectionViewCell {
/// 主体图片
lazy var imageView: UIImageView = {
let i = UIImageView.init()
i.clipsToBounds = true
i.contentMode = .scaleAspectFill
i.translatesAutoresizingMaskIntoConstraints = false
return i
}()
var selectActionBlock:((_ model: AssetModel, _ buttonIsSelected: Bool) -> Void)?
/// 选择按钮
lazy var selectButton: UIButton = {
let b = UIButton.init(type: .custom)
b.titleLabel?.font = UIFont.systemFont(ofSize: 13)
b.translatesAutoresizingMaskIntoConstraints = false
b.setImage(nil, for: .selected)
b.layer.cornerRadius = 12.5 * cSCREEN_RETIO
b.layer.masksToBounds = true
b.addTarget(self, action: #selector(selectButtonTouched(sender:)), for: .touchUpInside)
b.setBackgroundImage(UIImage(named: "picker_unselected"), for: .normal)
b.setBackgroundImage(UIImage(named: "picker_selected"), for: .selected)
return b
}()
private var _model:AssetModel!
func setupView(with model: AssetModel) {
_model = model
selectButton.isSelected = model.picked
if !model.picked {
selectButton.setTitle("", for: .normal)
} else {
selectButton.setTitle("\(model.number)", for: .normal)
}
WDPhotoSelectorManager.defaultManager.getPhoto(asset: model.asset!, photoWidth: cSCREEN_WIDTH) { (image, info) -> (Void) in
self.imageView.image = image
}
}
@objc func selectButtonTouched(sender: UIButton) {
sender.shakeAniamtion()
if selectActionBlock != nil {
selectActionBlock!(_model!, sender.isSelected)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
let con1 = NSLayoutConstraint.init(item: imageView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 0)
let con2 = NSLayoutConstraint.init(item: imageView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0)
let con3 = NSLayoutConstraint.init(item: imageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0)
let con4 = NSLayoutConstraint.init(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0)
self.contentView.addConstraints([con1, con2, con3, con4])
contentView.addSubview(selectButton)
let con5 = NSLayoutConstraint.init(item: selectButton, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -8 * cSCREEN_RETIO)
let con6 = NSLayoutConstraint.init(item: selectButton, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 8 * cSCREEN_RETIO)
let con7 = NSLayoutConstraint.init(item: selectButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 25 * cSCREEN_RETIO)
let con8 = NSLayoutConstraint.init(item: selectButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 25 * cSCREEN_RETIO)
contentView.addConstraints([con5, con6, con7, con8])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 45.345238 | 191 | 0.67288 |
0300d30b2f195e4881f314a3d48d1f62875ebfc8 | 2,734 | /*
Copyright (c) 2016-2017 M.I. Hollemans
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import UIKit
extension UIImage {
/**
Converts the image into an array of RGBA bytes.
*/
@nonobjc public func toByteArray() -> [UInt8] {
let width = Int(size.width)
let height = Int(size.height)
var bytes = [UInt8](repeating: 0, count: width * height * 4)
bytes.withUnsafeMutableBytes { ptr in
if let context = CGContext(
data: ptr.baseAddress,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) {
if let image = self.cgImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.draw(image, in: rect)
}
}
}
return bytes
}
/**
Creates a new UIImage from an array of RGBA bytes.
*/
@nonobjc public class func fromByteArray(_ bytes: UnsafeMutableRawPointer,
width: Int,
height: Int) -> UIImage {
if let context = CGContext(data: bytes, width: width, height: height,
bitsPerComponent: 8, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue),
let cgImage = context.makeImage() {
return UIImage(cgImage: cgImage, scale: 0, orientation: .up)
} else {
return UIImage()
}
}
}
| 38.507042 | 88 | 0.633504 |
e6b14d153e74067d8abd7240c4eda8731e6dd310 | 1,310 | //
// GetCurrentCartRequestTests.swift
// WhiteLabelECommerce
//
// Created by Marcos Vinicius Brito on 18/02/22.
//
@testable import WhiteLabelECommerce
import XCTest
class GetCurrentCartRequestTests: XCTestCase {
func testGetCurrentCartRequest_init_ShouldRetainCorrectValues() {
// Arrange
let sut = GetCurrentCartRequest(userId: 1)
// Assert
XCTAssertEqual(sut.baseURL, "https://fakestoreapi.com/carts/user/1")
XCTAssertEqual(sut.method, .get)
XCTAssertEqual(sut.contentType, "application/json")
XCTAssertNil(sut.params)
XCTAssertNil(sut.body)
XCTAssertNil(sut.headers)
}
func testGetGetCurrentCartRequest_asURLRequest_ShouldReturnURLRequest() {
// Arrange
let sut = GetCurrentCartRequest(userId: 1)
// Act
let urlRequest = sut.asURLRequest()
// Assert
XCTAssertNotNil(urlRequest)
XCTAssertEqual(urlRequest?.url?.absoluteString, "https://fakestoreapi.com/carts/user/1")
XCTAssertNil(urlRequest?.httpBody)
XCTAssertNotNil(urlRequest?.allHTTPHeaderFields)
XCTAssertEqual(urlRequest?.allHTTPHeaderFields?["Content-Type"], "application/json")
XCTAssertEqual(urlRequest?.allHTTPHeaderFields?["Accept"], "application/json")
}
}
| 31.95122 | 96 | 0.696947 |
ed12c19b034b752da02a1199fc386bced42c75b3 | 489 | //
// AppDelegate.swift
// TestMac
//
// Created by Hench on 7/13/20.
// Copyright © 2020 Hench. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 18.111111 | 71 | 0.705521 |
21f1ec21393cdb44ad54ed04ae91222ba5cab6c6 | 1,089 | //
// ViewController.swift
// Prework
//
// Created by Linxi Xu on 1/30/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var tipAmountLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calculateTip(_ sender: Any) {
// Get bill amount from text field input
let bill = Double(billAmountTextField.text!) ?? 0
// Get Total tip by multiplying tip * tip Percentage
let tipPercentages = [0.15, 0.18, 0.2]
let tip = bill *
tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
// Update Tip AMount Lebel
tipAmountLabel.text = String(format: "$%.2f", tip)
// Update Total Amount
totalLabel.text = String(format: "$%.2f", total)
}
}
| 25.928571 | 61 | 0.615243 |
87888aa5e54fb0f3d04ac81ecb3afd703e699eb8 | 828 | //
// SplashInteractor.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on 28/06/2017.
// Copyright © 2017 {{ cookiecutter.company_name }}. All rights reserved.
//
import Foundation
import RxSwift
protocol SplashInteractorProtocol {
func validateUserWelcomeStatus() -> Single<BoolProcessResult>
}
class SplashInteractor: SplashInteractorProtocol {
var process: SplashProcessProtocol?
init(process: SplashProcessProtocol?) {
self.process = process
}
func validateUserWelcomeStatus() -> Single<BoolProcessResult> {
return process?.checkUserWelcome().delaySubscription(RxTimeInterval(2), scheduler: MainScheduler.asyncInstance) ?? Single.just(BoolProcessResult(status: ProcessResult.Status.unknown, resultValue: false))
}
}
| 29.571429 | 212 | 0.733092 |
d6d0d0fe6aa8d471f954f7f8aab3a57a21a765b7 | 29,073 | /**
* 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
import SceneKit
import ARKit
// MARK: - Game State
enum GameState: Int16 { //게임 상태의 열거형
case detectSurface // Scan playable surface (Plane Detection On)
//ARKit은 주변을 파악하고 표면 감지하는 데 시간이 걸린다. 게임이 이 상태에 있는 동안, 플레이어는 테이블 같은 적당한
//수평 표면을 스캔해야 한다. 제대로 감지됐다면 Start 버튼을 눌러 게임을 할 수 있고 상태가 변경된다. p.98
case pointToSurface // Point to surface to see focus point (Plane Detection Off)
//감지된 표면에서 포커스 커서를 볼 수 있다. 주사위가 던져질 목표지점을 표시한다. p.98
case swipeToPlay // Focus point visible on surface, swipe up to play
//위쪽으로 스와이프하여 주사위를 던진다. p.99
}
class ViewController: UIViewController {
// MARK: - Properties
var trackingStatus: String = "" //상태를 알려주기 위한 문자열
var statusMessage: String = ""
var gameState: GameState = .detectSurface //게임의 상태 속성. default 상태
var focusPoint:CGPoint! //레이 캐스팅에 사용할 화면상 위치
var focusNode: SCNNode! //포커스 노드
var diceNodes: [SCNNode] = [] //주사위 노드들의 배열
var lightNode: SCNNode! //광원
var diceCount: Int = 5 //주사위의 수를 나타내는 카운터
var diceStyle: Int = 0 //스타일 전환에 사용할 index
var diceOffset: [SCNVector3] = [SCNVector3(0.0,0.0,0.0),
SCNVector3(-0.05, 0.00, 0.0),
SCNVector3(0.05, 0.00, 0.0),
SCNVector3(-0.05, 0.05, 0.02),
SCNVector3(0.05, 0.05, 0.02)]
//주사위의 위치 offset. AR로 주사위를 던질 때, 정확히 ARCamera 상의 위치에 생성하지 않는다.
//위치를 현실적으로 보정해준다.
// MARK: - Outlets
@IBOutlet var sceneView: ARSCNView!
//ARSCNView는 카메라의 라이브 배경 이미지 위에 3D scene 을 오버레이할 수 있다.
//ARKit과 SceneKit 간의 완벽한 통합을 제공한다.
//ARSCNView는 기본적으로 SceneKit 뷰이다. 여기에는 ARKit의 모션 추적 및 이미지 처리를 담당하는 ARSession
//객체가 포함된다. 이것은 세션 기반으로 ARSession을 생성 한 다음 실행하여 AR Tracking 프로세스를 시작해야 한다.
//SpriteKit과 ARKit을 통합한 ARSKView도 있다. 2D SpriteKit 컨텐츠를 사용하는 경우 사용한다.
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var styleButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
// MARK: - Actions
@IBAction func startButtonPressed(_ sender: Any) {
self.startGame()
}
@IBAction func styleButtonPressed(_ sender: Any) {
diceStyle = diceStyle >= 4 ? 0 : diceStyle + 1
//5가지 스타일을 반복한다.
}
@IBAction func resetButtonPressed(_ sender: Any) {
self.resetGame()
}
@IBAction func swipeUpGestureHandler(_ sender: Any) {
guard gameState == .swipeToPlay else { return } //게임이 시작할 상태가 아닐 때에 주사위를 던져선 안 된다.
//게임이 시작된면, .swipeToPlay 상태가 되고, 그 때에만 스와이프 동작을 허용한다.
guard let frame = self.sceneView.session.currentFrame else { return }
//currentFrame은 ARScene의 캡쳐된 이미지, AR 카메라, 조명, 앵커, 특징점과 같은 정보를 가지고 있다.
//세션의 가장 최근 ARScene 정보가 포함된 비디오 프레임 이미지
for count in 0..<diceCount {
throwDiceNode(transform: SCNMatrix4(frame.camera.transform),
offset: diceOffset[count])
//카메라의 위치와 회전 정보를 행렬로 변환하여 주사위를 던진다.
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//터치가 시작될 때 트리거 된다.
DispatchQueue.main.async {
if let touchLocation = touches.first?.location(in: self.sceneView) {
//SceneView에서 터치한 위치를 가져온다.
if let hit = self.sceneView.hitTest(touchLocation, options: nil).first {
//hitTest는 렌더링된 Scene에서 렌더링된 이미지의 한 지점에 해당하는 객체를 검색한다.
//터치한 위치를 hitTest의 시작점으로 사용한다.
if hit.node.name == "dice" { //해당 노드가 "dice"이면
hit.node.removeFromParentNode() //scene에서 해당 dice를 제거한다.
self.diceCount += 1 //카운터를 증가 시켜 던질 수 있는 주사위 수를 늘려준다.
}
}
}
}
//터치한 주사위를 삭제한다.
//Hit testing
//SceneView에는 히트 테스트를 수행할 수 있는 기능이 있다. 플레이어가 화면을 터치하는 화면 위치를 제공하면 된다.
//SceneKit은 광선을 Scene로 쏘고, 그 경로의 모든 물체를 "히트"로 간주한다.
}
// MARK: - View Management
override func viewDidLoad() {
super.viewDidLoad()
self.initSceneView()
self.initScene()
self.initARSession()
self.loadModels()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("*** ViewWillAppear()")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("*** ViewWillDisappear()")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
print("*** DidReceiveMemoryWarning()")
}
override var prefersStatusBarHidden: Bool {
return true
}
@objc
func orientationChanged() { //화면이 회전하면 focusPoint를 업데이트 해 줘야 한다.
//notification을 받아서 업데이트
focusPoint = CGPoint(x: view.center.x, y: view.center.y + view.center.y * 0.25)
//뷰의 y중심보다 25% 낮은 위치
//Ray casting
//레이 캐스팅은 3D 물체와의 교차점을 찾고 있는 동안, 화면 중심(초점)에서 가상 Scene로 광선을 만들어 낸다. p.107
//광성이 평면과 교차하면 해당 교차 위치에 포커스 노드를 배치하면 된다.
}
// MARK: - Initialization
func initSceneView() {
sceneView.delegate = self
sceneView.showsStatistics = true
sceneView.debugOptions = [
//ARSCNDebugOptions.showFeaturePoints,
//ARSCNDebugOptions.showWorldOrigin,
//SCNDebugOptions.showBoundingBoxes,
//SCNDebugOptions.showWireframe
]
//• Feature points : Scene 전체에 보이는 작은 점들을 추가한다.
// 디바이스의 위치와 방향을 정확하게 추적하는 데 사용된다.
//• World origin : 세션을 시작한 곳의 R(X)G(Y)B(Z) 교차선을 나타낸다.
//• Bounding boxes : 모든 3D 객체 주위에 상자 모양의 윤곽선을 보여 준다.
// SceneKit 객체 도형의 범위를 보여준다.
//• Wireframe : Scene의 geometry를 표시한다. AR Scene에서 각 3D 객체의 표면에 있는 폴리곤 윤곽을 볼 수 있다.
// 기하학적 모양이 얼마나 자세히 표시되는 지 확인할 수 있다.
focusPoint = CGPoint(x: view.center.x, y: view.center.y + view.center.y * 0.25)
//뷰의 y중심보다 25% 낮은 위치
//레이 캐스팅에 사용할 화면 상의 위치를 정의한다. 일반적으로 화면의 중심이다.
//하지만 여기에서 포커스 노드는 애니메이션이 추가되므로 중심보다 약간 아래의 위치에 추가해 준다.
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
//화면 회전 시 알림을 트리거
}
func initScene() {
let scene = SCNScene() //빈 Scene 생성
scene.isPaused = false
sceneView.scene = scene
scene.lightingEnvironment.contents = "PokerDice.scnassets/Textures/Environment_CUBE.jpg"
//전체적인 Scene의 조명을 Environment_CUBE.jpg로 설정
scene.lightingEnvironment.intensity = 2 //조명 강도 2
scene.physicsWorld.speed = 1.0 //물리엔진 설정. 기본값은 1.0이다(2.0은 2배 빠름, 0은 멈춘다).
scene.physicsWorld.timeStep = 1.0 / 60.0 //물리엔진 업데이트 간격
//기본적으로 SceneKit의 물리 엔진은 초당 60회 업데이트 된다. 간격을 늘리면 더 정확해지지만 CPU 소모가 커진다.
//빠르게 이동하는 객체 간 충돌 등을 사용할 때는 값을 올려야 한다.
}
func initARSession() {
guard ARWorldTrackingConfiguration.isSupported else {
//디바이스가 ARWorldTrackingConfiguration(6DOF)를 지원하는 지 여부
print("*** ARConfig: AR World Tracking Not Supported")
return
}
let config = ARWorldTrackingConfiguration() //ARWorldTrackingConfiguration 인스턴스 생성
//AR session을 시작하기 전에 AR session configuration을 먼저 만들어야 한다.
//AR session configuration은 장치가 있는 실제 세계와 가상 콘텐츠가 있는 3D 세계 사이의 연결을 설정한다.
config.worldAlignment = .gravity //worldAlignment 속성은 가상 콘텐츠를 매핑하는 방법을 결정한다.
//1. gravity : 콘텐츠를 중력에 평행한 y좌표 축에 설정한다. y축은 항상 실제 공간에서 위쪽을 향하게 된다.
// 또한 장치의 초기 위치를 좌표의 원점으로 사용한다. AR Sessio이 시작되는 순간 실제 공간에서의 장치 위치이다.
//2. gravityAndHeading : gravity와 같이 콘텐츠를 중력에 평행한 y좌표 축에 설정한다. 또한,
// x축이 서쪽에서 동쪽으로, z축이 북쪽에서 남쪽으로 지정된다. p.62
// 장치의 초기 위치를 원점으로 사용한다. ex. 나침반
//3. camera : 디바이스의 방향과 위치를 원점으로 사용한다.
config.providesAudioData = false
//AR Session이 오디오를 캡쳐할지 여부.
//다른 속성인 isLightEstimationEnabled(조명)도 있다.
config.planeDetection = .horizontal //표면을 탐지하기 위해 ARConfiguration에서 활성화해야 한다. 수평
//감지된 모든 표면(여기서는 수평)에 대해 ARPlaneAnchor 인스턴스를 자동으로 생성한다.
//renderer(_:didAdd:for) delegate가 호출되어 새로 추가된 앵커에 대해 알려준다.
//Anchors
//앵커는 움직이는 물위에서 선박의 위치를 유지한다. 마찬가지로 ARKit은 3D 콘텐츠에 첨부된 가상 앵커를 사용한다.
//주요 목적은 플레이어가 주변을 움직일 때 관련된 실제 세계에 3D 콘텐츠의 위치를 유지하는 것이다.
//ARAnchor 객체는 위치와 방향을 유지하는 변환을 포함하고 있다. 앵커는 보이는 요소가 아닌 ARKit에서 유지되는 객체이다.
//기본적으로 ARKit은 ARAnchor와 SCNNode를 연결한다. 3D 콘텐츠를 해당 노드의 하위 노드로 추가하면 작업이 완료된다.
//ARPlaneAnchor는 중심점, 방향, 표면 범위를 포함하는 추가 평면 정보와 함께 실제 변환(위치, 방향)을 포함한다.
//이 정보를 사용하여 SCeneKit Plane 노드를 생성할 수 있다. p.101
//cf. ARFaceAnchor도 있다.
config.isLightEstimationEnabled = true //광원 분석 여부
//밝은 환경에 있으면 빛의 강도가 높아지고, 어두운 환경이면 빛의 강도가 낮아진다.
sceneView.session.run(config) //AR Session 시작
//6DOF로 트래킹 데이터를 수집을 시작한다.
//Controlling an AR session
//AR Session을 제어하는 방법
//• Pausing : ARSession.pause()으로 AR Session 트래킹을 일시 중지한다. ex. 다른 앱으로 전환 시
//• Resuming : ARSession.run()으로 일시 중지된 세션을 다시 시작한다. 이전의 Config를 그대로 사용한다.
//• Updating : ARSession.run(ARSessionConfig)으로 Config를 업데이트한다.
// ex. 버튼을 누를 때에만 오디오 샘플링 활성화
//• Resetting : ARSession.run(_ : options :)으로 세션을 재시작한다. 이전 세션의 정보가 삭제된다.
}
// MARK: - Load Models
func loadModels() {
let diceScene = SCNScene(
named: "PokerDice.scnassets/Models/DiceScene.scn")! //Scene 로드하여 저장
for count in 0..<5 { //주사위 수가 총 5개
diceNodes.append(diceScene.rootNode.childNode(
withName: "dice\(count)",
recursively: false)!) //배열에 저장
//Scene의 rootNode scene를 검색하여, dice0 부터 dice4까지 모든 노드를 찾는다.
//해당 노드를 발견하면 diceNodes 배열에 추가한다.
//recursively 매개변수를 true로 하면, 자식 노드의 하위 트리까지 검색한다.
//false로 하면 해당 노드의 직접적인 자식만 검색
}
let focusScene = SCNScene(
named: "PokerDice.scnassets/Models/FocusScene.scn")! //Scene 로드하여 저장
focusNode = focusScene.rootNode.childNode(
withName: "focus", recursively: false)! //포커스 노드 발견해서
sceneView.scene.rootNode.addChildNode(focusNode) //SceneView에 자식노드로 추가한다.
lightNode = diceScene.rootNode.childNode(withName: "directional", recursively: false)!
//diceScene에서 광원 노드를 가져온다.
sceneView.scene.rootNode.addChildNode(lightNode) //SceneView에 자식노드로 추가한다.
}
// MARK: - Helper Functions
func throwDiceNode(transform: SCNMatrix4, offset: SCNVector3) {
//선택된 주사위 노드를 AR Scene로 복제하는 메서드
let distance = simd_distance(focusNode.simdPosition,
simd_make_float3(transform.m41,
transform.m42,
transform.m43))
//주사위에 다양한 힘을 가한다. 이를 위해 주사위와 초점 노드 사이의 거리를 계산한다.
let direction = SCNVector3(-(distance * 2.5) * transform.m31,
-(distance * 2.5) * (transform.m32 - Float.pi / 4),
-(distance * 2.5) * transform.m33)
//주사위를 던진다. 이를 위해 순방향 벡터를 생성하고, 주사위 회전을 포함하여 계산한 거리를 통합한다.
let rotation = SCNVector3(Double.random(min: 0, max: Double.pi),
Double.random(min: 0, max: Double.pi),
Double.random(min: 0, max: Double.pi))
//임의의 회전할 벡터를 정의한다. 주사위가 plane위에 떨어진 후
let position = SCNVector3(transform.m41 + offset.x,
transform.m42 + offset.y,
transform.m43 + offset.z)
//transform의 위치데이터를 벡터와 결합해 offset 위치를 만든다.
//Transform은 SCNMatrix4fh 4x4의 행렬이다. m41의 경우 4행 1열을 나타낸다.
//각 행은 변환, 회전, 크기 등의 특정 값과 연관되어 있다.
let diceNode = diceNodes[diceStyle].clone() //선택된 주사위 노드의 복제 생성
diceNode.name = "dice" //이름
diceNode.position = position //위치 설정
diceNode.eulerAngles = rotation //회전 각도 설정
diceNode.physicsBody?.resetTransform() //트랜스폼 리셋. 주사위의 위치를 업데이트 한다.
diceNode.physicsBody?.applyForce(direction, asImpulse: true)
//주사위에 힘을 가해 특정 방향으로 던진다.
sceneView.scene.rootNode.addChildNode(diceNode)
//복제된 주사위 노드가 AR Scene에 배치된다.
diceCount -= 1 //diceCount 감소 시켜 주사위가 굴려졌을음 나타낸다.
}
func updateStatus() { //현재 게임 상태
switch gameState {
case .detectSurface:
statusMessage = "Scan entire table surface...\nHit START when ready!"
case .pointToSurface:
statusMessage = "Point at designated surface first!"
case .swipeToPlay:
statusMessage = "Swipe UP to throw!\nTap on dice to collect it again."
}
self.statusLabel.text = trackingStatus != "" ?
"\(trackingStatus)" : "\(statusMessage)"
//statusLabel에 상태를 표기한다. 필요한 경우 기존 메시지에 추가
}
func updateFocusNode() {
let results = self.sceneView.hitTest(self.focusPoint, types: [.existingPlaneUsingExtent])
//해당 지점의 해당 타입의 실제 객체 또는 AR 앵커를 검색한다.
//hitTest는 레이 캐스트를 수행한다. 매개변수로 광선을 발사할 곳의 스크린 위치와 찾고자하는 대상 유형을 입력한다.
//.existingPlaneUsingExtent으로 plane 기반의 객체만 가져온다.
//.featurePoints, .estimatedHorizontalPlane, .existingPlane 등을 사용할 수 있다.
if results.count == 1 { //검색된 결과가 하나라면
if let match = results.first { //해당 결과를 가져온다.
let t = match.worldTransform //위치, 방향, 크기 정보가 포함된 worldTransform를 사용한다.
self.focusNode.position = SCNVector3(x: t.columns.3.x, y: t.columns.3.y, z: t.columns.3.z)
//변환 행렬을 기반으로 포커스 노드의 위치를 업데이트한다.
//위치정보는 변환 행렬의 세 번째 열에서 찾을 수 있다.
self.gameState = .swipeToPlay
}
} else { //검색 결과가 없다면
self.gameState = .pointToSurface
//표면을 감지하도록 gameState를 설정해 준다.
}
}
func createARPlaneNode(planeAnchor: ARPlaneAnchor, color: UIColor) -> SCNNode {
//앵커를 받아 Plane 요소를 추가한다.
// 1 - Create plane geometry using anchor extents
let planeGeometry = SCNPlane(width: CGFloat(planeAnchor.extent.x),
height: CGFloat(planeAnchor.extent.z))
//extent로 검출된 평면의 너비와 길이를 가져올 수 있다.
//앵커의 범위에 대한 지오메트리 평면(Editor에서 초록색으로 추가하던 객체)이 생성된다.
// 2 - Create meterial with just a diffuse color
let planeMaterial = SCNMaterial() //Material 생성
planeMaterial.diffuse.contents = "PokerDice.scnassets/Textures/Surface_DIFFUSE.png" //color
//Scene Editor로 설정하던 것을 코드로. 텍스처를 가져온다.
planeGeometry.materials = [planeMaterial] //지오메트리에 텍스처를 입힌다.
// 3 - Create plane node
let planeNode = SCNNode(geometry: planeGeometry) //지오메트리로 plane 노드 생성
planeNode.position = SCNVector3Make(planeAnchor.center.x, 0, planeAnchor.center.z)
//앵커의 중심점을 기준으로 평면 노드의 위치 설정
planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0)
//SCNPlane으로 생성된 지오메트리(Editor의 초록색 Plane)는 기본적으로 수직이다.
//따라서 평면으로 배치하려면 x축을 기준으로 시계 방향으로 90도 회전해야 한다.
//수직 앵커를 사용할 때는 이 줄을 생략할 수 있다.
planeNode.physicsBody = createARPlanePhysics(geometry: planeGeometry) //물리 엔진 추가
return planeNode
}
func updateARPlaneNode(planeNode: SCNNode, planeAchor: ARPlaneAnchor) {
//기존의 plane 노드를 새로운 위치, 방향, 크기로 업데이트 하는 메서드
// 1 - Update plane geometry with planeAnchor details
let planeGeometry = planeNode.geometry as! SCNPlane //여기서는 수평 plane만 사용하므로
planeGeometry.width = CGFloat(planeAchor.extent.x) //앵커 너비로 가로 업데이트
planeGeometry.height = CGFloat(planeAchor.extent.z) //앵커 길이로 세로 업데이트
// 2 - Update plane position
planeNode.position = SCNVector3Make(planeAchor.center.x, 0, planeAchor.center.z)
//앵커 중앙의 위치로 plane 노드의 위치를 업데이트한다.
planeNode.physicsBody = nil //plane이 업데이트 되면 해당 물리 엔진을 해제한 후
planeNode.physicsBody = createARPlanePhysics(geometry: planeGeometry) //새로 추가해 줘야 한다.
}
func removeARPlaneNode(node: SCNNode) {
//여러 Plane이 겹치는 경우가 있다.
//이런 경우, ARKit은 감지된 여러 Plane을 여러 평면으로 병합할 수 있다.
//이를 위해 하나의 평면을 남겨두고 나머지는 삭제한다.
for childNode in node.childNodes { //해당 노드의 자식 노드들을 loop로 돌아서
childNode.removeFromParentNode() //자식 노드들을 삭제한다.
}
}
func updateDiceNodes() {
for node in sceneView.scene.rootNode.childNodes { //사용 가능한 모든 노드 loop
if node.name == "dice" { //노드의 이름이 "dice"인 경우
if node.presentation.position.y < -2 {
//노드(dice)의 현재 y 위치가 지상보다 2미터 아래있다면
node.removeFromParentNode() //주사위 제거
diceCount += 1 //주사위 카운트를 증가 시켜 다시 굴릴 수 있도록 한다.
}
}
}
}
func createARPlanePhysics(geometry: SCNGeometry) -> SCNPhysicsBody {
//주사위가 표면을 감지할 수 있도록 하는 helper
let physicsBody = SCNPhysicsBody(
type: .kinematic,
shape: SCNPhysicsShape(geometry: geometry, options: nil))
//type과 shpae를 매개변수로 물리 엔진을 코드로 생성한다.
//여기서는 표면을 감지해야 하므로, plane 형태의 geometry가 와야 한다.
physicsBody.restitution = 0.5 //탄성
physicsBody.friction = 0.5 //저항
//속성을 설정해 준다.
return physicsBody
}
func suspendARPlaneDetection() {
//Plane 감지를 일시 중단한다.
//플레이어가 게임을 시작한 후에는 다른 Plane을 계속해서 찾을 필요가 없다.
let config = sceneView.session.configuration as! ARWorldTrackingConfiguration
//현재 AR tracking configuration을 가져온다.
config.planeDetection = [] //빈 배열로 설정해서, 탐지할 표면을 지운다.
sceneView.session.run(config) //변경한 설정으로 세션을 다시 시작한다.
//이후 plane 탐지를 위해 리소스를 소모하지 않을 것이다.
}
func hideARPlaneNodes() {
//감지된 Plane을 보여 주는 것도 무의미하다.
for anchor in (self.sceneView.session.currentFrame?.anchors)! {
//현재 Scene에서 사용 가능한 모든 앵커를 가져온다.
if let node = self.sceneView.node(for: anchor) { //해당 앵커에 관련된 노드를 가져온다.
for child in node.childNodes { //노드의 자식 모드를 loop
let material = child.geometry?.materials.first!
//지금은 material을 하나만 사용하고 있으므로.
material?.colorBufferWriteMask = [] //모든 색상 정보를 비활성화 해서 노드를 숨긴다.
}
}
}
}
func startGame() {
DispatchQueue.main.async {
self.startButton.isHidden = true //시작 버튼 숨김
self.suspendARPlaneDetection() //AR Plane 탐지 중지
self.hideARPlaneNodes() //감지된 Plane 숨김
self.gameState = .pointToSurface //게임 상태 변환
}
}
func resetARSession() {
//ARSession을 다시 시작한다. 게임을 리셋한 경우 주로 사용
let config = sceneView.session.configuration as! ARWorldTrackingConfiguration
//AR configuration을 가져온다.
config.planeDetection = .horizontal //plane 탐지를 다시 활성화 한다.
sceneView.session.run(config,
options: [.resetTracking, .removeExistingAnchors])
//세션을 다시 시작.
//.resetTracking : ARKit을 다시 시작한다.
//.removeExistingAnchors : 이전에 감지된 모든 앵커를 지운다.
}
func resetGame() {
DispatchQueue.main.async {
self.startButton.isHidden = false //시작 버튼 다시 보이게
self.resetARSession() //세션 다시 시작
self.gameState = .detectSurface //게임 상태 변환
}
}
}
extension ViewController : ARSCNViewDelegate {
// MARK: - SceneKit Management
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
DispatchQueue.main.async {
//self.statusLabel.text = self.trackingStatus
self.updateStatus() //상태 업데이트
self.updateFocusNode() //포커스 노드 업데이트
self.updateDiceNodes() //주사위 업데이트
}
}
// MARK: - Session State Management
func session(_ session: ARSession,
cameraDidChangeTrackingState camera: ARCamera) {
//세션이 실행되는 동안 외부 상태 및 이벤트에 따라 트래킹 상태를 변경될 수 있다.
//세션 상태가 변경될 때 마다 해당 메서드가 트리거 된다. 따라서 상태를 모니터링하기 좋은 장소이다.
switch camera.trackingState { //ARCamera의 상태로 Switch
case .notAvailable: //ARSession을 추적할 수 없는 경우
trackingStatus = "Tacking: Not available!"
case .normal: //정상적인 상태
trackingStatus = "Tracking: All Good!"
case .limited(let reason): //ARSession을 추적할 수는 있지만, 제한적인 경우
switch reason {
case .excessiveMotion: //디바이스가 너무 빨리 움직여 정확한 정확한 이미지 위치를 트래킹 할 수 없는 경우
trackingStatus = "Tracking: Limited due to excessive motion!"
case .insufficientFeatures: //이미지 위치를 트래킹할 feature들이 충분하지 않은 경우
trackingStatus = "Tracking: Limited due to insufficient features!"
case .initializing: //세션이 트래킹 정보를 제공할 충분한 데이터를 아직 수집하지 못한 경우
//새로 세션 시작하거나 구성 변경 시 일시적으로 발생한다.
trackingStatus = "Tracking: Initializing..."
case .relocalizing: //세션이 중단된 이후 재개하려고 시도 중인 경우
trackingStatus = "Tracking: Relocalizing..."
}
}
}
// MARK: - Session Error Managent
func session(_ session: ARSession,
didFailWithError error: Error) {
//delegate에게 오류로 세션이 중지될 때 알려 준다.
self.trackingStatus = "AR Session Failure: \(error)"
}
func sessionWasInterrupted(_ session: ARSession) {
//세션이 중단 되기 전에 이 메서드가 먼저 트리거 된다. 여기서 필요한 일부 설정을 저장하고 오류 처리할 수 있다.
//주로 앱이 백그라운드로 가거나, 많은 앱들이 실행 중인 경우 세션이 중단되는 경우가 발생한다.
self.trackingStatus = "AR Session Was Interrupted!"
}
func sessionInterruptionEnded(_ session: ARSession) {
//세션 재시작. 이전 interruption이 종료될 때 트리거 된다.
//세션 트래킹을 재설정하여 모든 것이 정상적으로 다시 작동하는 지 확인하는 것이 좋다.
self.trackingStatus = "AR Session Interruption Ended"
self.resetGame() //게임 재시작
}
// MARK: - Plane Management
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
//감지된 모든 표면(여기서는 수평)에 대한 AR anchor가 자동으로 추가될 때 호출된다.
//파라미터의 node는 세로운 SceneKit 노드로, ARAnchor 노드와 쌍을 이룬다.
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
//여기서는 ARPlaneAnchor 노드만 사용하므로 이외의 타입에 대해서는 그대로 반환한다.
DispatchQueue.main.async { //메인 스레드에서만 UI 업데이트 등의 시각적 요소를 만들 수 있다.
let planeNode = self.createARPlaneNode(planeAnchor: planeAnchor,
color: UIColor.yellow.withAlphaComponent(0.5))
//앵커의 정보를 색상과 함께 전달해 plane 노드를 생성한다.
node.addChildNode(planeNode) //해당 노드를 ARKit 노드의 하위 노드로 추가된다.
}
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
//SceneKit 노드의 속성이 해당 앵커의 현제 상태와 일치하도록 업데이트해야 하는 경우 호출된다.
//이전에 감지된 표면을 새 정보로 업데이트해야 할 경우 트리거 된다.
//여기서 node는 이전에 추가한 기존 plane 노드이다.
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
//여기서는 ARPlaneAnchor 노드만 사용하므로 이외의 타입에 대해서는 그대로 반환한다.
DispatchQueue.main.async { //메인 스레드에서만 UI 업데이트 등의 시각적 요소를 만들 수 있다.
self.updateARPlaneNode(
planeNode: node.childNodes[0],
planeAchor: planeAnchor)
//앵커 정보를 첫 번째 자식 노드와 함께 전달한다.
}
}
func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
//노드가 제거되었을 때 트리거 된다.
guard anchor is ARPlaneAnchor else { return }
DispatchQueue.main.async {
self.removeARPlaneNode(node: node) //노드를 삭제한다.
}
}
}
//A9 이상의 프로세서가 있는 실제 장치를 사용해야 한다.
//• iPhone SE
//• iPhone 6s 및 6s Plus
//• iPhone 7 및 7 Plus
//• iPad Pro (모든 크기의 1 세대 및 2 세대 : 9.7", 10.5" 및 12.9")
//• iPad (2017+ 모델)
//• iPhone 8 및 8 Plus
//• iPhone X
//ARKit을 사용하는 앱은 카메라에 대한 액세스가 반드시 있어야 한다.
//Info.plist의 Find Privacy - Camera Usage Description에서 설정할 수 있다.
//ARKit 템플릿으로 프로젝트를 생성하면, 자동으로 설정되어 있다.
//이 메시지는 카메라에 액세스 요청할 때 사용자에게 표시되는 문자열이다.
//SceneKit Asset Catalog는 .scnassets 확장자로 생성해 주면 된다.
//ARPokerDice group에서 right-click, Add Files to "ARPokerDice"... 선택
//SceneKit Scene File을 생성할 때, Group을 제대로 지정해 줘야 한다. .scnassets 확장자 내의 그룹인지 확인
//앱이 시작되면 ARKit은 공간에서의 디바이스의 현재 위치를 앵커로 사용한다.
//그 후, SceneKit을 로드하고 해당 scene 을 증강현실 공간에 배치한다.
//SceneKit은 앱의 모든 그래픽 및 오디오 콘텐츠를 만들고 관리할 수 있는 그래픽 프레임워크이다.
//art.scnassets에는 Scene, Texture, 3D Model, Animation, Sound effect 같은 다양한 Asset을 저장할 수 있다.
//Xcode의 AR 템플릿은 UI요소를 지원하지 않기 때문에 스토리보드에서 추가해 줘야 한다.
//스토리보드에서 ARSCNView 위에 UI객체를 삽입하면, 해당 UI로 대체되어 버린다.
//따라서 UIView가 자식으로 ARSCNView를 가지도록 계층 구조를 정리해 주는 것이 좋다.
//Auto Layout를 설정할 때 아이폰 X의 notch를 고려해야 한다. Safe Area로 맞춰주는 것이 좋다.
//Creating the configuration
//AR session을 시작하기 전에 AR session configuration을 먼저 만들어야 한다.
//AR session configuration은 장치가 있는 실제 세계와 가상 콘텐츠가 있는 3D 세계 사이의 연결을 설정한다.
//두 가지 유형의 configuration이 있다.
//• AROrientationTrackingConfiguration : for three degrees. 3DOF라 한다.
//• ARWorldTrackingConfiguration : for six degrees. 6DOF라 한다.
//3DOF
//3DOF는 각각 X, Y, Z 축으로 회전하는 Pitch, Roll, Yaw를 트래킹한다. p.60
//AROrientationTrackingConfiguration에서 사용한다.
//6DOF
//6DOF는 3DOF와 같이 Pitch, Roll, Yaw를 트래킹한다.
//또한, 각각 X, Y, Z 축에 평행하게 이동하는 Sway, Heave, Surge를 사용해 3D 공간의 장치 이동을 추적한다.
//Adding 3D objects
//COLLADA등의 다른 3D 파일도 SceneKit으로 변환해서 사용할 수 있다.
//Editor ▸ Enable default lighting 으로 기본 조명을 활성화 한다.
//Editor ▸ Convert to SceneKit scene file format(.scn) 으로 변환한다.
//Shaders, materials and textures
//Lighting models (shaders)
//조명 모델에 따라 다양한 질감및 재료 효과를 생성한다. p.76
//• Constant : 주변 조명만 통합하는 평면 조명 모델
//• Lambert : 주변 및 확산 조명 통합
//• Blinn : 주변, 확산, 반사 조명 정보를 통합. Jim Blinn 공식 사용. 더 크고 부드러면 반사를 만든다.
//• Phong : 주변, 확산, 반사 조명 정보를 통합. Bui Tuong Phong 공식으로 반사 하이라이트 개선
//• Physical Based : 실제 조명 및 재료의 현실적인 추상화와 확산을 통합한다. 가장 최근에 추가된 모델이며 사실적이다.
//Materials
//물, 가죽, 나무, 암석 등의 물질을 구성한다.
//각 Material은 서로 다른 질감 레이어로 구성되며 각 레이어는 특정 색상, 질감, 효과를 생성하는 데 사용된다.
//Textures
//3D 객체에 저장된 좌표 정보를 사용하여 해당 객체를 감싸는 2D 이미지.
//텍스처는 서로 다른 레이어에 적용되며 각 레이어는 색상, 반사, 광택, 거칠기, 투명도 등 특정 속성을 정의하는 데에도 사용한다.
//결합시 다양한 속성이 실제와 같은 재질과 질감을 정의하는 데 사용된다.
//Physically based rendering (PBR)
//PBR은 가장 사실적인 3D 객체를 구현한다.
//Environment map
//Environment map 전에 Cube map을 이해하는 것이 좋다. 큐브 맵은 큐브와 마찬가지로 여섯 면으로 구성된다.
//일반적으로 큐브 맵은 반사 표면과 "스카이 박스"를 만드는데 사용한다. 스카이 박스는 3D 가상 환경에서 하늘과 다른 먼 배경을
//만드는 데 사용한다. p.78. SceneKit는 큐브 맵에 대한 다양한 패턴을 지원한다. 가장 일반적인 horizontal strip 패턴은
//6개의 동일한 크기의 텍스처 집합을 1:6 비율 이미지로 구성한다. p.79. 환경 맵은 반사도가 높은 곳에서는 reflection map과
//비슷하게 구현된다. 또한 PBR 객체에 조명 정보를 제공하여 사실적인 조명 환경을 제공한다.
//Diffuse map
//확산 맵은 3D 객체에 기본 색상을 제공한다. 조명과 기타 특수 효과에 관계없이 일반적으로 객체가 무엇인지를 정의한다.
//ex. 구를 지구로 정의. 알파 채널로 투명도를 지정할 수 있다. p.79
//Normal map
//조명 계산 중 물체 표면에 각 픽셀이 빛을 어떻게 휘게 하여 모양을 시뮬레이션 하는지 설명한다.
//간단히 말해 노멀 맵은 표면에 더 많은 폴리곤을 추가하지 않고도 표면을 더 울퉁불퉁하게 만들어 사실적인 구현을 한다.
//ex. 지구의 산맥, 해구, 평야등을 표현. p.80
//Height map
//높이 지도는 PBR 조명 모델의 일부는 아니다. 높이 정보를 정의하는 흑백 이미지로, 흰 색상은 객체에서 가장 높은 점으로
//렌더링 되고, 검정색은 가장 낮은 점으로 렌더링 된다. 높이 맵을 정의한 후, 노멀 맵으로 변환할 수 있다.
//http://bit.ly/1ELCePX 에서 높이 맵을 노멀 맵으로 변환할 수 있다.
//Occlusion map
//빛이 객체의 갈라진 틈 사이와 같은 좁은 구석까지 도달하는 것을 방지한다. 자연광의 특성을 모방한다. p.82
//Emission map
//모든 조명 및 음영 정보를 무시하여 발광 효과를 만든다. p.82
//빛을 어둡게 해야 효과가 뚜렷해 진다.
//Self-illumina1on map
//다른 모든 효과 후에 적용된다. 최종 결과를 색칠하거나 밝게 또는 어둡게 한다. p.83
//Displacement map
//노멀 맵이 픽셀 강도를 사용하여 매끄러운 표면에서 다양한 높이를 생성하는 경우,
//Displacement map은 픽셀 강도를 사용하여 실제 표면을 변경한다. p.83
//Metalness and roughness maps
//PBR의 주요 특징은 Metalness와 Roughness이다. p.84
//• Metalness : 금속적인 느낌. 반사도
//• Roughness : 거칠기. 무광. 광택
//Metalness map
//금속성을 나타낸다. 검은 색은 완전한 비금속 특성이고, 흰색은 완전한 금속 특성을 나타낸다. p.84
//Roughness map
//거칠기는 실제 표면의 미세한 디테일을 대략적으로 나타낸다. 검색은은 매우 거친 표면, 흰색은 매우 매끄러운 표면이다. p.85
//Applying environment textures
//Scene Graph에서 노드들의 계층정보를 볼 수 있고, Scene inspector에서 배경과 조명 설정을 해 준다.
//Applying 3D model textures
//Material inspector에서 여러 맵들과 재질 등을 설정해 줄 수 있다.
//노드를 복사 붙여 넣기한 경우, Unshare를 해줘야 설정이 공유 되지 않는다.
//SceneKit의 물리엔진을 이용하여 더욱 사실감 있는 AR을 만들 수 있다.
//The physics body
//SceneKit에 내장된 물리 엔진을 사용하려면 SCNode에 SCNPhysicsBody를 연결해야 한다.
//SCNPhysicsBody에는 세 가지 유형이 있다.
//• A static body : 벽과 같은 정적. 다른 물리 구조체는 static body 구조체와 상호작용하고 영향을 받지만,
// static body는 영향을 받지 않고 항상 정적인 위치에 있게 된다.
//• A dynamic body : 물리 엔진에 의해 제어된다. 다른 구조체와 상호 작용한다. ex. 공, 주사위
//• A kinematic body : 물리 엔진에 의해 제어되지 않고, 프로그래밍 방식으로 제어한다.
//The physics shape
//피라미드, 상자, 구, 원통, 원뿔, 도넛, 캡슐, 튜브와 같은 기하학적 모양을 정의한다. p.113
//Other physical proper1es
//질량, 마찰, 탄성 등의 속성을 정의할 수 있다. p.114
//Adding physics
//Scenen Editor의 Physics Inspector 탭에서 물리 엔진을 적용할 수 있다.
//완벽한 물리적 특성을 구현할 필요 없다(복잡해 지며 오히려 너무 현실적이라 사용하기 불편해 진다). 적당히!
//각 속성에 대한 정의는 p.116
//Lights and shadows
//Scene Editor에서 광원을 추가하고 그림자를 설정할 수 있다. p.123
| 37.225352 | 173 | 0.654903 |
56bcf11ea47c214d1c4d927018da93f9c43648cf | 9,490 | import Foundation
open class FitpayEventsSubscriber {
public static var sharedInstance = FitpayEventsSubscriber()
private let eventsDispatcher = FitpayEventDispatcher()
private var subscribersWithBindings: [SubscriberWithBinding] = []
public typealias EventCallback = (FitpayEvent) -> Void
// MARK - Lifecycle
private init() {
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardAdded) { event in
self.executeCallbacksForEvent(event: .cardCreated)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardActivated) { event in
self.executeCallbacksForEvent(event: .cardActivated)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardDeactivated) { event in
self.executeCallbacksForEvent(event: .cardDeactivated)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardReactivated) { event in
self.executeCallbacksForEvent(event: .cardReactivated)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardDeleted) { event in
self.executeCallbacksForEvent(event: .cardDeleted)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .setDefaultCard) { event in
self.executeCallbacksForEvent(event: .setDefaultCard)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .resetDefaultCard) { event in
self.executeCallbacksForEvent(event: .resetDefaultCard)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardMetadataUpdated) { event in
self.executeCallbacksForEvent(event: .cardMetadataUpdated)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardProvisionFailed) { event in
self.executeCallbacksForEvent(event: .cardProvisionFailed)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .syncCompleted) { event in
self.executeCallbacksForEvent(event: .syncCompleted)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .syncFailed) { event in
var error: Error? = nil
if let nserror = (event.eventData as? [String: NSError])?["error"] {
error = SyncManager.ErrorCode(rawValue: nserror.code)
}
self.executeCallbacksForEvent(event: .syncCompleted, status: .failed, reason: error)
}
let _ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .apduPackageComplete) { event in
var status = EventStatus.success
var error: Error? = nil
if let nserror = (event.eventData as? [String: NSError])?["error"] {
error = SyncManager.ErrorCode(rawValue: nserror.code)
status = .failed
}
self.executeCallbacksForEvent(event: .apduPackageProcessed, status: status, reason: error, eventData: event.eventData)
}
}
// MARK: - Public Functions
open func subscribeTo(event: EventType, subscriber: AnyObject, callback: @escaping EventCallback) {
guard let binding = eventsDispatcher.addListenerToEvent(FitpayBlockEventListener(completion: callback), eventId: event) else {
log.error("FitpayEventsSusbcriber: can't create event binding for event: \(event.eventDescription())")
return
}
if var subscriberWithBindings = findSubscriberWithBindingsFor(subscriber: subscriber) {
subscriberWithBindings.bindings.append(binding)
} else {
subscribersWithBindings.append(SubscriberWithBinding(subscriber: subscriber, bindings: [binding]))
}
}
open func unsubscribe(subscriber: AnyObject) {
var subscriberWithBindings: SubscriberWithBinding? = nil
for (i, subscriberItr) in subscribersWithBindings.enumerated() {
if subscriberItr.subscriber === subscriber {
subscriberWithBindings = subscriberItr
subscribersWithBindings.remove(at: i)
break
}
}
if let subscriberWithBindings = subscriberWithBindings {
for binding in subscriberWithBindings.bindings {
self.unbind(binding)
}
}
}
open func unsubscribe(subscriber: AnyObject, event: EventType) {
guard var subscriberWithBindings = findSubscriberWithBindingsFor(subscriber: subscriber) else {
return
}
subscriberWithBindings.removeAllBindingsFor(event: event) {
(binding) in
self.unbind(binding)
}
removeSubscriberIfBindingsEmpty(subscriberWithBindings)
}
open func unsubscribe(subscriber: AnyObject, binding: FitpayEventBinding) {
guard var subscriberWithBindings = findSubscriberWithBindingsFor(subscriber: subscriber) else {
return
}
subscriberWithBindings.remove(binding: binding) {
(binding) in
self.unbind(binding)
}
removeSubscriberIfBindingsEmpty(subscriberWithBindings)
}
// MARK: - Internal Functions
func executeCallbacksForEvent(event: EventType, status: EventStatus = .success, reason: Error? = nil, eventData: Any = "") {
eventsDispatcher.dispatchEvent(FitpayEvent(eventId: event, eventData: eventData, status: status, reason: reason))
}
// MARK: - Private Functions
private func removeSubscriberIfBindingsEmpty(_ subscriberWithBinding: SubscriberWithBinding) {
if subscriberWithBinding.bindings.count == 0 {
for (i, subscriberItr) in subscribersWithBindings.enumerated() {
if subscriberItr.subscriber === subscriberWithBinding.subscriber {
subscribersWithBindings.remove(at: i)
break
}
}
}
}
private func unbind(_ binding: FitpayEventBinding) {
eventsDispatcher.removeBinding(binding)
}
private func findSubscriberWithBindingsFor(subscriber: AnyObject) -> SubscriberWithBinding? {
for subscriberItr in subscribersWithBindings {
if subscriberItr.subscriber === subscriber {
return subscriberItr
}
}
return nil
}
}
// MARK: - Nested Objects
extension FitpayEventsSubscriber{
public enum EventType: Int, FitpayEventTypeProtocol {
case cardCreated = 0
case cardActivated
case cardDeactivated
case cardReactivated
case cardDeleted
case setDefaultCard
case resetDefaultCard
case cardProvisionFailed
case cardMetadataUpdated
case userCreated
case getUserAndDevice
case apduPackageProcessed
case syncCompleted
public func eventId() -> Int {
return rawValue
}
public func eventDescription() -> String {
switch self {
case .cardCreated:
return "Card created event."
case .cardActivated:
return "Card activated event."
case .cardDeactivated:
return "Card deactivated event."
case .cardReactivated:
return "Card reactivated event."
case .cardDeleted:
return "Card deleted event."
case .setDefaultCard:
return "Set default card event."
case .resetDefaultCard:
return "Reset default card event."
case .cardProvisionFailed:
return "Card provision failed event."
case .cardMetadataUpdated:
return "Card metadata updated event."
case .userCreated:
return "User created event."
case .getUserAndDevice:
return "Get user and device event."
case .apduPackageProcessed:
return "Apdu package processed event."
case .syncCompleted:
return "Sync completed event."
}
}
}
struct SubscriberWithBinding {
weak var subscriber: AnyObject?
var bindings: [FitpayEventBinding] = []
mutating func removeAllBindingsFor(event: EventType, unBindBlock: (FitpayEventBinding) -> Void) {
var eventsIndexForDelete: [Int] = []
for (i, binding) in bindings.enumerated() {
if binding.eventId.eventId() == event.eventId() {
unBindBlock(binding)
eventsIndexForDelete.append(i)
}
}
for index in eventsIndexForDelete {
bindings.remove(at: index)
}
}
mutating func remove(binding: FitpayEventBinding, unBindBlock: (FitpayEventBinding) -> Void) {
for (i, bindingItr) in bindings.enumerated() {
if binding.eventId.eventId() == bindingItr.eventId.eventId() {
unBindBlock(binding)
bindings.remove(at: i)
}
}
}
}
}
| 36.640927 | 134 | 0.605796 |
4a239dcdacb181e18565a13f39a2c8232792d6e3 | 1,318 | //
// Test.swift
// Runner
//
// Created by gix on 2021/2/25.
//
import Foundation
import g_faraday
@objc class FaradayHelper: NSObject {
@objc static func enableAutomaticallyExtension() {
// 自动处理导航栏
UINavigationController.fa.automaticallyHandleNavigationBarHidden()
// 自动回调空值到flutter侧,避免flutter侧 await 一直不返回
UIViewController.fa.automaticallyCallbackNullToFlutter()
}
@objc static func startFlutterEngine(navigatorDelegate: FaradayNavigationDelegate,
httpProvider: FaradayHttpProvider? = nil,
commonHandler: FaradayHandler? = nil) {
Faraday.default.startFlutterEngine(navigatorDelegate: navigatorDelegate, httpProvider: httpProvider, commonHandler: commonHandler)
}
@objc static var currentFlutterViewController: FaradayFlutterViewController? {
return Faraday.default.currentFlutterViewController
}
@objc static func postNotification(_ name: String, arguments: Any? = nil) {
Faraday.default.postNotification(name, arguments: arguments)
}
@objc static func enableCallback(_ viewController: FaradayFlutterViewController, callback token: CallbackToken) {
viewController.fa.enableCallback(with: token)
}
}
| 34.684211 | 138 | 0.69044 |
911730fa2797fbbaf4b0bf0f3210ff01e5a2c14c | 256 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g {
let d {
if true {
{
enum S {
class
case ,
{
(
{
(
( {
{
{
{
{
{
( {
( {
{
{
{
| 9.481481 | 87 | 0.625 |
61fe19a8a627b1119de079ebc4ac6891f4d5fa1d | 1,621 | //
// Copyright (c) Vatsal Manot
//
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
import Swift
import SwiftUI
import UIKit
//swiftlint:disable all
public final class _UITextField: UITextField {
var kerning: CGFloat? {
didSet {
updateTextAttributes()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func editingChanged() {
updateTextAttributes()
}
func updateTextAttributes() {
let attributedText: NSMutableAttributedString
if let text = self.attributedText {
attributedText = .init(attributedString: text)
} else if let text = text {
attributedText = .init(string: text)
} else {
attributedText = .init(string: "")
}
let fullRange = NSRange(location: 0, length: attributedText.string.count)
if let kern = kerning ?? defaultTextAttributes[.kern] {
attributedText.addAttribute(.kern, value: kern, range: fullRange)
}
if let font = font {
attributedText.addAttribute(.font, value: font, range: fullRange)
}
if let textColor = textColor {
attributedText.addAttribute(.foregroundColor, value: textColor, range: fullRange)
}
self.attributedText = attributedText
}
}
#endif
| 26.145161 | 93 | 0.589759 |
9b949663c8983734e9bf0194e0cfbaa4e984c3af | 2,053 | /*
* Copyright (c) 2015 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class ImageTableViewCell: UITableViewCell {
var tiltShiftImage: TiltShiftImage? {
didSet {
if let tiltShiftImage = tiltShiftImage {
titleLabel.text = tiltShiftImage.title
updateImageViewWithImage(nil)
}
}
}
@IBOutlet weak var tsImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
func updateImageViewWithImage(image: UIImage?) {
if let image = image {
tsImageView.image = image
tsImageView.alpha = 0
UIView.animateWithDuration(0.3, animations: {
self.tsImageView.alpha = 1.0
self.activityIndicator.alpha = 0
}, completion: {
_ in
self.activityIndicator.stopAnimating()
})
} else {
tsImageView.image = nil
tsImageView.alpha = 0
activityIndicator.alpha = 1.0
activityIndicator.startAnimating()
}
}
}
| 32.078125 | 79 | 0.718461 |
ccd4fd92bd0a9291ae223f83d71fe59a2be44b66 | 472 | #if canImport(Foundation)
import Foundation
extension StringProtocol {
public func ranges<T: StringProtocol>(of aString: T, options mask: String.CompareOptions = [], locale: Locale? = nil) -> [Range<Index>] {
var result = [Range<Self.Index>]()
var start = startIndex
while let range = range(of: aString, options: mask, range: start..<endIndex, locale: locale) {
result.append(range)
start = range.upperBound
}
return result
}
}
#endif
| 29.5 | 139 | 0.677966 |
87e92af9168f62b738bb0044cdb13b5771af87cb | 17,569 | // MARK: - DatabaseValueConvertible
/// Types that adopt DatabaseValueConvertible can be initialized from
/// database values.
///
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible : SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from *dbValue*, if possible.
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
// SQLExpressible adoption
extension DatabaseValueConvertible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// See SQLExpression.sqlExpression
public var sqlExpression: SQLExpression {
return databaseValue
}
}
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
/// while let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.cursor(arguments: arguments, next: {
let dbValue: DatabaseValue = row.value(atIndex: 0)
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self
})
}
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from a prepared statement.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
let dbValue: DatabaseValue = row.value(atIndex: 0)
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self?
})
return try cursor.next() ?? nil
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From Request
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
/// for let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
/// while let name = try name.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?>
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?>
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?>
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.cursor(arguments: arguments, next: {
let dbValue: DatabaseValue = row.value(atIndex: 0)
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Wrapped?
})
}
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From Request
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?>
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Wrapped?> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?>
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
| 44.704835 | 168 | 0.633958 |
f85630f813b639ece19fae149986e2d78ef316b0 | 13,552 | //
// USBNavigator.swift
// OmniMobileApp
//
// Created by Ramirez Pastor, Jose Antonio on 7/17/19.
// Copyright © 2019 U.S. Bank. All rights reserved.
//
import Foundation
import UIKit
public enum TransitionDecision {
case push
case present
// TODO: - Do we need to handle the child VC as part of UIBroker?
case child
}
class USBNavigator {
static let shared = USBNavigator()
private let errorTopMost = "Failed to get the Top most navigation controller"
private init() {
// intensionally left blank..
}
/// Method to navigate from one screen to the next one.
///
/// - Parameters:
/// - screen:
/// - module:
/// - transition: (Optional) The transition style to use when navigating to the view controller. If not present, defaults to .push
/// * .push - will push the ViewController to current NavigationController
/// * .present - will present as a modal the ViewController already embedded in a new NavigationController.
/// - animated: (Optional) Pass true to animate the transition; otherwise, pass false. If not present, defaults to true.
/// - payload: (Optional) Dictionary of the type [String: Any] sent to the destination ViewController. Defaults to nil if not present.
/// - completion: (Optional) The block to execute after the presentation finishes. This block has no return value and takes UIViewController as a parameter. Defaults to nil
func navigate(screen: String, module: String, transition: TransitionDecision = .push, animated: Bool = true, payload: [String: Any]? = nil, completion: ((_ vc: UIViewController) -> Void)? = nil) {
// Get the destination VC and source VC
guard let destinationBroker = self.getViewController(screen: screen, module: module),
let destinationVC = destinationBroker as? UIViewController,
let sourceVC = UIViewController.top else {
LogUtil.logError("Failed to get the source (and/or) destination view controller instance.")
return
}
destinationBroker.payLoad = payload
destinationBroker.setCustomTransitions?()
switch transition {
case .present:
// TODO: Subclass UINavigationController to extend functionality
/*var nav = UINavigationController(rootViewController: vc)
setupNavigationController(&nav)
topNav.present(nav, animated: animated, completion: completion)*/
sourceVC.present(destinationVC, animated: animated, completion: nil)
case .push:
guard let topNav = getTopNavController() else { return }
topNav.pushViewController(destinationVC, animated: animated)
case .child:
addChildVC(sourceVC: sourceVC, destinationVC: destinationVC)
}
// TODO: - Discusson the completion params.
if let complitionhandle = completion {
complitionhandle(destinationVC)
}
}
/// Pops the top view controller from the navigation stack and updates the display.
///
/// - Parameters:
/// - animated: (Optional) Pass true to animate the transition; otherwise, pass false. If not present, defaults to true.
/// - payload: (Optional) Dictionary of the type [String: Any] sent to the destination ViewController.
func popViewController(animated: Bool = true, payload: [String: Any]? = nil) {
// Get the top navigation controller
guard let topNav = self.getTopNavController() else {
LogUtil.logError(errorTopMost)
return
}
// check if the pop is allowed
// if the count is 1 or less, you're in Root VC
// Hence, pop is not allowed
let count = topNav.children.count
guard count > 1, let currentVC = topNav.children.last else {
LogUtil.logError("Reached the root view controller. Pop not allowed.")
return
}
// Pop the view controller
topNav.popViewController(animated: animated)
// Perform all necessary navigation steps
let destinationVC = topNav.children[count - 2]
// Get the destination as UIBroker
guard let destBroker = destinationVC as? UIBroker else { return }
// Assign (or) Merge the payload to the destination VC
if let destPayload = destBroker.payLoad {
if let backPayload = payload {
var existingPayload = destPayload
existingPayload.merge(backPayload) { (_, new) in new }
destBroker.payLoad = existingPayload
}
} else {
destBroker.payLoad = payload
}
// Backward compatiblility to support existing method.
if let callBack = destBroker.backNavigationCallBack {
if let pl = payload, let oldBack = pl["backNavPayload"] {
callBack(oldBack)
} else {
callBack(nil)
}
}
}
/// Pops the top view controller to a specific view controller in stack
///
/// - Parameters:
/// - type: Type of the class to navigate to.
/// - animated: (Optional) Pass true to animate the transition; otherwise, pass false. If not present, defaults to true.
// TODO: - Check if the method needs a return value
@discardableResult
func popToViewController<T: UIViewController>(type: T.Type, animated: Bool = true) -> Bool {
// Get the top navigation controller
guard let topNav = self.getTopNavController(),
let currentVC = topNav.children.last else {
LogUtil.logError(errorTopMost)
return false
}
for viewController in topNav.children.reversed() where viewController is T {
topNav.popToViewController(viewController, animated: true)
return true
}
return false
}
/// Pops the top view controller to the root view controller of the navigation controller
///
/// - Parameters:
/// - animated: (Optional) Pass true to animate the transition; otherwise, pass false. If not present, defaults to true.
func popToRootViewController(animated: Bool = true) {
// Get the top navigation controller
guard let topNav = self.getTopNavController(),
let rootVC = topNav.children.first,
let currentVC = topNav.children.last else {
LogUtil.logError(errorTopMost)
return
}
topNav.popToRootViewController(animated: animated)
}
/// Pops the top view controller to the main landing view controller of the current flow
/// Landing view is identified using QuickAction Protocol or Command Center
///
/// - Parameters:
/// - animated: (Optional) Pass true to animate the transition; otherwise, pass false. If not present, defaults to true.
func popToMainLandingViewController(animated: Bool = true) {
// Get the top navigation controller
guard let topNav = self.getTopNavController(),
let currentVC = topNav.children.last else {
LogUtil.logError("Failed to get the Top most navigation controller")
return
}
popToRootViewController(animated: animated)
}
/// Dismisses the view controller that was presented modally by the view controller.
///
/// - Parameters:
/// - all: (Optional) Pass true to dismiss all presented ViewControllers
/// - animated: (Optional) Pass true to animate the transition; otherwise, pass false. If not present, defaults to true.
/// - payload: (Optional) Dictionary of the type [String: Any] sent to the presentingViewController.
/// - completion: (Optional) The block to execute after the presentation finishes. This block has no return value and takes no parameters. You may specify nil for this parameter.
func dismiss(_ vc: UIViewController? = nil, all: Bool = false, animated: Bool = true, trackDismiss: Bool = true, completion: (() -> Void)? = nil) {
guard let currentVC = (vc != nil ) ? vc : UIViewController.top else {
return
}
if all {
if let window = currentVC.view.window,
let rootView = window.rootViewController {
window.rootViewController?.dismiss(animated: animated, completion: completion)
}
} else {
currentVC.dismiss(animated: animated, completion: completion)
}
}
// Method to show to activity indicator with top reference
func showActivityIndicator() {
guard let vc = UIViewController.top as? BaseViewController else {
return
}
vc.showActivityIndicator()
}
// Method to hide to activity indicator with top reference
func hideActivityIndicator() {
guard let vc = UIViewController.top as? BaseViewController else {
return
}
vc.hideActivityIndicator()
}
// MARK: - Private methods.
// Add the destination VC as a child
private func addChildVC(sourceVC: UIViewController, destinationVC: UIViewController) {
sourceVC.addChild(destinationVC)
sourceVC.view.addSubview(destinationVC.view)
destinationVC.didMove(toParent: sourceVC)
}
// Get the destination screen as a UIBroker object
private func getViewController(screen: String, module: String) -> UIBroker? {
guard let screenPath = readFromPlist(screen: screen, module: module) else {
return nil
}
if checkStoryBoardOrNot(name: screenPath) {
let components = screenPath.components(separatedBy: ".")
guard let storyboardName = components.first,
let storyboardIdentifier = components.last else {
LogUtil.logError("Couldn't find Storyboard.")
return nil
}
let storyboard = UIStoryboard(name: String(storyboardName), bundle: nil)
guard let vc = storyboard.instantiateViewController(withIdentifier: String(storyboardIdentifier)) as? UIBroker else {
LogUtil.logError("VC does not conform to UIBroker.")
return nil
}
return vc
} else {
guard let genericClassType = getClassType(from: screenPath) else {
return nil
}
let viewController = genericClassType.init()
guard let uiBroker = viewController as? UIBroker else {
return nil
}
return uiBroker
}
}
// Get the UIViewController name from Navigation plist
private func readFromPlist(screen: String, module: String) -> String? {
LogUtil.logInfo("Looking for screen *\(screen)* in module *\(module)*")
var flowList: NSDictionary?
if let path = Bundle.main.path(forResource: GlobalConstants.navigationFileName, ofType: "plist") {
flowList = NSDictionary(contentsOfFile: path)
if let dict = flowList,
let screenPathDict = dict[module] as? [String: Any],
let screenPath = screenPathDict[screen] as? String {
LogUtil.logInfo("Found path *\(screenPath)*")
return screenPath
}
}
LogUtil.logError("Could not find path.")
return nil
}
/// takes the class name and gives class.Type
///
/// - Parameter name: class name
/// - Returns: NSObject.Type?
private func getClassType(from name: String) -> NSObject.Type? {
guard let topViewController = UIViewController.top,
let appModule = topViewController.className.components(separatedBy: ".").first else {
return nil
}
//getting class type from string "appModule+className" ex: "USBank.BusinessLendingCategoryViewController"
if let classType = NSClassFromString(appModule + "." + name) as? NSObject.Type {
return classType
}
return nil
}
//checking stroryboard existing or not
private func checkStoryBoardOrNot(name: String) -> Bool {
// In Navigation.plist, the format is as
// <storyboardName>.<storyboardIdentier>
let data = name.components(separatedBy: ".")
// if the count is 2, we have the value in
// standard format in plist.
if data.count == 2 {
return true
}
// there are some case, where above
// format is not followed
return false
}
// To get the navigation controller of the top most VC
// TODO: - Change this to use mainNavController after
// we implement the main navigation stack
private func getTopNavController() -> UINavigationController? {
guard let vc = UIViewController.top,
let navController = vc.navigationController else {
// TODO: - Change to proper dismiss method.
dismiss(all: true, animated: false, trackDismiss: false)
return UIViewController.navRoot ?? UINavigationController()
}
return navController
}
}
#if DEBUG
// MARK: - public methods to be accessed from XCTests
extension USBNavigator {
func testGetViewController(screen: String, module: String) -> UIBroker? {
return getViewController(screen: screen, module: module)
}
func storyboardCheck(name: String) -> Bool {
return checkStoryBoardOrNot(name: name)
}
}
#endif
| 39.976401 | 200 | 0.633117 |
8745fad6e055990bc676734a7ef3fe3592a46ee2 | 12,528 | // From: https://github.com/myfreeweb/SwiftCBOR
// License: Public Domain
import Foundation
let isBigEndian = Int(bigEndian: 42) == 42
/// Takes a value breaks it into bytes. assumes necessity to reverse for endianness if needed
/// This function has only been tested with UInt_s, Floats and Doubles
/// T must be a simple type. It cannot be a collection type.
func rawBytes<T>(of x: T) -> [UInt8] {
var mutable = x // create mutable copy for `withUnsafeBytes`
let bigEndianResult = withUnsafeBytes(of: &mutable) { Array($0) }
return isBigEndian ? bigEndianResult : bigEndianResult.reversed()
}
/// Defines basic CBOR.encode API.
/// Defines more fine-grained functions of form CBOR.encode*(_ x)
/// for all CBOR types except Float16
extension CBOR {
public static func encode<T: CBOREncodable>(_ value: T) -> Data {
return value.cborEncode
}
/// Encodes an array as either a CBOR array type or a CBOR bytestring type, depending on `asByteString`.
/// NOTE: when `asByteString` is true and T = UInt8, the array is interpreted in network byte order
/// Arrays with values of all other types will have their bytes reversed if the system is little endian.
public static func encode<T: CBOREncodable>(_ array: [T], asByteString: Bool = false) -> Data {
if asByteString {
let length = array.count
var res = length.cborEncode
res[0] = res[0] | 0b010_00000
let itemSize = MemoryLayout<T>.size
let bytelength = length * itemSize
res.reserveCapacity(res.count + bytelength)
let noReversalNeeded = isBigEndian || T.self == UInt8.self
array.withUnsafeBytes { bufferPtr in
guard let ptr = bufferPtr.baseAddress?.bindMemory(to: UInt8.self, capacity: bytelength) else {
fatalError("Invalid pointer")
}
var j = 0
for i in 0..<bytelength {
j = noReversalNeeded ? i : bytelength - 1 - i
res.append((ptr + j).pointee)
}
}
return res
} else {
return encodeArray(array)
}
}
public static func encode<A: CBOREncodable, B: CBOREncodable>(_ dict: [A: B]) -> Data {
return encodeMap(dict)
}
// MARK: - major 0: unsigned integer
public static func encodeUInt8(_ x: UInt8) -> Data {
if (x < 24) { return Data([x]) }
else { return Data([0x18, x]) }
}
public static func encodeUInt16(_ x: UInt16) -> Data {
return Data([0x19] + rawBytes(of: x))
}
public static func encodeUInt32(_ x: UInt32) -> Data {
return Data([0x1a] + rawBytes(of: x))
}
public static func encodeUInt64(_ x: UInt64) -> Data {
return Data([0x1b] + rawBytes(of: x))
}
internal static func encodeVarUInt(_ x: UInt64) -> Data {
switch x {
case let x where x <= UInt8.max: return CBOR.encodeUInt8(UInt8(x))
case let x where x <= UInt16.max: return CBOR.encodeUInt16(UInt16(x))
case let x where x <= UInt32.max: return CBOR.encodeUInt32(UInt32(x))
default: return CBOR.encodeUInt64(x)
}
}
// MARK: - major 1: negative integer
public static func encodeNegativeInt(_ x: Int64) -> Data {
assert(x < 0)
var res = encodeVarUInt(~UInt64(bitPattern: x))
res[0] = res[0] | 0b001_00000
return res
}
// MARK: - major 2: bytestring
public static func encodeByteString(_ bs: [UInt8]) -> Data {
var res = byteStringHeader(count: bs.count)
res.append(contentsOf: bs)
return res
}
static func byteStringHeader(count: Int) -> Data {
var res = count.cborEncode
res[0] = res[0] | 0b010_00000
return res
}
public static func encodeData(_ data: Data) -> Data {
return encodeByteString(data.bytes)
}
// MARK: - major 3: UTF8 string
static func stringHeader(str: String) -> Data {
let utf8array = Array(str.utf8)
var res = utf8array.count.cborEncode
res[0] = res[0] | 0b011_00000
return res
}
public static func encodeString(_ str: String) -> Data {
var res = stringHeader(str: str)
res.append(contentsOf: str.utf8Data)
return res
}
// MARK: - major 4: array of data items
public static func arrayHeader(count: Int) -> Data {
var res = count.cborEncode
res[0] = res[0] | 0b100_00000
return res
}
public static func encodeArray<T: CBOREncodable>(_ arr: [T]) -> Data {
var res = arrayHeader(count: arr.count)
res.append(contentsOf: arr.flatMap{ return $0.cborEncode })
return res
}
// MARK: - major 5: a map of pairs of data items
public static func mapHeader(count: Int) -> Data {
var res = Data()
res = count.cborEncode
res[0] = res[0] | 0b101_00000
return res
}
public static func encodeMap<A: CBOREncodable, B: CBOREncodable>(_ map: [A: B]) -> Data {
var res = mapHeader(count: map.count)
res.reserveCapacity(1 + map.count * (MemoryLayout<A>.size + MemoryLayout<B>.size + 2))
for (k, v) in map {
res.append(contentsOf: k.cborEncode)
res.append(contentsOf: v.cborEncode)
}
return res
}
public static func encodeOrderedMap(_ map: OrderedMap) -> Data {
var res = mapHeader(count: map.count)
for entry in map.elements {
res.append(contentsOf: entry.key.cborEncode)
res.append(contentsOf: entry.value.cborEncode)
}
return res
}
public static func encodeMap<A: CBOREncodable>(_ map: [A: Any?]) throws -> Data {
var res = Data()
res = map.count.cborEncode
res[0] = res[0] | 0b101_00000
try CBOR.encodeMap(map, into: &res)
return res
}
// MARK: - major 6: tagged values
public static func tagHeader(tag: Tag) -> Data {
var res = encodeVarUInt(tag.rawValue)
res[0] = res[0] | 0b110_00000
return res
}
public static func encodeTagged<T: CBOREncodable>(tag: Tag, value: T) -> Data {
var res = tagHeader(tag: tag)
res.append(contentsOf: value.cborEncode)
return res
}
// MARK: - major 7: floats, simple values, the 'break' stop code
public static func encodeSimpleValue(_ x: UInt8) -> Data {
if x < 24 {
return Data([0b111_00000 | x])
} else {
return Data([0xf8, x])
}
}
public static func encodeNull() -> Data {
return Data([0xf6])
}
public static func encodeUndefined() -> Data {
return Data([0xf7])
}
public static func encodeBreak() -> Data {
return Data([0xff])
}
public static func encodeFloat(_ x: Float) -> Data {
return Data([0xfa] + rawBytes(of: x))
}
public static func encodeDouble(_ x: Double) -> Data {
return Data([0xfb] + rawBytes(of: x))
}
public static func encodeBool(_ x: Bool) -> Data {
return Data(x ? [0xf5] : [0xf4])
}
// MARK: - Indefinite length items
/// Returns a CBOR value indicating the opening of an indefinite-length data item.
/// The user is responsible for creating and sending subsequent valid CBOR.
/// In particular, the user must end the stream with the CBOR.break byte, which
/// can be returned with `encodeStreamEnd()`.
///
/// The stream API is limited right now, but will get better when Swift allows
/// one to generically constrain the elements of generic Iterators, in which case
/// streaming implementation is trivial
public static func encodeArrayStreamStart() -> Data {
return Data([0x9f])
}
public static func encodeMapStreamStart() -> Data {
return Data([0xbf])
}
public static func encodeStringStreamStart() -> Data {
return Data([0x7f])
}
public static func encodeByteStringStreamStart() -> Data {
return Data([0x5f])
}
/// This is the same as a CBOR "break" value
public static func encodeStreamEnd() -> Data {
return Data([0xff])
}
// TODO: unify definite and indefinite code
public static func encodeArrayChunk<T: CBOREncodable>(_ chunk: [T]) -> Data {
var res = Data()
res.reserveCapacity(chunk.count * MemoryLayout<T>.size)
res.append(contentsOf: chunk.flatMap{ return $0.cborEncode })
return res
}
public static func encodeMapChunk<A: CBOREncodable, B: CBOREncodable>(_ map: [A: B]) -> Data {
var res = Data()
let count = map.count
res.reserveCapacity(count * MemoryLayout<A>.size + count * MemoryLayout<B>.size)
for (k, v) in map {
res.append(contentsOf: k.cborEncode)
res.append(contentsOf: v.cborEncode)
}
return res
}
public static func dateHeader() -> Data {
Data([0b110_00001])
}
public static func encodeDate(_ date: Date) -> Data {
let timeInterval = date.timeIntervalSince1970
let (integral, fractional) = modf(timeInterval)
let seconds = Int64(integral)
let nanoseconds = UInt32(fractional * Double(NSEC_PER_SEC))
var res = Data()
if seconds < 0 {
res.append(contentsOf: CBOR.encodeNegativeInt(Int64(timeInterval)))
} else if seconds > UInt32.max {
res.append(contentsOf: CBOR.encodeDouble(timeInterval))
} else if nanoseconds > 0 {
res.append(contentsOf: CBOR.encodeDouble(timeInterval))
} else {
res.append(contentsOf: CBOR.encode(Int(seconds)))
}
// Epoch timestamp tag is 1
return dateHeader() + res
}
public static func encodeAny(_ any: Any?) throws -> Data {
switch any {
case is Int:
return (any as! Int).cborEncode
case is UInt:
return (any as! UInt).cborEncode
case is UInt8:
return (any as! UInt8).cborEncode
case is UInt16:
return (any as! UInt16).cborEncode
case is UInt32:
return (any as! UInt32).cborEncode
case is UInt64:
return (any as! UInt64).cborEncode
case is String:
return (any as! String).cborEncode
case is Float:
return (any as! Float).cborEncode
case is Double:
return (any as! Double).cborEncode
case is Bool:
return (any as! Bool).cborEncode
case is [UInt8]:
return CBOR.encodeByteString(any as! [UInt8])
case is Data:
return CBOR.encodeData(any as! Data)
case is Date:
return CBOR.encodeDate(any as! Date)
case is NSNull:
return CBOR.encodeNull()
case is [Any]:
let anyArr = any as! [Any]
var res = anyArr.count.cborEncode
res[0] = res[0] | 0b100_00000
let encodedInners = try anyArr.reduce(into: []) { acc, next in
acc.append(contentsOf: try encodeAny(next))
}
res.append(contentsOf: encodedInners)
return res
case is [String: Any]:
let anyMap = any as! [String: Any]
var res = anyMap.count.cborEncode
res[0] = res[0] | 0b101_00000
try CBOR.encodeMap(anyMap, into: &res)
return res
case is Void:
return CBOR.encodeUndefined()
case nil:
return CBOR.encodeNull()
default:
throw CBOREncoderError.invalidType
}
}
private static func encodeMap<A: CBOREncodable>(_ map: [A: Any?], into res: inout Data) throws {
let sortedKeysWithEncodedKeys = map.keys.map {
(encoded: $0.cborEncode, key: $0)
}.sorted(by: {
$0.encoded.lexicographicallyPrecedes($1.encoded)
})
try sortedKeysWithEncodedKeys.forEach { keyTuple in
res.append(contentsOf: keyTuple.encoded)
let encodedVal = try encodeAny(map[keyTuple.key]!)
res.append(contentsOf: encodedVal)
}
}
}
public enum CBOREncoderError: LocalizedError {
case invalidType
public var errorDescription: String? {
switch self {
case .invalidType:
return "Invalid CBOR type."
}
}
}
| 32.795812 | 110 | 0.590358 |
620915f7e5ba0447dbe364c1a2250c368e2ad5ec | 33,995 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
private extension ByteBuffer {
mutating func withMutableWritePointer(body: (UnsafeMutableRawBufferPointer) throws -> IOResult<Int>) rethrows -> IOResult<Int> {
var singleResult: IOResult<Int>!
_ = try self.writeWithUnsafeMutableBytes { ptr in
let localWriteResult = try body(ptr)
singleResult = localWriteResult
switch localWriteResult {
case .processed(let written):
return written
case .wouldBlock(let written):
return written
}
}
return singleResult
}
}
/// A `Channel` for a client socket.
///
/// - note: All operations on `SocketChannel` are thread-safe.
final class SocketChannel: BaseSocketChannel<Socket> {
private var connectTimeout: TimeAmount? = nil
private var connectTimeoutScheduled: Scheduled<Void>?
private var allowRemoteHalfClosure: Bool = false
private var inputShutdown: Bool = false
private var outputShutdown: Bool = false
private let pendingWrites: PendingStreamWritesManager
// This is `Channel` API so must be thread-safe.
override public var isWritable: Bool {
return pendingWrites.isWritable
}
override var isOpen: Bool {
assert(eventLoop.inEventLoop)
assert(super.isOpen == self.pendingWrites.isOpen)
return super.isOpen
}
init(eventLoop: SelectableEventLoop, protocolFamily: Int32) throws {
let socket = try Socket(protocolFamily: protocolFamily, type: Posix.SOCK_STREAM, setNonBlocking: true)
self.pendingWrites = PendingStreamWritesManager(iovecs: eventLoop.iovecs, storageRefs: eventLoop.storageRefs)
try super.init(socket: socket, eventLoop: eventLoop, recvAllocator: AdaptiveRecvByteBufferAllocator())
}
init(eventLoop: SelectableEventLoop, descriptor: CInt) throws {
let socket = try Socket(descriptor: descriptor, setNonBlocking: true)
self.pendingWrites = PendingStreamWritesManager(iovecs: eventLoop.iovecs, storageRefs: eventLoop.storageRefs)
try super.init(socket: socket, eventLoop: eventLoop, recvAllocator: AdaptiveRecvByteBufferAllocator())
}
deinit {
// We should never have any pending writes left as otherwise we may leak callbacks
assert(pendingWrites.isEmpty)
}
override func setOption0<T: ChannelOption>(option: T, value: T.OptionType) throws {
assert(eventLoop.inEventLoop)
guard isOpen else {
throw ChannelError.ioOnClosedChannel
}
switch option {
case _ as ConnectTimeoutOption:
connectTimeout = value as? TimeAmount
case _ as AllowRemoteHalfClosureOption:
allowRemoteHalfClosure = value as! Bool
case _ as WriteSpinOption:
pendingWrites.writeSpinCount = value as! UInt
case _ as WriteBufferWaterMarkOption:
pendingWrites.waterMark = value as! WriteBufferWaterMark
default:
try super.setOption0(option: option, value: value)
}
}
override func getOption0<T: ChannelOption>(option: T) throws -> T.OptionType {
assert(eventLoop.inEventLoop)
guard isOpen else {
throw ChannelError.ioOnClosedChannel
}
switch option {
case _ as ConnectTimeoutOption:
return connectTimeout as! T.OptionType
case _ as AllowRemoteHalfClosureOption:
return allowRemoteHalfClosure as! T.OptionType
case _ as WriteSpinOption:
return pendingWrites.writeSpinCount as! T.OptionType
case _ as WriteBufferWaterMarkOption:
return pendingWrites.waterMark as! T.OptionType
default:
return try super.getOption0(option: option)
}
}
override func registrationFor(interested: SelectorEventSet) -> NIORegistration {
return .socketChannel(self, interested)
}
init(socket: Socket, parent: Channel? = nil, eventLoop: SelectableEventLoop) throws {
self.pendingWrites = PendingStreamWritesManager(iovecs: eventLoop.iovecs, storageRefs: eventLoop.storageRefs)
try super.init(socket: socket, parent: parent, eventLoop: eventLoop, recvAllocator: AdaptiveRecvByteBufferAllocator())
}
override func readFromSocket() throws -> ReadResult {
assert(self.eventLoop.inEventLoop)
// Just allocate one time for the while read loop. This is fine as ByteBuffer is a struct and uses COW.
var buffer = recvAllocator.buffer(allocator: allocator)
var result = ReadResult.none
for i in 1...maxMessagesPerRead {
guard self.isOpen && !self.inputShutdown else {
throw ChannelError.eof
}
// Reset reader and writerIndex and so allow to have the buffer filled again. This is better here than at
// the end of the loop to not do an allocation when the loop exits.
buffer.clear()
switch try buffer.withMutableWritePointer(body: self.socket.read(pointer:)) {
case .processed(let bytesRead):
if bytesRead > 0 {
let mayGrow = recvAllocator.record(actualReadBytes: bytesRead)
readPending = false
assert(self.isActive)
pipeline.fireChannelRead0(NIOAny(buffer))
result = .some
if buffer.writableBytes > 0 {
// If we did not fill the whole buffer with read(...) we should stop reading and wait until we get notified again.
// Otherwise chances are good that the next read(...) call will either read nothing or only a very small amount of data.
// Also this will allow us to call fireChannelReadComplete() which may give the user the chance to flush out all pending
// writes.
return result
} else if mayGrow && i < maxMessagesPerRead {
// if the ByteBuffer may grow on the next allocation due we used all the writable bytes we should allocate a new `ByteBuffer` to allow ramping up how much data
// we are able to read on the next read operation.
buffer = recvAllocator.buffer(allocator: allocator)
}
} else {
if inputShutdown {
// We received a EOF because we called shutdown on the fd by ourself, unregister from the Selector and return
readPending = false
unregisterForReadable()
return result
}
// end-of-file
throw ChannelError.eof
}
case .wouldBlock(let bytesRead):
assert(bytesRead == 0)
return result
}
}
return result
}
override func writeToSocket() throws -> OverallWriteResult {
let result = try self.pendingWrites.triggerAppropriateWriteOperations(scalarBufferWriteOperation: { ptr in
guard ptr.count > 0 else {
// No need to call write if the buffer is empty.
return .processed(0)
}
// normal write
return try self.socket.write(pointer: ptr)
}, vectorBufferWriteOperation: { ptrs in
// Gathering write
try self.socket.writev(iovecs: ptrs)
}, scalarFileWriteOperation: { descriptor, index, endIndex in
try self.socket.sendFile(fd: descriptor, offset: index, count: endIndex - index)
})
if result.writable {
// writable again
self.pipeline.fireChannelWritabilityChanged0()
}
return result.writeResult
}
override func connectSocket(to address: SocketAddress) throws -> Bool {
if try self.socket.connect(to: address) {
return true
}
if let timeout = connectTimeout {
connectTimeoutScheduled = eventLoop.scheduleTask(in: timeout) { () -> Void in
if self.pendingConnect != nil {
// The connection was still not established, close the Channel which will also fail the pending promise.
self.close0(error: ChannelError.connectTimeout(timeout), mode: .all, promise: nil)
}
}
}
return false
}
override func finishConnectSocket() throws {
if let scheduled = self.connectTimeoutScheduled {
// Connection established so cancel the previous scheduled timeout.
self.connectTimeoutScheduled = nil
scheduled.cancel()
}
try self.socket.finishConnect()
}
override func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) {
do {
switch mode {
case .output:
if outputShutdown {
promise?.fail(error: ChannelError.outputClosed)
return
}
try socket.shutdown(how: .WR)
outputShutdown = true
// Fail all pending writes and so ensure all pending promises are notified
pendingWrites.failAll(error: error, close: false)
unregisterForWritable()
promise?.succeed(result: ())
pipeline.fireUserInboundEventTriggered(ChannelEvent.outputClosed)
case .input:
if inputShutdown {
promise?.fail(error: ChannelError.inputClosed)
return
}
switch error {
case ChannelError.eof:
// No need to explicit call socket.shutdown(...) as we received an EOF and the call would only cause
// ENOTCON
break
default:
try socket.shutdown(how: .RD)
}
inputShutdown = true
unregisterForReadable()
promise?.succeed(result: ())
pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
case .all:
if let timeout = connectTimeoutScheduled {
connectTimeoutScheduled = nil
timeout.cancel()
}
super.close0(error: error, mode: mode, promise: promise)
}
} catch let err {
promise?.fail(error: err)
}
}
override func markFlushPoint() {
// Even if writable() will be called later by the EventLoop we still need to mark the flush checkpoint so we are sure all the flushed messages
// are actually written once writable() is called.
self.pendingWrites.markFlushCheckpoint()
}
override func cancelWritesOnClose(error: Error) {
self.pendingWrites.failAll(error: error, close: true)
}
@discardableResult override func readIfNeeded0() -> Bool {
if inputShutdown {
return false
}
return super.readIfNeeded0()
}
override public func read0() {
if inputShutdown {
return
}
super.read0()
}
override func bufferPendingWrite(data: NIOAny, promise: EventLoopPromise<Void>?) {
if outputShutdown {
promise?.fail(error: ChannelError.outputClosed)
return
}
guard let data = data.tryAsIOData() else {
promise?.fail(error: ChannelError.writeDataUnsupported)
return
}
if !self.pendingWrites.add(data: data, promise: promise) {
pipeline.fireChannelWritabilityChanged0()
}
}
}
/// A `Channel` for a server socket.
///
/// - note: All operations on `ServerSocketChannel` are thread-safe.
final class ServerSocketChannel: BaseSocketChannel<ServerSocket> {
private var backlog: Int32 = 128
private let group: EventLoopGroup
/// The server socket channel is never writable.
// This is `Channel` API so must be thread-safe.
override public var isWritable: Bool { return false }
convenience init(eventLoop: SelectableEventLoop, group: EventLoopGroup, protocolFamily: Int32) throws {
try self.init(serverSocket: try ServerSocket(protocolFamily: protocolFamily, setNonBlocking: true), eventLoop: eventLoop, group: group)
}
init(serverSocket: ServerSocket, eventLoop: SelectableEventLoop, group: EventLoopGroup) throws {
self.group = group
try super.init(socket: serverSocket, eventLoop: eventLoop, recvAllocator: AdaptiveRecvByteBufferAllocator())
}
convenience init(descriptor: CInt, eventLoop: SelectableEventLoop, group: EventLoopGroup) throws {
let socket = try ServerSocket(descriptor: descriptor, setNonBlocking: true)
try self.init(serverSocket: socket, eventLoop: eventLoop, group: group)
try self.socket.listen(backlog: backlog)
}
override func registrationFor(interested: SelectorEventSet) -> NIORegistration {
return .serverSocketChannel(self, interested)
}
override func setOption0<T: ChannelOption>(option: T, value: T.OptionType) throws {
assert(eventLoop.inEventLoop)
guard isOpen else {
throw ChannelError.ioOnClosedChannel
}
switch option {
case _ as BacklogOption:
backlog = value as! Int32
default:
try super.setOption0(option: option, value: value)
}
}
override func getOption0<T: ChannelOption>(option: T) throws -> T.OptionType {
assert(eventLoop.inEventLoop)
guard isOpen else {
throw ChannelError.ioOnClosedChannel
}
switch option {
case _ as BacklogOption:
return backlog as! T.OptionType
default:
return try super.getOption0(option: option)
}
}
override public func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
assert(eventLoop.inEventLoop)
guard self.isOpen else {
promise?.fail(error: ChannelError.ioOnClosedChannel)
return
}
guard self.isRegistered else {
promise?.fail(error: ChannelLifecycleError.inappropriateOperationForState)
return
}
let p: EventLoopPromise<Void> = eventLoop.newPromise()
p.futureResult.map {
// It's important to call the methods before we actually notify the original promise for ordering reasons.
self.becomeActive0(promise: promise)
}.whenFailure{ error in
promise?.fail(error: error)
}
executeAndComplete(p) {
try socket.bind(to: address)
self.updateCachedAddressesFromSocket(updateRemote: false)
try self.socket.listen(backlog: backlog)
}
}
override func connectSocket(to address: SocketAddress) throws -> Bool {
throw ChannelError.operationUnsupported
}
override func finishConnectSocket() throws {
throw ChannelError.operationUnsupported
}
override func readFromSocket() throws -> ReadResult {
var result = ReadResult.none
for _ in 1...maxMessagesPerRead {
guard self.isOpen else {
throw ChannelError.eof
}
if let accepted = try self.socket.accept(setNonBlocking: true) {
readPending = false
result = .some
do {
let chan = try SocketChannel(socket: accepted, parent: self, eventLoop: group.next() as! SelectableEventLoop)
assert(self.isActive)
pipeline.fireChannelRead0(NIOAny(chan))
} catch let err {
_ = try? accepted.close()
throw err
}
} else {
break
}
}
return result
}
override func shouldCloseOnReadError(_ err: Error) -> Bool {
guard let err = err as? IOError else { return true }
switch err.errnoCode {
case ECONNABORTED,
EMFILE,
ENFILE,
ENOBUFS,
ENOMEM:
// These are errors we may be able to recover from. The user may just want to stop accepting connections for example
// or provide some other means of back-pressure. This could be achieved by a custom ChannelDuplexHandler.
return false
default:
return true
}
}
override func cancelWritesOnClose(error: Error) {
// No writes to cancel.
return
}
override public func channelRead0(_ data: NIOAny) {
assert(eventLoop.inEventLoop)
let ch = data.forceAsOther() as SocketChannel
ch.eventLoop.execute {
ch.register().thenThrowing {
guard ch.isOpen else {
throw ChannelError.ioOnClosedChannel
}
ch.becomeActive0(promise: nil)
}.whenFailure { error in
ch.close(promise: nil)
}
}
}
override func bufferPendingWrite(data: NIOAny, promise: EventLoopPromise<Void>?) {
promise?.fail(error: ChannelError.operationUnsupported)
}
override func markFlushPoint() {
// We do nothing here: flushes are no-ops.
}
override func flushNow() -> IONotificationState {
return IONotificationState.unregister
}
}
/// A channel used with datagram sockets.
///
/// Currently this channel is in an early stage. It supports only unconnected
/// datagram sockets, and does not currently support either multicast or
/// broadcast send or receive.
///
/// The following features are well worth adding:
///
/// - Multicast support
/// - Broadcast support
/// - Connected mode
final class DatagramChannel: BaseSocketChannel<Socket> {
// Guard against re-entrance of flushNow() method.
private let pendingWrites: PendingDatagramWritesManager
// This is `Channel` API so must be thread-safe.
override public var isWritable: Bool {
return pendingWrites.isWritable
}
override var isOpen: Bool {
assert(eventLoop.inEventLoop)
assert(super.isOpen == self.pendingWrites.isOpen)
return super.isOpen
}
convenience init(eventLoop: SelectableEventLoop, descriptor: CInt) throws {
let socket = Socket(descriptor: descriptor)
do {
try self.init(socket: socket, eventLoop: eventLoop)
} catch {
_ = try? socket.close()
throw error
}
}
init(eventLoop: SelectableEventLoop, protocolFamily: Int32) throws {
let socket = try Socket(protocolFamily: protocolFamily, type: Posix.SOCK_DGRAM)
do {
try socket.setNonBlocking()
} catch let err {
_ = try? socket.close()
throw err
}
self.pendingWrites = PendingDatagramWritesManager(msgs: eventLoop.msgs,
iovecs: eventLoop.iovecs,
addresses: eventLoop.addresses,
storageRefs: eventLoop.storageRefs)
try super.init(socket: socket, eventLoop: eventLoop, recvAllocator: FixedSizeRecvByteBufferAllocator(capacity: 2048))
}
init(socket: Socket, parent: Channel? = nil, eventLoop: SelectableEventLoop) throws {
try socket.setNonBlocking()
self.pendingWrites = PendingDatagramWritesManager(msgs: eventLoop.msgs,
iovecs: eventLoop.iovecs,
addresses: eventLoop.addresses,
storageRefs: eventLoop.storageRefs)
try super.init(socket: socket, parent: parent, eventLoop: eventLoop, recvAllocator: FixedSizeRecvByteBufferAllocator(capacity: 2048))
}
// MARK: Datagram Channel overrides required by BaseSocketChannel
override func setOption0<T: ChannelOption>(option: T, value: T.OptionType) throws {
assert(eventLoop.inEventLoop)
guard isOpen else {
throw ChannelError.ioOnClosedChannel
}
switch option {
case _ as WriteSpinOption:
pendingWrites.writeSpinCount = value as! UInt
case _ as WriteBufferWaterMarkOption:
pendingWrites.waterMark = value as! WriteBufferWaterMark
default:
try super.setOption0(option: option, value: value)
}
}
override func getOption0<T: ChannelOption>(option: T) throws -> T.OptionType {
assert(eventLoop.inEventLoop)
guard isOpen else {
throw ChannelError.ioOnClosedChannel
}
switch option {
case _ as WriteSpinOption:
return pendingWrites.writeSpinCount as! T.OptionType
case _ as WriteBufferWaterMarkOption:
return pendingWrites.waterMark as! T.OptionType
default:
return try super.getOption0(option: option)
}
}
override func registrationFor(interested: SelectorEventSet) -> NIORegistration {
return .datagramChannel(self, interested)
}
override func connectSocket(to address: SocketAddress) throws -> Bool {
// For now we don't support operating in connected mode for datagram channels.
throw ChannelError.operationUnsupported
}
override func finishConnectSocket() throws {
// For now we don't support operating in connected mode for datagram channels.
throw ChannelError.operationUnsupported
}
override func readFromSocket() throws -> ReadResult {
var rawAddress = sockaddr_storage()
var rawAddressLength = socklen_t(MemoryLayout<sockaddr_storage>.size)
var buffer = self.recvAllocator.buffer(allocator: self.allocator)
var readResult = ReadResult.none
for i in 1...self.maxMessagesPerRead {
guard self.isOpen else {
throw ChannelError.eof
}
buffer.clear()
let result = try buffer.withMutableWritePointer {
try self.socket.recvfrom(pointer: $0, storage: &rawAddress, storageLen: &rawAddressLength)
}
switch result {
case .processed(let bytesRead):
assert(bytesRead > 0)
assert(self.isOpen)
let mayGrow = recvAllocator.record(actualReadBytes: bytesRead)
readPending = false
let msg = AddressedEnvelope(remoteAddress: rawAddress.convert(), data: buffer)
assert(self.isActive)
pipeline.fireChannelRead0(NIOAny(msg))
if mayGrow && i < maxMessagesPerRead {
buffer = recvAllocator.buffer(allocator: allocator)
}
readResult = .some
case .wouldBlock(let bytesRead):
assert(bytesRead == 0)
return readResult
}
}
return readResult
}
override func shouldCloseOnReadError(_ err: Error) -> Bool {
guard let err = err as? IOError else { return true }
switch err.errnoCode {
// ECONNREFUSED can happen on linux if the previous sendto(...) failed.
// See also:
// - https://bugzilla.redhat.com/show_bug.cgi?id=1375
// - https://lists.gt.net/linux/kernel/39575
case ECONNREFUSED,
ENOMEM:
// These are errors we may be able to recover from.
return false
default:
return true
}
}
/// Buffer a write in preparation for a flush.
override func bufferPendingWrite(data: NIOAny, promise: EventLoopPromise<Void>?) {
guard let data = data.tryAsByteEnvelope() else {
promise?.fail(error: ChannelError.writeDataUnsupported)
return
}
if !self.pendingWrites.add(envelope: data, promise: promise) {
assert(self.isActive)
pipeline.fireChannelWritabilityChanged0()
}
}
/// Mark a flush point. This is called when flush is received, and instructs
/// the implementation to record the flush.
override func markFlushPoint() {
// Even if writable() will be called later by the EventLoop we still need to mark the flush checkpoint so we are sure all the flushed messages
// are actually written once writable() is called.
self.pendingWrites.markFlushCheckpoint()
}
/// Called when closing, to instruct the specific implementation to discard all pending
/// writes.
override func cancelWritesOnClose(error: Error) {
self.pendingWrites.failAll(error: error, close: true)
}
override func writeToSocket() throws -> OverallWriteResult {
let result = try self.pendingWrites.triggerAppropriateWriteOperations(scalarWriteOperation: { (ptr, destinationPtr, destinationSize) in
guard ptr.count > 0 else {
// No need to call write if the buffer is empty.
return .processed(0)
}
// normal write
return try self.socket.sendto(pointer: ptr,
destinationPtr: destinationPtr,
destinationSize: destinationSize)
}, vectorWriteOperation: { msgs in
try self.socket.sendmmsg(msgs: msgs)
})
if result.writable {
// writable again
assert(self.isActive)
self.pipeline.fireChannelWritabilityChanged0()
}
return result.writeResult
}
// MARK: Datagram Channel overrides not required by BaseSocketChannel
override func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
assert(self.eventLoop.inEventLoop)
guard self.isRegistered else {
promise?.fail(error: ChannelLifecycleError.inappropriateOperationForState)
return
}
do {
try socket.bind(to: address)
self.updateCachedAddressesFromSocket(updateRemote: false)
becomeActive0(promise: promise)
} catch let err {
promise?.fail(error: err)
}
}
}
extension SocketChannel: CustomStringConvertible {
var description: String {
return "SocketChannel { selectable = \(self.selectable), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }"
}
}
extension ServerSocketChannel: CustomStringConvertible {
var description: String {
return "ServerSocketChannel { selectable = \(self.selectable), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }"
}
}
extension DatagramChannel: CustomStringConvertible {
var description: String {
return "DatagramChannel { selectable = \(self.selectable), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }"
}
}
extension DatagramChannel: MulticastChannel {
/// The socket options for joining and leaving multicast groups are very similar.
/// This enum allows us to write a single function to do all the work, and then
/// at the last second pull out the correct socket option name.
private enum GroupOperation {
/// Join a multicast group.
case join
/// Leave a multicast group.
case leave
/// Given a socket option level, returns the appropriate socket option name for
/// this group operation.
///
/// - parameters:
/// - level: The socket option level. Must be one of `IPPROTO_IP` or
/// `IPPROTO_IPV6`. Will trap if an invalid value is provided.
/// - returns: The socket option name to use for this group operation.
func optionName(level: CInt) -> CInt {
switch (self, level) {
case (.join, CInt(IPPROTO_IP)):
return CInt(IP_ADD_MEMBERSHIP)
case (.leave, CInt(IPPROTO_IP)):
return CInt(IP_DROP_MEMBERSHIP)
case (.join, CInt(IPPROTO_IPV6)):
return CInt(IPV6_JOIN_GROUP)
case (.leave, CInt(IPPROTO_IPV6)):
return CInt(IPV6_LEAVE_GROUP)
default:
preconditionFailure("Unexpected socket option level: \(level)")
}
}
}
public func joinGroup(_ group: SocketAddress, interface: NIONetworkInterface?, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
self.performGroupOperation0(group, interface: interface, promise: promise, operation: .join)
} else {
eventLoop.execute {
self.performGroupOperation0(group, interface: interface, promise: promise, operation: .join)
}
}
}
public func leaveGroup(_ group: SocketAddress, interface: NIONetworkInterface?, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
self.performGroupOperation0(group, interface: interface, promise: promise, operation: .leave)
} else {
eventLoop.execute {
self.performGroupOperation0(group, interface: interface, promise: promise, operation: .leave)
}
}
}
/// The implementation of `joinGroup` and `leaveGroup`.
///
/// Joining and leaving a multicast group ultimately corresponds to a single, carefully crafted, socket option.
private func performGroupOperation0(_ group: SocketAddress,
interface: NIONetworkInterface?,
promise: EventLoopPromise<Void>?,
operation: GroupOperation) {
assert(self.eventLoop.inEventLoop)
guard self.isActive else {
promise?.fail(error: ChannelLifecycleError.inappropriateOperationForState)
return
}
// We need to check that we have the appropriate address types in all cases. They all need to overlap with
// the address type of this channel, or this cannot work.
guard let localAddress = self.localAddress else {
promise?.fail(error: MulticastError.unknownLocalAddress)
return
}
guard localAddress.protocolFamily == group.protocolFamily else {
promise?.fail(error: MulticastError.badMulticastGroupAddressFamily)
return
}
// Ok, now we need to check that the group we've been asked to join is actually a multicast group.
guard group.isMulticast else {
promise?.fail(error: MulticastError.illegalMulticastAddress(group))
return
}
// Ok, we now have reason to believe this will actually work. We need to pass this on to the socket.
do {
switch (group, interface?.address) {
case (.unixDomainSocket, _):
preconditionFailure("Should not be reachable, UNIX sockets are never multicast addresses")
case (.v4(let groupAddress), .some(.v4(let interfaceAddress))):
// IPv4Binding with specific target interface.
let multicastRequest = ip_mreq(imr_multiaddr: groupAddress.address.sin_addr, imr_interface: interfaceAddress.address.sin_addr)
try self.socket.setOption(level: CInt(IPPROTO_IP), name: operation.optionName(level: CInt(IPPROTO_IP)), value: multicastRequest)
case (.v4(let groupAddress), .none):
// IPv4 binding without target interface.
let multicastRequest = ip_mreq(imr_multiaddr: groupAddress.address.sin_addr, imr_interface: in_addr(s_addr: INADDR_ANY))
try self.socket.setOption(level: CInt(IPPROTO_IP), name: operation.optionName(level: CInt(IPPROTO_IP)), value: multicastRequest)
case (.v6(let groupAddress), .some(.v6)):
// IPv6 binding with specific target interface.
let multicastRequest = ipv6_mreq(ipv6mr_multiaddr: groupAddress.address.sin6_addr, ipv6mr_interface: UInt32(interface!.interfaceIndex))
try self.socket.setOption(level: CInt(IPPROTO_IPV6), name: operation.optionName(level: CInt(IPPROTO_IPV6)), value: multicastRequest)
case (.v6(let groupAddress), .none):
// IPv6 binding with no specific interface requested.
let multicastRequest = ipv6_mreq(ipv6mr_multiaddr: groupAddress.address.sin6_addr, ipv6mr_interface: 0)
try self.socket.setOption(level: CInt(IPPROTO_IPV6), name: operation.optionName(level: CInt(IPPROTO_IPV6)), value: multicastRequest)
case (.v4, .some(.v6)), (.v6, .some(.v4)), (.v4, .some(.unixDomainSocket)), (.v6, .some(.unixDomainSocket)):
// Mismatched group and interface address: this is an error.
throw MulticastError.badInterfaceAddressFamily
}
promise?.succeed(result: ())
} catch {
promise?.fail(error: error)
return
}
}
}
| 39.947121 | 183 | 0.612649 |
792206cf0ec8823fa8631da936db90e0f8022d39 | 1,000 | //
// CGSizeToDictionary.swift
// Mixpanel
//
// Created by Yarden Eitan on 9/6/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
import UIKit
@objc(CGSizeToNSDictionary) class CGSizeToNSDictionary: ValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSDictionary.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
override func transformedValue(_ value: Any?) -> Any? {
guard let value = value as? NSValue, value.responds(to: #selector(getter: NSValue.cgSizeValue)) else {
return nil
}
return value.cgSizeValue.dictionaryRepresentation as NSDictionary
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
let dict = value as! CFDictionary
if let size = CGSize(dictionaryRepresentation: dict) {
return NSValue(cgSize: size)
}
return NSValue(cgSize: .zero)
}
}
| 25.641026 | 110 | 0.662 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.