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
|
---|---|---|---|---|---|
e806588feae5602683468adc676ebf87c1d275c2 | 913 | //
// PushNotificationRegistrationRepository.swift
// Data
//
// Created by Ryne Cheow on 28/9/17.
// Copyright © 2017 Pointwelve. All rights reserved.
//
import Domain
import Foundation
import RxSwift
typealias PushNotificationRegistrationRepositoryType = Gettable
class PushNotificationRegistrationRepository: PushNotificationRegistrationRepositoryType {
typealias Key = String
typealias Value = Void
fileprivate let cache: BasicCache<String, StandardResponseData>
init(apiClient: APIClient) {
cache = NetworkDataSource(apiClient: apiClient,
keyTransformer: RouterTransformer.registerPush(),
valueTransformer: JsonTransformer.standardResponse()).asBasicCache()
}
}
extension PushNotificationRegistrationRepository {
func get(_ key: String) -> Observable<Void> {
return cache.get(key).map { _ in () }
}
}
| 27.666667 | 100 | 0.715225 |
dd293b1ab7728e97c2e2aa72d8937a4178b67957 | 4,389 | //
// SHWKWebView.swift
// SHKit
//
// Created by hsh on 2019/6/4.
// Copyright © 2019 hsh. All rights reserved.
//
import UIKit
import WebKit
//WebView
public class SHWKWebView: WKWebView {
//加载请求
@discardableResult
public override func load(_ request:URLRequest)->WKNavigation?{
if #available(iOS 11.0,*) {
return super.load(request)!;
}
//处理iOS11之前POST请求的参数问题
if (request.httpMethod?.uppercased() == "POST"){
guard let url = request.url?.absoluteString else { return nil};
var params:String = String(data: request.httpBody!, encoding: .utf8)!;
if (params.contains("=")){
params = params.replacingOccurrences(of: "=", with: "\":\"");
params = params.replacingOccurrences(of: "&", with: "\",\"");
params = String(format: "{\"%@\"}", params);
}else{
params = "{}";
}
let postJavaScript = String(format: "var url = '%@';var params = %@;var form = document.createElement('form');form.setAttribute('method', 'post');form.setAttribute('action', url);for(var key in params) {if(params.hasOwnProperty(key)) {var hiddenField = document.createElement('input');hiddenField.setAttribute('type', 'hidden');hiddenField.setAttribute('name', key);hiddenField.setAttribute('value', params[key]);form.appendChild(hiddenField);}}document.body.appendChild(form);form.submit();", url,params);
self.evaluateJavaScript(postJavaScript) { [unowned self] (object, error) in
if (error != nil){
self.navigationDelegate?.webView?(self, didFailProvisionalNavigation: nil, withError: error!);
}
}
return nil
}else{
return super.load(request);
}
}
//加载请求带post参数
public func loadRequest(_ request:inout URLRequest,postDict:NSDictionary)->WKNavigation?{
if (postDict.count == 0) {
return self.load(request);
}
let keys:[String] = postDict.allKeys as! [String];
let tmpStr = NSMutableString()
for (index,key) in keys.enumerated() {
if (index > 0){
tmpStr.append("&");
}
tmpStr.append(String(format: "%@=%@", keys[index],postDict.value(forKey: key) as! CVarArg));
}
request.httpMethod = "POST";
request.httpBody = tmpStr.data(using: String.Encoding.utf8.rawValue);
return self.load(request);
}
//带设置cookie参数接口
public func loadRequest(_ request:URLRequest,cookiesDict:NSDictionary)->WKNavigation?{
if #available(iOS 11.0, *) {
let cookieStore = self.configuration.websiteDataStore.httpCookieStore;
var wkNavigation:WKNavigation?
cookieStore.getAllCookies { (cookies) in
if (cookies.count > 0) {
for cookie in cookies{
cookieStore.setCookie(cookie, completionHandler: {
print(cookie);
})
}
}
wkNavigation = self.load(request);
}
return wkNavigation;
}
if (cookiesDict.allKeys.count == 0) {
return self.load(request);
}
var finalRequest = request;
let keys:[String] = cookiesDict.allKeys as! [String];
let cookiesStr = NSMutableString()
for (index,value) in keys.enumerated() {
if (index > 0){
cookiesStr.append(value);
}
cookiesStr.appendFormat("%@=%@", keys[index],cookiesDict.value(forKey:keys[index]) as! CVarArg);
}
if (cookiesStr.length > 0){
finalRequest.addValue(cookiesStr as String, forHTTPHeaderField: "Cookie");
}
return self.load(finalRequest);
}
//清除缓存
public func cleanCache(){
//iOS9
let websiteDataTypes:NSSet = NSSet(set: [WKWebsiteDataTypeDiskCache,WKWebsiteDataTypeOfflineWebApplicationCache,WKWebsiteDataTypeMemoryCache]);
let from:Date = Date(timeIntervalSince1970: 0);
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: from) {
print("清除缓存完毕");
};
}
}
| 37.512821 | 518 | 0.570517 |
5b9d14632e2b6ebab06d66897ce5081d9a0ed395 | 2,035 | //
// BookCoverCollectionViewCell.swift
// MAD
//
// Created by Lily Li on 12/26/17.
// Copyright © 2017 Eric C. All rights reserved.
//
import UIKit
import Lottie
class BookCoverCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var coverImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var blurredView: UIView!
@IBOutlet weak var boundingView: UIView!
var animationView: LOTAnimationView = LOTAnimationView(name: "scan");
var timer = Timer()
override func awakeFromNib() {
super.awakeFromNib()
coverImageView.layer.cornerRadius=15
coverImageView.layer.masksToBounds=true
boundingView.layer.cornerRadius=25
boundingView.layer.masksToBounds=true
//coverImageView.backgroundColor = UIColor.blue
//let animationView: LOTAnimationView = LOTAnimationView(name: "scan");
animationView.contentMode = .scaleAspectFill
animationView.frame = CGRect(x: 17, y: 55, width: 135, height: 135)
coverImageView.tintColor = UIColor.red
self.boundingView.addSubview(animationView)
//self.boundingView.sendSubview(toBack: animationView)
self.boundingView.bringSubview(toFront: coverImageView)
//self.coverImageView.sendSubview(toBack: animationView)
animationView.loopAnimation = true
//animationView.play()
animationView.play(fromProgress: 0, toProgress: 1.0, withCompletion: nil)
timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(SearchTableViewController.action), userInfo: nil, repeats: true)
}
@objc func action()
{
//print(titleLabel.text)
if(self.coverImageView.image != nil && animationView.isHidden == false)
{
animationView.pause()
animationView.isHidden = true
self.timer.invalidate()
//print(titleLabel.text)
}
}
}
| 31.307692 | 156 | 0.657494 |
fc2d91b64831d7c58a066683a298a523956083bb | 613 | //
// AppReducer.swift
// MobileApp
//
// Created by Mariusz Sut on 11/11/2020.
// Copyright © 2020 MSut. All rights reserved.
//
import Foundation
struct AppReducer {
static func reduce(state: AppState, action: Action) -> AppState {
var mutableState = state
mutableState.mainState = MainReducer.reduce(state: state.mainState, action: action)
mutableState.searchTabState = SearchTabReducer.reduce(state: state.searchTabState, action: action)
mutableState.aboutTabState = AboutReducer.reduce(state: state.aboutTabState, action: action)
return mutableState
}
}
| 30.65 | 106 | 0.712887 |
69f071a84bd5bcc0b8b6754e66ddb4bb964b67fb | 2,182 | //
// LoginViewModelTests.swift
// LoginChallengeTests
//
// Created by Toshiya Kobayashi on 2022/02/05.
//
import XCTest
import Entities
@testable import LoginChallenge
class LoginViewModelTests: XCTestCase {
class ResolverMock: Resolver {
let authRepositoryMock = AuthRepositoryMock()
override func authRepository() -> AuthRepository { authRepositoryMock }
}
var viewModel: LoginViewModel!
var resolver: ResolverMock!
override func setUpWithError() throws {
resolver = ResolverMock()
Resolver.instance = resolver
viewModel = LoginViewModel()
}
override func tearDownWithError() throws {
Resolver.reset()
}
func test_ログインボタンが無効の時はログイン処理を行わない() async throws {
XCTAssertFalse(viewModel.state.isLoginButtonEnabled)
resolver.authRepositoryMock.loginHandler = { (_, _) in
XCTFail()
}
let result = try await publishedValues(of: viewModel.$state.map(\.isLoading).removeDuplicates()) {
await viewModel.onLoginButtonDidTap()
}
XCTAssertEqual(result, [false])
}
func test_ログイン処理中はローディング中状態になりログイン完了後は非ローディング状態になる() async throws {
viewModel.onInputFieldValueChanged(id: "a", password: "a")
let result = try await publishedValues(of: viewModel.$state.map(\.isLoading).removeDuplicates()) {
await viewModel.onLoginButtonDidTap()
}
XCTAssertEqual(result, [false, true, false])
}
func test_ログイン完了するとホーム画面に遷移する() async throws {
viewModel.onInputFieldValueChanged(id: "a", password: "a")
XCTAssertFalse(viewModel.state.showHomeView)
await viewModel.onLoginButtonDidTap()
XCTAssertTrue(viewModel.state.showHomeView)
}
func test_ログイン失敗時にエラーアラートを表示する() async throws {
viewModel.onInputFieldValueChanged(id: "a", password: "a")
XCTAssertNil(viewModel.state.showErrorAlert)
resolver.authRepositoryMock.loginHandler = { (_, _) in
throw GeneralError(message: "")
}
await viewModel.onLoginButtonDidTap()
XCTAssertEqual(viewModel.state.showErrorAlert, .system)
}
}
| 28.337662 | 106 | 0.675985 |
751b819c2a3e71dd56153621b75f5ceac7040dc7 | 14,308 | import UIKit
import AVFoundation
class GenerateAvatarViewController: ViewController<GenerateAvatarView> {
enum InfoLabels {
case waitingCameraAccess
case noFace
case smallFace
case takingPhoto
case nothing
}
private var layers: String?
private var shouldAutoOpenCamera: Bool = true
private var isAvatarGenerated: Bool = false
private var faceDetected = false
private var smallFace = false
private var faceDetectTimer: Timer?
private var locked = false
private var uploadTask: URLSessionDataTask?
private let player: AVPlayer = {
let path = Bundle.resourceBundle.path(forResource: "onboardingAvatar", ofType: "mp4")!
let player = AVPlayer(url: URL(fileURLWithPath: path))
return player
}()
var infoLabel: InfoLabels = .waitingCameraAccess {
didSet {
DispatchQueue.main.async {
self.updateInfoLabel()
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
override func viewDidLoad() {
super.viewDidLoad()
mainView.linesRoundRotateAnimationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openCamera)))
mainView.allowButton.addTarget(self, action: #selector(allowButtonTapped), for: .touchUpInside)
mainView.continueButton.addTarget(self, action: #selector(continueButtonTapped), for: .touchUpInside)
mainView.camera.delegate = self
mainView.onboardingAvatarVideoView.playerLayer.player = player
play()
bindEvents()
updateButtonTitles()
}
// MARK: - Private Actions
@objc private func bindEvents() {
NotificationCenter.default.addObserver(self, selector: #selector(pause), name: .UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(play), name: .UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(close), name: .AVPlayerItemDidPlayToEndTime, object: nil)
}
@objc private func close() {
mainView.linesRoundRotateAnimationView.rotate()
UIView.animate(withDuration: 0.3) {
self.mainView.onboardingAvatarVideoView.alpha = 0
self.mainView.avatarPlaceholderView.alpha = 1
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
if self?.shouldAutoOpenCamera == true {
self?.checkCameraAccess()
}
}
removeEvents()
}
@objc private func pause() {
player.pause()
}
@objc private func play() {
mainView.onboardingAvatarVideoView.alpha = 1
mainView.avatarPlaceholderView.alpha = 0
player.play()
mainView.linesRoundRotateAnimationView.update(lineType: .dot)
UIView.animate(withDuration: 0.3, delay: 1.15, options: .curveEaseOut) {
self.mainView.linesRoundRotateAnimationView.update(lineType: .line)
}
}
@objc private func openCamera() {
initCamera()
}
@objc private func continueButtonTapped() {
if isAvatarGenerated {
initCamera()
} else {
shouldAutoOpenCamera = false
layers = ImageLoader.defaultLayers
close()
isAvatarGenerated = true
nextStep()
}
}
@objc private func allowButtonTapped() {
if isAvatarGenerated {
nextStep()
} else {
let status = AVCaptureDevice.authorizationStatus(for: .video)
if status == .authorized {
close()
} else {
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return }
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: nil)
}
}
}
}
// MARK: - Private Methods
private func removeEvents() {
NotificationCenter.default.removeObserver(self)
}
private func checkCameraAccess() {
let status = AVCaptureDevice.authorizationStatus(for: .video)
if status == .notDetermined {
AVCaptureDevice.requestAccess(for: .video) { [weak self] response in
if response {
DispatchQueue.main.async { [weak self] in
self?.showCameraController()
}
}
}
} else if status == .authorized {
showCameraController()
}
updateButtonTitles()
}
private func showCameraController() {
initCamera()
}
private func updateAvatar() {
mainView.camera.previewLayer.alpha = 0
mainView.avatarPlaceholderView.alpha = 0
mainView.linesRoundRotateAnimationView.alpha = 0
mainView.descriptionLabel.alpha = 0
mainView.avatarImageView.alpha = 1
mainView.backgroundImageView.alpha = 1
isAvatarGenerated = true
let side = mainView.avatarImageView.bounds.size.height
ImageLoader.setAvatar(with: layers, for: mainView.avatarImageView, side: side, cornerRadius: side/2)
}
private func nextStep() {
guard let layers = layers else { return }
let vc = StickerFaceViewController(type: .editor, layers: layers)
vc.modalPresentationStyle = .fullScreen
navigationController?.setViewControllers([vc], animated: true)
}
private func updateButtonTitles() {
let continueTitle: String
let allowTitle: String
if isAvatarGenerated {
continueTitle = "setupAvatarGenerateNewTitle".libraryLocalized
allowTitle = "commonContinue".libraryLocalized
} else {
let status = AVCaptureDevice.authorizationStatus(for: .video)
allowTitle = status == .authorized ?
"setupAvatarGenerateTitle".libraryLocalized :
"setupAvatarAllowTitle".libraryLocalized
continueTitle = "setupAvatarContinueTitle".libraryLocalized
}
mainView.allowButton.setTitle(allowTitle, for: .normal)
mainView.continueButton.setTitle(continueTitle, for: .normal)
}
func initCamera() {
mainView.avatarPlaceholderView.alpha = 1
mainView.linesRoundRotateAnimationView.alpha = 1
mainView.avatarImageView.alpha = 0
mainView.backgroundImageView.alpha = 0
mainView.camera.previewLayer.alpha = 1
mainView.linesRoundRotateAnimationView.setState(false)
mainView.linesRoundRotateAnimationView.loader(false, completion: {
let session = self.mainView.camera.session
DispatchQueue.global(qos: .background).async {
session.startRunning()
}
})
}
@objc func hasFaceDidChange() {
if faceDetected {
mainView.linesRoundRotateAnimationView.setState(true)
faceDetectTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(takePhoto), userInfo: nil, repeats: false)
} else if smallFace {
infoLabel = .smallFace
} else {
infoLabel = .noFace
}
mainView.linesRoundRotateAnimationView.setState(faceDetected)
}
@objc func takePhoto() {
locked = true
mainView.camera.capturePhoto()
}
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
var newSize: CGSize
if widthRatio > heightRatio {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func upload(_ image: Data) {
let defaultLayers = "1;28;35;67;69;159;160;16;13;37"
let resizedImage = resizeImage(image: UIImage(data: image, scale:1.0)!, targetSize: CGSize(width: 600, height: 600))
let imageData = UIImageJPEGRepresentation(resizedImage, 0.9)
let urlString = "https://sticker.face.cat/api/process?platform=ios"
let session = URLSession(configuration: URLSessionConfiguration.default)
let mutableURLRequest = NSMutableURLRequest(url: NSURL(string: urlString)! as URL)
mutableURLRequest.httpMethod = "POST"
let boundaryConstant = "----------------12345";
let contentType = "multipart/form-data;boundary=" + boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add image
uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"file\"; filename=\"filename.jpg\"\r\n".data(using: .utf8)!)
uploadData.append("Content-Type: image\r\n\r\n".data(using: .utf8)!)
uploadData.append(imageData!)
uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)
mutableURLRequest.httpBody = uploadData as Data
uploadTask = session.dataTask(with: mutableURLRequest as URLRequest, completionHandler: { [weak self] data, _, error in
guard let self = self else {
return
}
if error != nil {
self.setupLayers(defaultLayers)
} else if let data = data {
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
self.setupLayers(defaultLayers)
return
}
guard json["error"] == nil else {
self.setupLayers(defaultLayers)
return
}
var stickers = [String]()
if let stickersRaw = json["stickers"] as? [Int] {
for i in stickersRaw {
stickers.append("\(i)")
}
}
if let layers = json["model"] as? String {
DispatchQueue.main.async {
self.setupLayers(layers)
}
}
} catch {
self.setupLayers(defaultLayers)
}
}
})
uploadTask?.resume()
}
private func setupLayers(_ layers: String) {
self.layers = layers
locked = false
smallFace = false
faceDetected = false
updateAvatar()
updateButtonTitles()
}
func updateInfoLabel() {
var text: String
switch infoLabel {
case .waitingCameraAccess:
text = "setupAvatarWaitingCameraAccess".libraryLocalized
case .noFace:
text = "setupAvatarNoFace".libraryLocalized
case .smallFace:
text = "setupAvatarSmallFace".libraryLocalized
case .takingPhoto:
text = "setupAvaterTakingPhoto".libraryLocalized
case .nothing:
text = ""
}
mainView.subtitleLabel.text = text
}
}
// MARK: - SFCameraDelegate
extension GenerateAvatarViewController: SFCameraDelegate {
func camera(_ camera: SFCamera, faceDidDetect frame: CGRect) {
if faceDetected || locked {
return
}
faceDetected = true
smallFace = false
DispatchQueue.main.async {
self.faceDetectTimer?.invalidate()
self.faceDetectTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.hasFaceDidChange), userInfo: nil, repeats: false)
}
}
func cameraFacesDidNotDetect(_ camera: SFCamera) {
if !faceDetected && !smallFace || locked {
return
}
faceDetected = false
smallFace = false
DispatchQueue.main.async {
self.faceDetectTimer?.invalidate()
self.faceDetectTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.hasFaceDidChange), userInfo: nil, repeats: false)
}
}
func cameraFacesSmallDetect(_ camera: SFCamera) {
if smallFace || locked {
return
}
faceDetected = false
smallFace = true
DispatchQueue.main.async {
self.faceDetectTimer?.invalidate()
self.faceDetectTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.hasFaceDidChange), userInfo: nil, repeats: false)
}
}
func camera(_ camera: SFCamera, photoDidTake image: Data) {
mainView.avatarPlaceholderView.alpha = 0
camera.previewLayer.alpha = 0
mainView.linesRoundRotateAnimationView.loader(true) {
self.upload(image)
}
mainView.camera.session.stopRunning()
}
}
| 34.477108 | 163 | 0.581353 |
f7e876ed2c440b077f280a3b5729cd7a64ce9cbb | 1,421 | //
// AppDelegate.swift
// AutoLayout_Example
//
// Created by Kas Song on 2020.05.15.
// Copyright © 2020 Kas Song. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.394737 | 179 | 0.748065 |
769b06e2937262612f1820a1d9baa7410a7cc5ce | 986 | //
// PeriodQNARouter.swift
// Moody
//
// Created by Neha Pant on 26/06/2019.
// Copyright (c) 2019 Neha Pant. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
@objc protocol PeriodQNARoutingLogic
{
func routeNextScreen()
func popScreen()
}
protocol PeriodQNADataPassing
{
var dataStore: PeriodQNADataStore? { get }
}
class PeriodQNARouter: NSObject, PeriodQNARoutingLogic, PeriodQNADataPassing
{
weak var viewController: PeriodQNAViewController?
var dataStore: PeriodQNADataStore?
func routeNextScreen() {
let contraceptiveQNAScreen = ContraceptiveViewController()
viewController?.navigationController?.pushViewController(contraceptiveQNAScreen, animated: true)
}
func popScreen(){
viewController?.navigationController?.popViewController(animated: true)
}
}
| 25.282051 | 104 | 0.736308 |
188f80e0856e0eafbc61f3e9ce25359158727a8d | 327 | //
// SharedTypes.swift
//
// https://github.com/netzgut/integral-swift
//
// Copyright (c) 2020 Ben Weidig
//
// This work is licensed under the terms of the MIT license.
// For a copy, see LICENSE, or <https://opensource.org/licenses/MIT>
//
public typealias Factory<T> = () -> T
internal typealias Proxy<T> = () -> T
| 21.8 | 69 | 0.66055 |
75ca003cb1d3e3b51867c7055bdc269ca3f571d6 | 45,774 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: mission_raw.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct Mavsdk_Rpc_MissionRaw_UploadMissionRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The mission items
var missionItems: [Mavsdk_Rpc_MissionRaw_MissionItem] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_UploadMissionResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_CancelMissionUploadRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_CancelMissionUploadResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_DownloadMissionRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_DownloadMissionResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
/// The mission items
var missionItems: [Mavsdk_Rpc_MissionRaw_MissionItem] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_CancelMissionDownloadRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_CancelMissionDownloadResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_StartMissionRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_StartMissionResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_PauseMissionRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_PauseMissionResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_ClearMissionRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_ClearMissionResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Index of the mission item to be set as the next one (0-based)
var index: Int32 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult {
get {return _missionRawResult ?? Mavsdk_Rpc_MissionRaw_MissionRawResult()}
set {_missionRawResult = newValue}
}
/// Returns true if `missionRawResult` has been explicitly set.
var hasMissionRawResult: Bool {return self._missionRawResult != nil}
/// Clears the value of `missionRawResult`. Subsequent reads from it will return its default value.
mutating func clearMissionRawResult() {self._missionRawResult = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult? = nil
}
struct Mavsdk_Rpc_MissionRaw_SubscribeMissionProgressRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_MissionProgressResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Mission progress
var missionProgress: Mavsdk_Rpc_MissionRaw_MissionProgress {
get {return _missionProgress ?? Mavsdk_Rpc_MissionRaw_MissionProgress()}
set {_missionProgress = newValue}
}
/// Returns true if `missionProgress` has been explicitly set.
var hasMissionProgress: Bool {return self._missionProgress != nil}
/// Clears the value of `missionProgress`. Subsequent reads from it will return its default value.
mutating func clearMissionProgress() {self._missionProgress = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _missionProgress: Mavsdk_Rpc_MissionRaw_MissionProgress? = nil
}
struct Mavsdk_Rpc_MissionRaw_SubscribeMissionChangedRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Mavsdk_Rpc_MissionRaw_MissionChangedResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Mission has changed
var missionChanged: Bool = false
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Mission progress type.
struct Mavsdk_Rpc_MissionRaw_MissionProgress {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Current mission item index (0-based)
var current: Int32 = 0
/// Total number of mission items
var total: Int32 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Mission item exactly identical to MAVLink MISSION_ITEM_INT.
struct Mavsdk_Rpc_MissionRaw_MissionItem {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Sequence (uint16_t)
var seq: UInt32 = 0
/// The coordinate system of the waypoint (actually uint8_t)
var frame: UInt32 = 0
/// The scheduled action for the waypoint (actually uint16_t)
var command: UInt32 = 0
/// false:0, true:1 (actually uint8_t)
var current: UInt32 = 0
/// Autocontinue to next waypoint (actually uint8_t)
var autocontinue: UInt32 = 0
/// PARAM1, see MAV_CMD enum
var param1: Float = 0
/// PARAM2, see MAV_CMD enum
var param2: Float = 0
/// PARAM3, see MAV_CMD enum
var param3: Float = 0
/// PARAM4, see MAV_CMD enum
var param4: Float = 0
/// PARAM5 / local: x position in meters * 1e4, global: latitude in degrees * 10^7
var x: Int32 = 0
/// PARAM6 / y position: local: x position in meters * 1e4, global: longitude in degrees *10^7
var y: Int32 = 0
/// PARAM7 / local: Z coordinate, global: altitude (relative or absolute, depending on frame)
var z: Float = 0
/// @brief Mission type (actually uint8_t)
var missionType: UInt32 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Result type.
struct Mavsdk_Rpc_MissionRaw_MissionRawResult {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Result enum value
var result: Mavsdk_Rpc_MissionRaw_MissionRawResult.Result = .unknown
/// Human-readable English string describing the result
var resultStr: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
/// Possible results returned for action requests.
enum Result: SwiftProtobuf.Enum {
typealias RawValue = Int
/// Unknown result
case unknown // = 0
/// Request succeeded
case success // = 1
/// Error
case error // = 2
/// Too many mission items in the mission
case tooManyMissionItems // = 3
/// Vehicle is busy
case busy // = 4
/// Request timed out
case timeout // = 5
/// Invalid argument
case invalidArgument // = 6
/// Mission downloaded from the system is not supported
case unsupported // = 7
/// No mission available on the system
case noMissionAvailable // = 8
/// Mission transfer (upload or download) has been cancelled
case transferCancelled // = 9
case UNRECOGNIZED(Int)
init() {
self = .unknown
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .unknown
case 1: self = .success
case 2: self = .error
case 3: self = .tooManyMissionItems
case 4: self = .busy
case 5: self = .timeout
case 6: self = .invalidArgument
case 7: self = .unsupported
case 8: self = .noMissionAvailable
case 9: self = .transferCancelled
default: self = .UNRECOGNIZED(rawValue)
}
}
var rawValue: Int {
switch self {
case .unknown: return 0
case .success: return 1
case .error: return 2
case .tooManyMissionItems: return 3
case .busy: return 4
case .timeout: return 5
case .invalidArgument: return 6
case .unsupported: return 7
case .noMissionAvailable: return 8
case .transferCancelled: return 9
case .UNRECOGNIZED(let i): return i
}
}
}
init() {}
}
#if swift(>=4.2)
extension Mavsdk_Rpc_MissionRaw_MissionRawResult.Result: CaseIterable {
// The compiler won't synthesize support with the UNRECOGNIZED case.
static var allCases: [Mavsdk_Rpc_MissionRaw_MissionRawResult.Result] = [
.unknown,
.success,
.error,
.tooManyMissionItems,
.busy,
.timeout,
.invalidArgument,
.unsupported,
.noMissionAvailable,
.transferCancelled,
]
}
#endif // swift(>=4.2)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "mavsdk.rpc.mission_raw"
extension Mavsdk_Rpc_MissionRaw_UploadMissionRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".UploadMissionRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_items"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedMessageField(value: &self.missionItems)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.missionItems.isEmpty {
try visitor.visitRepeatedMessageField(value: self.missionItems, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_UploadMissionRequest, rhs: Mavsdk_Rpc_MissionRaw_UploadMissionRequest) -> Bool {
if lhs.missionItems != rhs.missionItems {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_UploadMissionResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".UploadMissionResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_UploadMissionResponse, rhs: Mavsdk_Rpc_MissionRaw_UploadMissionResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_CancelMissionUploadRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CancelMissionUploadRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_CancelMissionUploadRequest, rhs: Mavsdk_Rpc_MissionRaw_CancelMissionUploadRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_CancelMissionUploadResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CancelMissionUploadResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_CancelMissionUploadResponse, rhs: Mavsdk_Rpc_MissionRaw_CancelMissionUploadResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_DownloadMissionRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".DownloadMissionRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_DownloadMissionRequest, rhs: Mavsdk_Rpc_MissionRaw_DownloadMissionRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_DownloadMissionResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".DownloadMissionResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
2: .standard(proto: "mission_items"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
case 2: try decoder.decodeRepeatedMessageField(value: &self.missionItems)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if !self.missionItems.isEmpty {
try visitor.visitRepeatedMessageField(value: self.missionItems, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_DownloadMissionResponse, rhs: Mavsdk_Rpc_MissionRaw_DownloadMissionResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.missionItems != rhs.missionItems {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_CancelMissionDownloadRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CancelMissionDownloadRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_CancelMissionDownloadRequest, rhs: Mavsdk_Rpc_MissionRaw_CancelMissionDownloadRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_CancelMissionDownloadResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".CancelMissionDownloadResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_CancelMissionDownloadResponse, rhs: Mavsdk_Rpc_MissionRaw_CancelMissionDownloadResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_StartMissionRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".StartMissionRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_StartMissionRequest, rhs: Mavsdk_Rpc_MissionRaw_StartMissionRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_StartMissionResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".StartMissionResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_StartMissionResponse, rhs: Mavsdk_Rpc_MissionRaw_StartMissionResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_PauseMissionRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PauseMissionRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_PauseMissionRequest, rhs: Mavsdk_Rpc_MissionRaw_PauseMissionRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_PauseMissionResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PauseMissionResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_PauseMissionResponse, rhs: Mavsdk_Rpc_MissionRaw_PauseMissionResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_ClearMissionRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".ClearMissionRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_ClearMissionRequest, rhs: Mavsdk_Rpc_MissionRaw_ClearMissionRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_ClearMissionResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".ClearMissionResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_ClearMissionResponse, rhs: Mavsdk_Rpc_MissionRaw_ClearMissionResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SetCurrentMissionItemRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "index"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self.index)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.index != 0 {
try visitor.visitSingularInt32Field(value: self.index, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemRequest, rhs: Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemRequest) -> Bool {
if lhs.index != rhs.index {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SetCurrentMissionItemResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_raw_result"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionRawResult)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionRawResult {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemResponse, rhs: Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemResponse) -> Bool {
if lhs._missionRawResult != rhs._missionRawResult {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_SubscribeMissionProgressRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SubscribeMissionProgressRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_SubscribeMissionProgressRequest, rhs: Mavsdk_Rpc_MissionRaw_SubscribeMissionProgressRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_MissionProgressResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MissionProgressResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_progress"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._missionProgress)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._missionProgress {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_MissionProgressResponse, rhs: Mavsdk_Rpc_MissionRaw_MissionProgressResponse) -> Bool {
if lhs._missionProgress != rhs._missionProgress {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_SubscribeMissionChangedRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SubscribeMissionChangedRequest"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_SubscribeMissionChangedRequest, rhs: Mavsdk_Rpc_MissionRaw_SubscribeMissionChangedRequest) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_MissionChangedResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MissionChangedResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "mission_changed"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularBoolField(value: &self.missionChanged)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.missionChanged != false {
try visitor.visitSingularBoolField(value: self.missionChanged, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_MissionChangedResponse, rhs: Mavsdk_Rpc_MissionRaw_MissionChangedResponse) -> Bool {
if lhs.missionChanged != rhs.missionChanged {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_MissionProgress: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MissionProgress"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "current"),
2: .same(proto: "total"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self.current)
case 2: try decoder.decodeSingularInt32Field(value: &self.total)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.current != 0 {
try visitor.visitSingularInt32Field(value: self.current, fieldNumber: 1)
}
if self.total != 0 {
try visitor.visitSingularInt32Field(value: self.total, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_MissionProgress, rhs: Mavsdk_Rpc_MissionRaw_MissionProgress) -> Bool {
if lhs.current != rhs.current {return false}
if lhs.total != rhs.total {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_MissionItem: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MissionItem"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "seq"),
2: .same(proto: "frame"),
3: .same(proto: "command"),
4: .same(proto: "current"),
5: .same(proto: "autocontinue"),
6: .same(proto: "param1"),
7: .same(proto: "param2"),
8: .same(proto: "param3"),
9: .same(proto: "param4"),
10: .same(proto: "x"),
11: .same(proto: "y"),
12: .same(proto: "z"),
13: .standard(proto: "mission_type"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularUInt32Field(value: &self.seq)
case 2: try decoder.decodeSingularUInt32Field(value: &self.frame)
case 3: try decoder.decodeSingularUInt32Field(value: &self.command)
case 4: try decoder.decodeSingularUInt32Field(value: &self.current)
case 5: try decoder.decodeSingularUInt32Field(value: &self.autocontinue)
case 6: try decoder.decodeSingularFloatField(value: &self.param1)
case 7: try decoder.decodeSingularFloatField(value: &self.param2)
case 8: try decoder.decodeSingularFloatField(value: &self.param3)
case 9: try decoder.decodeSingularFloatField(value: &self.param4)
case 10: try decoder.decodeSingularInt32Field(value: &self.x)
case 11: try decoder.decodeSingularInt32Field(value: &self.y)
case 12: try decoder.decodeSingularFloatField(value: &self.z)
case 13: try decoder.decodeSingularUInt32Field(value: &self.missionType)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.seq != 0 {
try visitor.visitSingularUInt32Field(value: self.seq, fieldNumber: 1)
}
if self.frame != 0 {
try visitor.visitSingularUInt32Field(value: self.frame, fieldNumber: 2)
}
if self.command != 0 {
try visitor.visitSingularUInt32Field(value: self.command, fieldNumber: 3)
}
if self.current != 0 {
try visitor.visitSingularUInt32Field(value: self.current, fieldNumber: 4)
}
if self.autocontinue != 0 {
try visitor.visitSingularUInt32Field(value: self.autocontinue, fieldNumber: 5)
}
if self.param1 != 0 {
try visitor.visitSingularFloatField(value: self.param1, fieldNumber: 6)
}
if self.param2 != 0 {
try visitor.visitSingularFloatField(value: self.param2, fieldNumber: 7)
}
if self.param3 != 0 {
try visitor.visitSingularFloatField(value: self.param3, fieldNumber: 8)
}
if self.param4 != 0 {
try visitor.visitSingularFloatField(value: self.param4, fieldNumber: 9)
}
if self.x != 0 {
try visitor.visitSingularInt32Field(value: self.x, fieldNumber: 10)
}
if self.y != 0 {
try visitor.visitSingularInt32Field(value: self.y, fieldNumber: 11)
}
if self.z != 0 {
try visitor.visitSingularFloatField(value: self.z, fieldNumber: 12)
}
if self.missionType != 0 {
try visitor.visitSingularUInt32Field(value: self.missionType, fieldNumber: 13)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_MissionItem, rhs: Mavsdk_Rpc_MissionRaw_MissionItem) -> Bool {
if lhs.seq != rhs.seq {return false}
if lhs.frame != rhs.frame {return false}
if lhs.command != rhs.command {return false}
if lhs.current != rhs.current {return false}
if lhs.autocontinue != rhs.autocontinue {return false}
if lhs.param1 != rhs.param1 {return false}
if lhs.param2 != rhs.param2 {return false}
if lhs.param3 != rhs.param3 {return false}
if lhs.param4 != rhs.param4 {return false}
if lhs.x != rhs.x {return false}
if lhs.y != rhs.y {return false}
if lhs.z != rhs.z {return false}
if lhs.missionType != rhs.missionType {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_MissionRawResult: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MissionRawResult"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "result"),
2: .standard(proto: "result_str"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularEnumField(value: &self.result)
case 2: try decoder.decodeSingularStringField(value: &self.resultStr)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.result != .unknown {
try visitor.visitSingularEnumField(value: self.result, fieldNumber: 1)
}
if !self.resultStr.isEmpty {
try visitor.visitSingularStringField(value: self.resultStr, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Mavsdk_Rpc_MissionRaw_MissionRawResult, rhs: Mavsdk_Rpc_MissionRaw_MissionRawResult) -> Bool {
if lhs.result != rhs.result {return false}
if lhs.resultStr != rhs.resultStr {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Mavsdk_Rpc_MissionRaw_MissionRawResult.Result: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "RESULT_UNKNOWN"),
1: .same(proto: "RESULT_SUCCESS"),
2: .same(proto: "RESULT_ERROR"),
3: .same(proto: "RESULT_TOO_MANY_MISSION_ITEMS"),
4: .same(proto: "RESULT_BUSY"),
5: .same(proto: "RESULT_TIMEOUT"),
6: .same(proto: "RESULT_INVALID_ARGUMENT"),
7: .same(proto: "RESULT_UNSUPPORTED"),
8: .same(proto: "RESULT_NO_MISSION_AVAILABLE"),
9: .same(proto: "RESULT_TRANSFER_CANCELLED"),
]
}
| 37.923778 | 165 | 0.747695 |
c1d4e27182c363723ef266f01b5dc070b8914816 | 3,942 | /*
`CategoriesViewController` is the left-hand side view in the browsing activity. It manages a list view of the groups and changes the data source of VideosViewController.swift .
*/
import UIKit
class CategoriesViewController: UITableViewController, VideoRepositoryListener {
// Represents a section in the table view with related collections of videos.
class Section {
let title: String?
let collections: [CollectionIdentifier]
init(title: String?, collections: [CollectionIdentifier]) {
self.title = title
self.collections = collections
}
}
// Initialized in didFinishLaunch, do not use in init
weak var videosViewController: VideosViewController!
var collectionIds: [CollectionIdentifier] = []
var sections: [Section] = []
func updateSections() {
let general = Section(title: nil, collections: [.AllVideos])
let groups = Section(
title: NSLocalizedString("Groups", comment: "Title of a category section"),
collections: videoRepository.groups.map { .Group($0.id) })
self.sections = [general, groups]
self.tableView.reloadData()
}
func videoRepositoryUpdated() {
updateSections()
}
override func viewWillAppear(animated: Bool) {
videoRepository.addListener(self)
}
override func viewWillDisappear(animated: Bool) {
videoRepository.removeListener(self)
}
// MARK: - table view
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sections[section].collections.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section].title
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath)
if let collectionId = self.sections[safe: indexPath.section]?.collections[safe: indexPath.item],
collection = videoRepository.retrieveCollectionByIdentifier(collectionId) {
cell.textLabel?.text = collection.title
cell.detailTextLabel?.text = collection.subtitle
cell.detailTextLabel?.numberOfLines = 2
cell.detailTextLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
} else {
cell.textLabel?.text = nil
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let maybeCollection = self.sections[safe: indexPath.section]?.collections[safe: indexPath.item]
if let collection = maybeCollection {
self.videosViewController.showCollection(collection)
self.splitViewController?.showDetailViewController(self.videosViewController.navigationController!, sender: nil)
}
}
// MARK: - buttons
@IBAction func editButtonPressed(sender: UIBarButtonItem) {
do {
let sharesNav = self.storyboard!.instantiateViewControllerWithIdentifier("SharesViewController") as! UINavigationController
let sharesController = sharesNav.topViewController as! SharesViewController
try sharesController.prepareForManageGroups()
self.presentViewController(sharesNav, animated: true) {
}
} catch {
self.showErrorModal(error, title: NSLocalizedString("error_on_create_group", comment: "Error title shown when creating a group was interrupted"))
}
}
}
| 36.5 | 176 | 0.66692 |
643376d4c29c9cc308f01760d6950d0047f035ae | 5,216 | /*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import ObjectiveC
// MARK: -
// MARK: (NSObject) Extension
public extension NSObject {
// MARK: -
// MARK: Vars
fileprivate struct dg_associatedKeys {
static var observersArray = "observers"
}
fileprivate var dg_observers: [[String : NSObject]] {
get {
if let observers = objc_getAssociatedObject(self, &dg_associatedKeys.observersArray) as? [[String : NSObject]] {
return observers
} else {
let observers = [[String : NSObject]]()
self.dg_observers = observers
return observers
}
} set {
objc_setAssociatedObject(self, &dg_associatedKeys.observersArray, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: -
// MARK: Methods
public func dg_addObserver(_ observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if dg_observers.index(where: { $0 == observerInfo }) == nil {
dg_observers.append(observerInfo)
addObserver(observer, forKeyPath: keyPath, options: .new, context: nil)
}
}
public func dg_removeObserver(_ observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if let index = dg_observers.index(where: { $0 == observerInfo}) {
dg_observers.remove(at: index)
removeObserver(observer, forKeyPath: keyPath)
}
}
}
// MARK: -
// MARK: (UIScrollView) Extension
public extension UIScrollView {
// MARK: - Vars
fileprivate struct dg_associatedKeys {
static var pullToRefreshView = "pullToRefreshView"
}
fileprivate var pullToRefreshView: DGElasticPullToRefreshView? {
get {
return objc_getAssociatedObject(self, &dg_associatedKeys.pullToRefreshView) as? DGElasticPullToRefreshView
}
set {
objc_setAssociatedObject(self, &dg_associatedKeys.pullToRefreshView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Methods (Public)
public func dg_addPullToRefreshWithActionHandler(_ actionHandler: @escaping () -> Void, loadingView: DGElasticPullToRefreshLoadingView?) {
isMultipleTouchEnabled = false
panGestureRecognizer.maximumNumberOfTouches = 1
let pullToRefreshView = DGElasticPullToRefreshView()
self.pullToRefreshView = pullToRefreshView
pullToRefreshView.actionHandler = actionHandler
pullToRefreshView.loadingView = loadingView
addSubview(pullToRefreshView)
pullToRefreshView.observing = true
}
public func dg_removePullToRefresh() {
pullToRefreshView?.disassociateDisplayLink()
pullToRefreshView?.observing = false
pullToRefreshView?.removeFromSuperview()
}
public func dg_setPullToRefreshBackgroundColor(_ color: UIColor) {
pullToRefreshView?.backgroundColor = color
}
public func dg_setPullToRefreshFillColor(_ color: UIColor) {
pullToRefreshView?.fillColor = color
}
public func dg_stopLoading() {
pullToRefreshView?.stopLoading()
}
}
// MARK: -
// MARK: (UIView) Extension
public extension UIView {
func dg_center(_ usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentation() {
// Position can be used as a center, because anchorPoint is (0.5, 0.5)
return presentationLayer.position
}
return center
}
}
// MARK: -
// MARK: (UIPanGestureRecognizer) Extension
public extension UIPanGestureRecognizer {
func dg_resign() {
isEnabled = false
isEnabled = true
}
}
// MARK: -
// MARK: (UIGestureRecognizerState) Extension
public extension UIGestureRecognizer.State {
func dg_isAnyOf(_ values: [UIGestureRecognizer.State]) -> Bool {
return values.contains(where: { $0 == self })
}
}
| 31.804878 | 148 | 0.682515 |
1a66fe07484f0fed718c22c8254a0251b8a322ee | 3,330 | /*
LibraryAPI.swift
This source file is part of the SDGSwift open source project.
https://sdggiesbrecht.github.io/SDGSwift
Copyright ©2018–2021 Jeremy David Giesbrecht and the SDGSwift project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
#if !PLATFORM_NOT_SUPPORTED_BY_SWIFT_SYNTAX
import Foundation
import SDGControlFlow
import SDGLogic
import SDGCollections
import SDGText
import SDGLocalization
import SwiftSyntax
import PackageModel
import SDGSwift
import SDGSwiftPackageManager
import SDGSwiftLocalizations
/// A library product of a package.
public final class LibraryAPI: _NonOverloadableAPIElement, SortableAPIElement,
_UniquelyDeclaredManifestAPIElement
{
// MARK: - Static Methods
internal static func reportForParsing(
module: StrictString
) -> UserFacing<StrictString, InterfaceLocalization> {
return UserFacing<StrictString, InterfaceLocalization>({ localization in
switch localization {
case .englishUnitedKingdom:
return "Parsing ‘\(module)’..."
case .englishUnitedStates, .englishCanada:
return "Parsing “\(module)”..."
case .deutschDeutschland:
return "„\(module)“ wird zerteilt ..."
}
})
}
// MARK: - Initialization
@available(macOS 10.15, *)
internal convenience init<Syntax>(
product: Product,
manifest: Syntax,
reportProgress: (String) -> Void
) throws where Syntax: SyntaxProtocol {
let search =
".library(".scalars
+ RepetitionPattern(ConditionalPattern({ $0 ∈ CharacterSet.whitespacesAndNewlines }))
+ "name: \u{22}\(product.name)\u{22}".scalars
let manifestDeclaration = manifest.smallestSubnode(containing: search)?.parent
self.init(
documentation: manifestDeclaration?.documentation ?? [], // @exempt(from: tests)
declaration: FunctionCallExprSyntax.normalizedLibraryDeclaration(name: product.name)
)
for module in product.targets where ¬module.name.hasPrefix("_") {
reportProgress(
String(LibraryAPI.reportForParsing(module: StrictString(module.name)).resolved())
)
children.append(.module(try ModuleAPI(module: module, manifest: manifest)))
}
}
internal init(
documentation: [SymbolDocumentation],
alreadyNormalizedDeclaration declaration: FunctionCallExprSyntax,
constraints: GenericWhereClauseSyntax?,
name: TokenSyntax,
children: [APIElement]
) {
self.declaration = declaration
self.name = name
_storage = APIElementStorage(documentation: documentation)
self.constraints = constraints
}
// MARK: - APIElementProtocol
public var _storage: _APIElementStorage
public func _summarySubentries() -> [String] {
return modules.map({ $0.name.source() })
}
// MARK: - DeclaredAPIElement
// #documentation(SDGSwiftSource.UniquelyDeclaredAPIElement.declaration)
/// The element’s declaration.
public let declaration: FunctionCallExprSyntax
// #documentation(SDGSwiftSource.UniquelyDeclaredAPIElement.name)
/// The element’s name.
public let name: TokenSyntax
}
#endif
| 29.732143 | 93 | 0.697297 |
8a5f40129f3719db01f558ba01c0f348b91b4f00 | 1,466 | //
// GoproSetRequestArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Request to set a GOPRO_COMMAND with a desired
public struct GoproSetRequest {
/// System ID
public let targetSystem: UInt8
/// Component ID
public let targetComponent: UInt8
/// Command ID
public let cmdId: GoproCommand
/// Value
public let value: [UInt8]
}
extension GoproSetRequest: Message {
public static let id = UInt8(218)
public static var typeName = "GOPRO_SET_REQUEST"
public static var typeDescription = "Request to set a GOPRO_COMMAND with a desired"
public static var fieldDefinitions: [FieldDefinition] = [("targetSystem", 0, "UInt8", 0, "System ID"), ("targetComponent", 1, "UInt8", 0, "Component ID"), ("cmdId", 2, "GoproCommand", 0, "Command ID"), ("value", 3, "[UInt8]", 4, "Value")]
public init(data: Data) throws {
targetSystem = try data.number(at: 0)
targetComponent = try data.number(at: 1)
cmdId = try data.enumeration(at: 2)
value = try data.array(at: 3, capacity: 4)
}
public func pack() throws -> Data {
var payload = Data(count: 7)
try payload.set(targetSystem, at: 0)
try payload.set(targetComponent, at: 1)
try payload.set(cmdId, at: 2)
try payload.set(value, at: 3, capacity: 4)
return payload
}
}
| 29.918367 | 242 | 0.690314 |
5d740b60c7e915cfc83664001b72ff3c384c4f60 | 387 | //
// BookwormApp.swift
// Bookworm
//
// Created by Mina Ashna on 03/12/2020.
//
import SwiftUI
@main
struct BookwormApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
| 18.428571 | 97 | 0.645995 |
760e7a97d0d0e9519eaf70c554379fdd67068c9e | 1,275 | //// Copyright 2018 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
extension CGFloat {
/// Builds a `CGFloat` from `true` or `false`.
///
/// * `true` produces a value of 1.0
/// * `false` produces a value of 0.0
///
/// - Parameter bool: The value you would like to convert.
///
/// - Note: This can be used to convert a `Bool` to a Core Graphics usable float value where the range of
/// animatable values are between 0.0 and 1.0, for example, `alpha`.
init(_ bool: Bool) {
self = bool ? 1.0 : 0.0
}
}
extension CGFloat {
/// Convert a degree value to its corresponding radian value.
var degreeToRadian: CGFloat {
return (self / 180.0) * .pi
}
}
| 30.357143 | 109 | 0.654902 |
d5bce64bbecc6efb661500e4efc01f1fe48033c5 | 299 | //
// Mesa3D.swift
//
//
// Created by Alsey Coleman Miller on 3/9/22.
//
// Mesa3D
public extension Configuration.ID {
static var mesa3d: Configuration.ID { "BR2_PACKAGE_MESA3D" }
static var mesa3d_gbm: Configuration.ID { "BR2_PACKAGE_MESA3D_GBM" }
}
| 19.933333 | 80 | 0.615385 |
d642285e745d19f8666d287b376dc56422ea0d44 | 1,457 | /*********************************************
*
* This code is under the MIT License (MIT)
*
* Copyright (c) 2016 AliSoftware
*
*********************************************/
import UIKit
// MARK: Protocol Definition
/// Make your UIViewController subclasses conform to this protocol when:
/// * they *are* Storyboard-based, and
/// * this ViewController is the initialViewController of your Storyboard
///
/// to be able to instantiate them from the Storyboard in a type-safe manner
public protocol StoryboardBased: class {
/// The UIStoryboard to use when we want to instantiate this ViewController
static var storyboard: UIStoryboard { get }
}
// MARK: Default Implementation
public extension StoryboardBased {
/// By default, use the storybaord with the same name as the class
static var storyboard: UIStoryboard {
return UIStoryboard(name: String(describing: self), bundle: Bundle(for: self))
}
}
// MARK: Support for instantiation from Storyboard
public extension StoryboardBased where Self: UIViewController {
/**
Create an instance of the ViewController from its associated Storyboard's initialViewController
- returns: instance of the conforming ViewController
*/
static func instantiate() -> Self {
guard let vc = storyboard.instantiateInitialViewController() as? Self else {
fatalError("The initialViewController of '\(storyboard)' is not of class '\(self)'")
}
return vc
}
}
| 27.490566 | 98 | 0.685655 |
48a7da740e4fa1e58090440bff235ef0315a5a6c | 4,434 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: request/storage/query_signed_put_url_request.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public struct QuerySignedPutUrlRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var contentType: ContentType = .profile
public var keyStr: String {
get {return _keyStr ?? String()}
set {_keyStr = newValue}
}
/// Returns true if `keyStr` has been explicitly set.
public var hasKeyStr: Bool {return self._keyStr != nil}
/// Clears the value of `keyStr`. Subsequent reads from it will return its default value.
public mutating func clearKeyStr() {self._keyStr = nil}
public var keyNum: Int64 {
get {return _keyNum ?? 0}
set {_keyNum = newValue}
}
/// Returns true if `keyNum` has been explicitly set.
public var hasKeyNum: Bool {return self._keyNum != nil}
/// Clears the value of `keyNum`. Subsequent reads from it will return its default value.
public mutating func clearKeyNum() {self._keyNum = nil}
public var contentLength: Int64 = 0
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _keyStr: String? = nil
fileprivate var _keyNum: Int64? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "im.turms.proto"
extension QuerySignedPutUrlRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".QuerySignedPutUrlRequest"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "content_type"),
2: .standard(proto: "key_str"),
3: .standard(proto: "key_num"),
4: .standard(proto: "content_length"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularEnumField(value: &self.contentType) }()
case 2: try { try decoder.decodeSingularStringField(value: &self._keyStr) }()
case 3: try { try decoder.decodeSingularInt64Field(value: &self._keyNum) }()
case 4: try { try decoder.decodeSingularInt64Field(value: &self.contentLength) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.contentType != .profile {
try visitor.visitSingularEnumField(value: self.contentType, fieldNumber: 1)
}
if let v = self._keyStr {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
}
if let v = self._keyNum {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 3)
}
if self.contentLength != 0 {
try visitor.visitSingularInt64Field(value: self.contentLength, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: QuerySignedPutUrlRequest, rhs: QuerySignedPutUrlRequest) -> Bool {
if lhs.contentType != rhs.contentType {return false}
if lhs._keyStr != rhs._keyStr {return false}
if lhs._keyNum != rhs._keyNum {return false}
if lhs.contentLength != rhs.contentLength {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 39.945946 | 136 | 0.729138 |
ed1ecb4b6c9dcb4008f47c3ed05a85fb232b7ecb | 568 | enum OutAction: Int {
case
// basic
event = 0,
// renderer
screenSize,
screenOrientation,
screenStatusBarHeight,
screenNavigationBarHeight,
navigatorLanguage,
navigatorOnline,
devicePixelRatio,
deviceIsPhone,
pointerPress,
pointerRelease,
pointerMove,
deviceKeyboardShow,
deviceKeyboardHide,
deviceKeyboardHeight,
keyPress,
keyHold,
keyInput,
keyRelease,
imageSize,
textSize,
fontLoad,
nativeItemWidth,
nativeItemHeight,
windowResize,
itemKeysFocus
}
| 17.212121 | 30 | 0.669014 |
7591179ba30fd58f6aa9f20cee98bf506d6407d1 | 182 | import UIKit
import Reusable
final class {{ model_name }}{{ property.name_title }}Cell: UITableViewCell, NibReusable {
@IBOutlet weak var {{ property.name }}Label: UILabel!
}
| 20.222222 | 89 | 0.725275 |
22806b890cb14e80bdb6df2b704e711ba7669879 | 15,201 | // Copyright © 2018 Stormbird PTE. LTD.
import Foundation
import UIKit
import BigInt
import PromiseKit
import RealmSwift
protocol TokenViewControllerDelegate: class, CanOpenURL {
func didTapSwap(forTransactionType transactionType: TransactionType, service: SwapTokenURLProviderType, inViewController viewController: TokenViewController)
func shouldOpen(url: URL, shouldSwitchServer: Bool, forTransactionType transactionType: TransactionType, inViewController viewController: TokenViewController)
func didTapSend(forTransactionType transactionType: TransactionType, inViewController viewController: TokenViewController)
func didTapReceive(forTransactionType transactionType: TransactionType, inViewController viewController: TokenViewController)
func didTap(transaction: TransactionInstance, inViewController viewController: TokenViewController)
func didTap(activity: Activity, inViewController viewController: TokenViewController)
func didTap(action: TokenInstanceAction, transactionType: TransactionType, viewController: TokenViewController)
}
class TokenViewController: UIViewController {
private let roundedBackground = RoundedBackground()
private var viewModel: TokenViewControllerViewModel
private var tokenHolder: TokenHolder?
private let tokenObject: TokenObject
private let session: WalletSession
private let tokensDataStore: TokensDataStore
private let assetDefinitionStore: AssetDefinitionStore
private let transactionType: TransactionType
private let analyticsCoordinator: AnalyticsCoordinator
private let buttonsBar = ButtonsBar(configuration: .combined(buttons: 2))
private lazy var tokenScriptFileStatusHandler = XMLHandler(token: tokenObject, assetDefinitionStore: assetDefinitionStore)
weak var delegate: TokenViewControllerDelegate?
private lazy var tokenInfoPageView: TokenInfoPageView = {
let view = TokenInfoPageView(server: session.server, token: tokenObject, transactionType: transactionType)
view.delegate = self
return view
}()
private var activitiesPageView: ActivitiesPageView
private lazy var alertsPageView = AlertsPageView()
private let activitiesService: ActivitiesServiceType
private var activitiesSubscriptionKey: Subscribable<ActivitiesViewModel>.SubscribableKey?
init(session: WalletSession, tokensDataStore: TokensDataStore, assetDefinition: AssetDefinitionStore, transactionType: TransactionType, analyticsCoordinator: AnalyticsCoordinator, token: TokenObject, viewModel: TokenViewControllerViewModel, activitiesService: ActivitiesServiceType) {
self.tokenObject = token
self.viewModel = viewModel
self.session = session
self.tokensDataStore = tokensDataStore
self.assetDefinitionStore = assetDefinition
self.transactionType = transactionType
self.analyticsCoordinator = analyticsCoordinator
self.activitiesService = activitiesService
activitiesPageView = ActivitiesPageView(viewModel: .init(activitiesViewModel: .init()), sessions: activitiesService.sessions)
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
activitiesPageView.delegate = self
roundedBackground.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(roundedBackground)
let containerView = PagesContainerView(pages: [tokenInfoPageView, activitiesPageView])
roundedBackground.addSubview(containerView)
let footerBar = ButtonsBarBackgroundView(buttonsBar: buttonsBar)
roundedBackground.addSubview(footerBar)
NSLayoutConstraint.activate([
footerBar.anchorsConstraint(to: view),
containerView.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor),
containerView.topAnchor.constraint(equalTo: roundedBackground.topAnchor),
containerView.bottomAnchor.constraint(equalTo: footerBar.topAnchor),
] + roundedBackground.createConstraintsWithContainer(view: view))
navigationItem.largeTitleDisplayMode = .never
activitiesSubscriptionKey = activitiesService.subscribableViewModel.subscribe { [weak activitiesPageView] viewModel in
guard let view = activitiesPageView else { return }
view.configure(viewModel: .init(activitiesViewModel: viewModel ?? .init(activities: [])))
}
}
required init?(coder aDecoder: NSCoder) {
return nil
}
deinit {
activitiesSubscriptionKey.flatMap { activitiesService.subscribableViewModel.unsubscribe($0) }
}
override func viewDidLoad() {
super.viewDidLoad()
configureBalanceViewModel()
configure(viewModel: viewModel)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hideNavigationBarTopSeparatorLine()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
showNavigationBarTopSeparatorLine()
}
func configure(viewModel: TokenViewControllerViewModel) {
self.viewModel = viewModel
view.backgroundColor = viewModel.backgroundColor
title = tokenObject.titleInPluralForm(withAssetDefinitionStore: assetDefinitionStore)
updateNavigationRightBarButtons(tokenScriptFileStatusHandler: tokenScriptFileStatusHandler)
var viewModel2 = tokenInfoPageView.viewModel
viewModel2.values = viewModel.chartHistory
tokenInfoPageView.configure(viewModel: viewModel2)
let actions = viewModel.actions
buttonsBar.configure(.combined(buttons: viewModel.actions.count))
buttonsBar.viewController = self
for (action, button) in zip(actions, buttonsBar.buttons) {
button.setTitle(action.name, for: .normal)
button.addTarget(self, action: #selector(actionButtonTapped), for: .touchUpInside)
switch session.account.type {
case .real:
if let tokenHolder = generateTokenHolder(), let selection = action.activeExcludingSelection(selectedTokenHolders: [tokenHolder], forWalletAddress: session.account.address, fungibleBalance: viewModel.fungibleBalance) {
if selection.denial == nil {
button.displayButton = false
}
}
case .watch:
button.isEnabled = false
}
}
}
private func updateNavigationRightBarButtons(tokenScriptFileStatusHandler xmlHandler: XMLHandler) {
let tokenScriptStatusPromise = xmlHandler.tokenScriptStatus
if tokenScriptStatusPromise.isPending {
let label: UIBarButtonItem = .init(title: R.string.localizable.tokenScriptVerifying(), style: .plain, target: nil, action: nil)
navigationItem.rightBarButtonItem = label
tokenScriptStatusPromise.done { [weak self] _ in
self?.updateNavigationRightBarButtons(tokenScriptFileStatusHandler: xmlHandler)
}.cauterize()
}
if let server = xmlHandler.server, let status = tokenScriptStatusPromise.value, server.matches(server: session.server) {
switch status {
case .type0NoTokenScript:
navigationItem.rightBarButtonItem = nil
case .type1GoodTokenScriptSignatureGoodOrOptional, .type2BadTokenScript:
let button = createTokenScriptFileStatusButton(withStatus: status, urlOpener: self)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}
} else {
navigationItem.rightBarButtonItem = nil
}
}
private func configureBalanceViewModel() {
switch transactionType {
case .nativeCryptocurrency:
session.balanceCoordinator.subscribableEthBalanceViewModel.subscribe { [weak self] viewModel in
guard let celf = self, let viewModel = viewModel else { return }
celf.tokenInfoPageView.viewModel.title = "\(viewModel.amountShort) \(viewModel.symbol)"
celf.tokenInfoPageView.viewModel.ticker = viewModel.ticker
celf.tokenInfoPageView.viewModel.currencyAmount = viewModel.currencyAmount
celf.configure(viewModel: celf.viewModel)
}
session.refresh(.ethBalance)
case .ERC20Token(let token, _, _):
let amount = EtherNumberFormatter.short.string(from: token.valueBigInt, decimals: token.decimals)
//Note that if we want to display the token name directly from token.name, we have to be careful that DAI token's name has trailing \0
tokenInfoPageView.viewModel.title = "\(amount) \(token.symbolInPluralForm(withAssetDefinitionStore: assetDefinitionStore))"
tokenInfoPageView.viewModel.ticker = session.balanceCoordinator.coinTicker(token.addressAndRPCServer)
tokenInfoPageView.viewModel.currencyAmount = session.balanceCoordinator.ethBalanceViewModel.currencyAmount
configure(viewModel: viewModel)
case .ERC875Token, .ERC875TokenOrder, .ERC721Token, .ERC721ForTicketToken, .ERC1155Token, .dapp, .tokenScript, .claimPaidErc875MagicLink:
break
}
}
@objc private func send() {
delegate?.didTapSend(forTransactionType: transactionType, inViewController: self)
}
@objc private func receive() {
delegate?.didTapReceive(forTransactionType: transactionType, inViewController: self)
}
@objc private func actionButtonTapped(sender: UIButton) {
let actions = viewModel.actions
for (action, button) in zip(actions, buttonsBar.buttons) where button == sender {
switch action.type {
case .swap(let service):
delegate?.didTapSwap(forTransactionType: transactionType, service: service, inViewController: self)
case .erc20Send:
send()
case .erc20Receive:
receive()
case .nftRedeem, .nftSell, .nonFungibleTransfer:
break
case .tokenScript:
if let tokenHolder = generateTokenHolder(), let selection = action.activeExcludingSelection(selectedTokenHolders: [tokenHolder], forWalletAddress: session.account.address, fungibleBalance: viewModel.fungibleBalance) {
if let denialMessage = selection.denial {
UIAlertController.alert(
message: denialMessage,
alertButtonTitles: [R.string.localizable.oK()],
alertButtonStyles: [.default],
viewController: self
)
} else {
//no-op shouldn't have reached here since the button should be disabled. So just do nothing to be safe
}
} else {
delegate?.didTap(action: action, transactionType: transactionType, viewController: self)
}
case .xDaiBridge:
delegate?.shouldOpen(url: Constants.xDaiBridge, shouldSwitchServer: true, forTransactionType: transactionType, inViewController: self)
case .buy(let service):
var tokenObject: TokenActionsServiceKey?
switch transactionType {
case .nativeCryptocurrency(let token, _, _):
tokenObject = TokenActionsServiceKey(tokenObject: token)
case .ERC20Token(let token, _, _):
tokenObject = TokenActionsServiceKey(tokenObject: token)
case .ERC875Token, .ERC875TokenOrder, .ERC721Token, .ERC721ForTicketToken, .ERC1155Token, .dapp, .tokenScript, .claimPaidErc875MagicLink:
tokenObject = .none
}
guard let token = tokenObject, let url = service.url(token: token) else { return }
logStartOnRamp(name: "Ramp")
delegate?.shouldOpen(url: url, shouldSwitchServer: false, forTransactionType: transactionType, inViewController: self)
}
break
}
}
private func generateTokenHolder() -> TokenHolder? {
//TODO is it correct to generate the TokenHolder instance once and never replace it? If not, we have to be very careful with subscriptions. Not re-subscribing in an infinite loop
guard tokenHolder == nil else { return tokenHolder }
//TODO id 1 for fungibles. Might come back to bite us?
let hardcodedTokenIdForFungibles = BigUInt(1)
guard let tokenObject = viewModel.token else { return nil }
let xmlHandler = XMLHandler(token: tokenObject, assetDefinitionStore: assetDefinitionStore)
//TODO Event support, if/when designed for fungibles
let values = xmlHandler.resolveAttributesBypassingCache(withTokenIdOrEvent: .tokenId(tokenId: hardcodedTokenIdForFungibles), server: self.session.server, account: self.session.account)
let subscribablesForAttributeValues = values.values
let allResolved = subscribablesForAttributeValues.allSatisfy { $0.subscribableValue?.value != nil }
if allResolved {
//no-op
} else {
for each in subscribablesForAttributeValues {
guard let subscribable = each.subscribableValue else { continue }
subscribable.subscribe { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.configure(viewModel: strongSelf.viewModel)
}
}
}
let token = Token(tokenIdOrEvent: .tokenId(tokenId: hardcodedTokenIdForFungibles), tokenType: tokenObject.type, index: 0, name: tokenObject.name, symbol: tokenObject.symbol, status: .available, values: values)
tokenHolder = TokenHolder(tokens: [token], contractAddress: tokenObject.contractAddress, hasAssetDefinition: true)
return tokenHolder
}
}
extension TokenViewController: CanOpenURL2 {
func open(url: URL) {
delegate?.didPressOpenWebPage(url, in: self)
}
}
extension TokenViewController: TokenInfoPageViewDelegate {
func didPressViewContractWebPage(forContract contract: AlphaWallet.Address, in tokenInfoPageView: TokenInfoPageView) {
delegate?.didPressViewContractWebPage(forContract: contract, server: session.server, in: self)
}
}
extension TokenViewController: ActivitiesPageViewDelegate {
func didTap(activity: Activity, in view: ActivitiesPageView) {
delegate?.didTap(activity: activity, inViewController: self)
}
func didTap(transaction: TransactionInstance, in view: ActivitiesPageView) {
delegate?.didTap(transaction: transaction, inViewController: self)
}
}
// MARK: Analytics
extension TokenViewController {
private func logStartOnRamp(name: String) {
analyticsCoordinator.log(navigation: Analytics.Navigation.onRamp, properties: [Analytics.Properties.name.rawValue: name])
}
}
| 48.410828 | 288 | 0.69752 |
1a150c40952227d0515659b9e8f79ab082410dbf | 1,733 | //
// User.swift
// Assignment3
//
// Created by Ngoc Do on 3/27/16.
// Copyright © 2016 com.appable. All rights reserved.
//
import UIKit
class User: NSObject {
var name:String?
var screenName:String?
var profileURL:NSURL?
var tagline:String?
var location:String?
var dict:NSDictionary?
init(dict:NSDictionary) {
self.dict = dict
name = dict["name"] as? String
screenName = dict["screen_name"] as? String
tagline = dict["description"] as? String
let url = dict["profile_image_url_https"] as? String
if let url = url{
profileURL = NSURL(string: url)
}
let loc = dict["location"] as?String
if let loc = loc{
location = loc
}
}
static var _currentUser:User?
class var currentUser:User?{
get{
if(_currentUser == nil){
let userData = userDefault.objectForKey("currentUser") as? NSData
if let userData = userData {
let dict:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(userData, options: []) as! NSDictionary
_currentUser = User(dict: dict)
}
}
return _currentUser
}
set(user){
_currentUser = user
if let user = user{
let data = try! NSJSONSerialization.dataWithJSONObject(user.dict!, options: [])
userDefault.setObject(data, forKey: "currentUser")
}else{
userDefault.setObject(nil, forKey: "currentUser")
}
userDefault.synchronize()
}
}
}
| 26.661538 | 127 | 0.535488 |
e954433936eb694746122a1807b42c8c51b86698 | 1,038 | //
// LinPhoneSwiftExampleTests.swift
// LinPhoneSwiftExampleTests
//
// Created by Alsey Coleman Miller on 7/24/17.
// Copyright © 2017 Alsey Coleman Miller. All rights reserved.
//
import XCTest
@testable import LinPhoneSwiftExample
class LinPhoneSwiftExampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 28.054054 | 111 | 0.654143 |
e5e373e88df8503cae18105153ee53a2b91e9eca | 3,232 | //
// TechViewController.swift
// TechStu
//
// Created by Anubhav Singh on 05/10/20.
// Copyright © 2020 Swify. All rights reserved.
//
import UIKit
struct ProductData {
let title:String?
let link:String?
let img:UIImage?
}
struct ServiceData {
let title:String?
let link:String?
let img:UIImage?
}
class TechViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var tableView: UITableView!
var pdData:[ProductData] = []
var serData:[ServiceData] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count = 0
if segmentController.selectedSegmentIndex == 0 {
count = pdData.count
}
else if segmentController.selectedSegmentIndex == 1{
count = serData.count
}
return count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TechTableViewCell
cell.selectionStyle = .none
if segmentController.selectedSegmentIndex == 0{
cell.companyTitle.text = pdData[indexPath.row].title
cell.hrfText.text = pdData[indexPath.row].link
cell.logoImage.image = pdData[indexPath.row].img
}
else if segmentController.selectedSegmentIndex == 1{
cell.companyTitle.text = serData[indexPath.row].title
cell.hrfText.text = serData[indexPath.row].link
cell.logoImage.image = serData[indexPath.row].img
}
return cell
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.contentView.backgroundColor = UIColor.orange
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { (_) in
cell!.contentView.backgroundColor = .clear
}
}
@IBOutlet weak var segmentController: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
pdData = [
ProductData(title: "Amazon", link:"https://www.amazon.jobs/en/" , img: #imageLiteral(resourceName: "dog1")),
ProductData(title: "anu", link: "this", img: #imageLiteral(resourceName: "icons8-home-52")),
ProductData(title: "singh", link: "do", img: #imageLiteral(resourceName: "dog2"))
]
serData = [
ServiceData(title: "ser", link: "sur", img: #imageLiteral(resourceName: "dog1")),
ServiceData(title: "given", link: "what", img: #imageLiteral(resourceName: "gsoc")),
ServiceData(title: "yes ", link: "do", img: #imageLiteral(resourceName: "icons8-gear-30 blue"))
]
// segmentController.st
}
@IBAction func Segment(_ sender: UISegmentedControl) {
self.tableView.reloadData()
}
}
| 31.378641 | 116 | 0.624072 |
333b169aa80e0c5f90fba3e0e3203e773de554ce | 2,803 | //
// WaintingRoomControls.swift
// videoLlamada
//
// Created by Gio Valdes on 15/03/21.
//
import UIKit
import DateScrollPicker
extension WaintingRoom: ControlsDelegate, ZoomDelegate
{
func gotoWaintingRoom()
{
print("goto waintig room")
self.dismiss(animated: true, completion: nil)
// presentingViewController?.dismiss(animated: true, completion: {
// let waintingRoomController = ViewController()
// waintingRoomController.modalTransitionStyle = .crossDissolve
// self.present(waintingRoomController, animated: true, completion: nil)
// })
}
func gotoCall()
{
print("goto room")
let zoomController = ZoomController()
zoomController.modalPresentationStyle = .fullScreen
zoomController.modalTransitionStyle = .crossDissolve
zoomController.delegate = self
zoomController.meetingNo = Manager.instance.selectedMeeting?.meetingNo ?? ""
zoomController.pass = Manager.instance.selectedMeeting?.pass ?? ""
zoomController.kSDKUserName = Manager.instance.userName
self.present(zoomController, animated: true, completion: nil)
}
@objc func goWeekLess(_ gesture:UITapGestureRecognizer)
{
scrollDay = scrollDay?.addDays(-7)
dateScrollPicker.scrollToDate(date: scrollDay ?? Date())
initWeek = scrollDay?.addDays(-3) ?? Date()
finishWeek = scrollDay?.addDays(3) ?? Date()
let finalStr = formatter.string(from: initWeek ) + " - " + formatter.string(from: finishWeek )
labelWeeks.text = finalStr
}
@objc func goWeekMore(_ gesture:UITapGestureRecognizer)
{
scrollDay = scrollDay?.addDays(7)
dateScrollPicker.scrollToDate(date: scrollDay ?? Date())
initWeek = scrollDay?.addDays(-3) ?? Date()
finishWeek = scrollDay?.addDays(3) ?? Date()
let finalStr = formatter.string(from: initWeek ) + " - " + formatter.string(from: finishWeek )
labelWeeks.text = finalStr
}
public func dateScrollPicker(_ dateScrollPicker: DateScrollPicker, didSelectDate date: Date)
{
Manager.instance.meetingArr.removeAll()
Manager.instance.selectedDates.removeAll()
// let firebaseData = MeetingsFirebase()
// firebaseData.getMeeting(userId: 0, date: date, completion: {(completed, arr) in
// if(completed)
// {
// Manager.instance.meetingArr = arr
// self.calendarList.reloadData()
// }else{
// self.calendarList.reloadData()
// }
// })
}
}
| 29.505263 | 103 | 0.602212 |
fb6493068966248e1804169340fd305877b26777 | 3,565 | //
// VimeoSessionManager.swift
// VimeoUpload
//
// Created by Alfred Hanssen on 10/17/15.
// Copyright © 2015 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import AFNetworking
/** `VimeoSessionManager` handles networking and serialization for raw HTTP requests. It is a direct subclass of `AFHTTPSessionManager` and it's designed to be used internally by `VimeoClient`. For the majority of purposes, it would be better to use `VimeoClient` and a `Request` object to better encapsulate this logic, since the latter provides richer functionality overall.
*/
final public class VimeoSessionManager: AFHTTPSessionManager
{
// MARK: Initialization
/**
Creates a new session manager
- parameter baseUrl: The base URL for the HTTP client
- parameter sessionConfiguration: Object describing the URL session policies for this session manager
- parameter requestSerializer: Serializer to use for all requests handled by this session manager
- returns: an initialized `VimeoSessionManager`
*/
required public init(baseUrl: URL, sessionConfiguration: URLSessionConfiguration, requestSerializer: VimeoRequestSerializer)
{
super.init(baseURL: baseUrl, sessionConfiguration: sessionConfiguration)
self.requestSerializer = requestSerializer
self.responseSerializer = VimeoResponseSerializer()
}
required public init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
// MARK: - Authentication
/**
Called when authentication completes successfully to update the session manager with the new access token
- parameter account: the new account
*/
func clientDidAuthenticate(with account: VIMAccount)
{
guard let requestSerializer = self.requestSerializer as? VimeoRequestSerializer
else
{
return
}
let accessToken = account.accessToken
requestSerializer.accessTokenProvider = {
return accessToken
}
}
/**
Called when a client is logged out and the current account should be cleared from the session manager
*/
func clientDidClearAccount()
{
guard let requestSerializer = self.requestSerializer as? VimeoRequestSerializer
else
{
return
}
requestSerializer.accessTokenProvider = nil
}
}
| 37.925532 | 378 | 0.707714 |
5bf8c19dd35858ca8f9ff765062d43d656645a05 | 1,016 | //
// CustomTableHeaderCell.swift
// TestCellSwiftVersion
//
// Created by tomfriwel on 20/04/2017.
// Copyright © 2017 tomfriwel. All rights reserved.
//
import Cocoa
class CustomTableHeaderCell: NSTableHeaderCell {
override init(textCell: String) {
super.init(textCell: textCell)
self.font = NSFont.boldSystemFont(ofSize: 28) // Or set NSFont to your choice
self.textColor = NSColor.red
self.backgroundColor = NSColor.red
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
// skip super.drawWithFrame(), since that is what draws borders
self.drawInterior(withFrame: cellFrame, in: controlView)
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
let titleRect = self.titleRect(forBounds: cellFrame)
self.attributedStringValue.draw(in: titleRect)
}
}
| 30.787879 | 85 | 0.687008 |
0117ba1d652d24617adfe7f0844aadf9e8bd6f0f | 3,876 | import ReactiveSwift
import ReactiveCocoa
import UIKit
import Quick
import Nimble
import enum Result.NoError
private final class UIScrollViewDelegateForZooming: NSObject, UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scrollView.subviews.first!
}
}
class UIScrollViewSpec: QuickSpec {
override func spec() {
var scrollView: UIScrollView!
weak var _scrollView: UIScrollView?
beforeEach {
scrollView = UIScrollView(frame: .zero)
_scrollView = scrollView
}
afterEach {
scrollView = nil
expect(_scrollView).to(beNil())
}
it("should accept changes from bindings to its content inset value") {
scrollView.contentInset = .zero
let (pipeSignal, observer) = Signal<UIEdgeInsets, NoError>.pipe()
scrollView.reactive.contentInset <~ SignalProducer(pipeSignal)
observer.send(value: UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4))
expect(scrollView.contentInset) == UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)
observer.send(value: .zero)
expect(scrollView.contentInset) == UIEdgeInsets.zero
}
it("should accept changes from bindings to its scroll indicator insets value") {
scrollView.scrollIndicatorInsets = .zero
let (pipeSignal, observer) = Signal<UIEdgeInsets, NoError>.pipe()
scrollView.reactive.scrollIndicatorInsets <~ SignalProducer(pipeSignal)
observer.send(value: UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4))
expect(scrollView.scrollIndicatorInsets) == UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)
observer.send(value: .zero)
expect(scrollView.scrollIndicatorInsets) == UIEdgeInsets.zero
}
it("should accept changes from bindings to its scroll enabled state") {
scrollView.isScrollEnabled = true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
scrollView.reactive.isScrollEnabled <~ SignalProducer(pipeSignal)
observer.send(value: true)
expect(scrollView.isScrollEnabled) == true
observer.send(value: false)
expect(scrollView.isScrollEnabled) == false
}
it("should accept changes from bindings to its zoom scale value") {
let contentView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
scrollView.addSubview(contentView)
let delegate = UIScrollViewDelegateForZooming()
scrollView.delegate = delegate
scrollView.minimumZoomScale = 1
scrollView.maximumZoomScale = 5
scrollView.zoomScale = 1
let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe()
scrollView.reactive.zoomScale <~ SignalProducer(pipeSignal)
observer.send(value: 3)
expect(scrollView.zoomScale) == 3
observer.send(value: 1)
expect(scrollView.zoomScale) == 1
}
it("should accept changes from bindings to its minimum zoom scale value") {
scrollView.minimumZoomScale = 0
let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe()
scrollView.reactive.minimumZoomScale <~ SignalProducer(pipeSignal)
observer.send(value: 42)
expect(scrollView.minimumZoomScale) == 42
observer.send(value: 0)
expect(scrollView.minimumZoomScale) == 0
}
it("should accept changes from bindings to its maximum zoom scale value") {
scrollView.maximumZoomScale = 0
let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe()
scrollView.reactive.maximumZoomScale <~ SignalProducer(pipeSignal)
observer.send(value: 42)
expect(scrollView.maximumZoomScale) == 42
observer.send(value: 0)
expect(scrollView.maximumZoomScale) == 0
}
it("should accept changes from bindings to its scrolls to top state") {
scrollView.scrollsToTop = true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
scrollView.reactive.scrollsToTop <~ SignalProducer(pipeSignal)
observer.send(value: true)
expect(scrollView.scrollsToTop) == true
observer.send(value: false)
expect(scrollView.scrollsToTop) == false
}
}
}
| 31.008 | 97 | 0.736842 |
cc285206ce3115f06b7075c40b057a56656c4854 | 306 | //
// Constant.swift
// VirusTracker
//
// Created by Arpit Lokwani on 21/03/20.
// Copyright © 2020 SendBird. All rights reserved.
//
import Foundation
struct Constant{
static let BaseURL = "http://idea.bizofit.com/index.php/"
static let BaseTestURL = "http://ideatest.bizofit.com/index.php/"
}
| 20.4 | 69 | 0.699346 |
cc5a8ea676c85924b9f9e69cef467596e8f3f46b | 5,879 | //
// Collation.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Collation defines how strings are compared and is used when creating a COLLATE expression.
/// The COLLATE expression can be used in the WHERE clause when comparing two strings or in the
/// ORDER BY clause when specifying how the order of the query results.
public protocol CollationProtocol {
}
/// Collation factory. CouchbaseLite provides two types of the Collation,
/// ASCII and Unicode. Without specifying the COLLATE expression. Couchbase Lite
/// will use the ASCII with case sensitive collation by default.
public final class Collation {
/// Creates an ASCII collation that will compare two strings by using binary comparison.
///
/// - Returns: The ASCII collation.
static public func ascii() -> ASCII {
return ASCII()
}
/// Creates a Unicode collation that will compare two strings by using Unicode Collation
/// Algorithm. If the locale is not specified, the collation is Unicode-aware but
/// not localized; for example, accented Roman letters sort right after the base letter
/// (This is implemented by using the "en_US" locale.).
///
/// - Returns: The Unicode collation.
static public func unicode() -> Unicode {
return Unicode()
}
/// ASCII collation compares two strings by using binary comparison.
public final class ASCII: CollationProtocol {
/// Specifies whether the collation is case-sensitive or not. Case-insensitive
/// collation will treat ASCII uppercase and lowercase letters as equivalent.
///
/// - Parameter ignoreCase: True for case-insenstivie; false for case-senstive.
/// - Returns: The ASCII Collation object.
public func ignoreCase(_ ignoreCase: Bool) -> Self {
self.ignoreCase = ignoreCase
return self
}
// MARK: Internal
var ignoreCase = false
func toImpl() -> CBLQueryCollation {
return CBLQueryCollation.ascii(withIgnoreCase: ignoreCase)
}
}
/// [Unicode Collation](http://userguide.icu-project.org/collation) that will compare two strings
/// by using Unicode collation algorithm. If the locale is not specified, the collation is
/// Unicode-aware but not localized; for example, accented Roman letters sort right after
/// the base letter (This is implemented by using the "en_US" locale).
public final class Unicode: CollationProtocol {
/// Specifies whether the collation is case-insenstive or not. Case-insensitive
/// collation will treat ASCII uppercase and lowercase letters as equivalent.
///
/// - Parameter ignoreCase: True for case-insenstivie; false for case-senstive.
/// - Returns: The Unicode Collation object.
public func ignoreCase(_ ignoreCase: Bool) -> Self {
self.ignoreCase = ignoreCase
return self
}
/// Specifies whether the collation ignore the accents or diacritics when
/// comparing the strings or not.
///
/// - Parameter ignoreAccents: True for accent-insenstivie; false for accent-senstive.
/// - Returns: The Unicode Collation object.
public func ignoreAccents(_ ignoreAccents: Bool) -> Self {
self.ignoreAccents = ignoreAccents
return self
}
/// Specifies the locale to allow the collation to compare strings appropriately base on
/// the locale.
///
/// - Parameter locale: The locale code which is an
/// [ISO-639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
/// language code plus, optionally, an underscore and an
/// [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)
/// country code: "en", "en_US", "fr_CA", etc.
/// Specifing the locale will allow the collation to compare strings
/// appropriately base on the locale. If not specified, the 'en_US'
/// will be used by default.
/// - Returns: The Unicode Collation object.
public func locale(_ locale: String?) -> Self {
self.locale = locale
return self
}
// MARK: Internal
var ignoreCase = false
var ignoreAccents = false
var locale: String?
func toImpl() -> CBLQueryCollation {
return CBLQueryCollation.unicode(withLocale: locale,
ignoreCase: ignoreCase,
ignoreAccents: ignoreAccents)
}
}
}
extension CollationProtocol {
func toImpl() -> CBLQueryCollation {
if let o = self as? Collation.ASCII {
return o.toImpl()
}
if let o = self as? Collation.Unicode {
return o.toImpl()
}
fatalError("Unsupported collation.");
}
}
| 37.685897 | 101 | 0.610818 |
e5cfadb6ea4c3ac20b4b8bf314b3cc08504fdd83 | 254 | // RUN: not %target-swift-frontend %s -parse
// 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<{{{let a{struct S<f:f.c}}}var b(}
| 31.75 | 87 | 0.724409 |
7620793dc2f626ae5ba0707f30a138d5e1e4b7bf | 2,739 | // LogTextView.swift
// Copyright (c) 2019 Jerome Hsieh. All rights reserved.
// Created by Jerome Hsieh.
/// NOTE: Work with CGFloatExtension.swift file.
import UIKit
public class LogTextView: UITextView {
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
layer.zPosition = .greatestFiniteMagnitude
setupStyle()
}
required public init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func hitTest(_: CGPoint, with _: UIEvent?) -> UIView? {
return nil
}
private func setupStyle() {
backgroundColor = .white
alpha = 0.7
textColor = .black
}
}
extension UIView {
public typealias Constraint = (_ subview: UIView, _ superview: UIView) -> NSLayoutConstraint
public func addSubview(_ subview: UIView, constraints: [Constraint]) {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
addConstraints(constraints.map { $0(subview, self) })
}
public func insertSubview(_ subview: UIView, at: Int, constraints: [Constraint]) {
insertSubview(subview, at: at)
subview.translatesAutoresizingMaskIntoConstraints = false
addConstraints(constraints.map { $0(subview, self) })
}
/// ex: subview.topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor, constant: constant)
/// - Parameter subviewKeyPath: subview's KeyPath
/// - Parameter superviewKeyPath: superview's KeyPath
/// - Parameter constant: anchors distance constant
public static func anchorConstraintEqual<LayoutAnchor, Axis>(from subviewKeyPath: KeyPath<UIView, LayoutAnchor>,
to superviewKeyPath: KeyPath<UIView, LayoutAnchor>,
constant: CGFloat = 0.0) -> Constraint where LayoutAnchor: NSLayoutAnchor<Axis> {
return { subview, superview in
subview[keyPath: subviewKeyPath]
.constraint(equalTo: superview[keyPath: superviewKeyPath],
constant: constant)
}
}
/// ex: subview.topAnchor.constraint(equalTo: superview.topAnchor, constant: constant)
/// - Parameter viewKeyPath: subview's and superview's KeyPath
/// - Parameter constant: anchors distance constant
public static func anchorConstraintEqual<LayoutAnchor, Axis>(with viewKeyPath: KeyPath<UIView, LayoutAnchor>,
constant: CGFloat = 0.0) -> Constraint where LayoutAnchor: NSLayoutAnchor<Axis> {
return anchorConstraintEqual(from: viewKeyPath,
to: viewKeyPath,
constant: constant)
}
}
| 39.695652 | 137 | 0.672508 |
cc10830385a4fa4d79ca01f43a95f59bc84efdd8 | 7,940 | //
// TopRatedMovieTableViewController.swift
// Flicks
//
// Created by Weijie Chen on 4/2/17.
// Copyright © 2017 Weijie Chen. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
class TopRatedMovieTableViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
var topratedmovies : [NSDictionary] = []
let refreshControl = UIRefreshControl()
@IBOutlet weak var networkerrorview: UIView!
@IBOutlet weak var table_view: UITableView!
@IBOutlet weak var networkerrortext: UILabel!
let baseUrl : String = "http://image.tmdb.org/t/p/"
let posterSmall : String = "w92"
let posterLarge : String = "w500"
override func viewDidLoad() {
super.viewDidLoad()
table_view.dataSource = self
table_view.delegate = self
table_view.rowHeight = 100
initializeTopMovies()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func initializeTopMovies(){
refreshControl.addTarget(self, action: #selector(refreshTopRated), for: UIControlEvents.valueChanged)
table_view.insertSubview(refreshControl, at: 0)
self.networkerrorview.isHidden = true
loadTopRated()
}
func refreshTopRated(){
loadTopRated()
}
func loadTopRated(){
let url = URL(string: "https://api.themoviedb.org/3/movie/top_rated?api_key=2682b3b6bb9c066686bac9b3362c271d")
let request = URLRequest(url: url!)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
//Display HUD right before the request is made
MBProgressHUD.showAdded(to: self.view, animated: true)
let task : URLSessionDataTask = session.dataTask(
with: request as URLRequest,
completionHandler: { (data, response, error) in
if let data = data {
if let responseDictionary = try! JSONSerialization.jsonObject(
with: data, options:[]) as? NSDictionary {
//print("responseDictionary: \(responseDictionary)")
// Recall there are two fields in the response dictionary, 'meta' and 'response'.
// This is how we get the 'response' field
let responseFieldDictionary = responseDictionary["results"] as! [NSDictionary]
self.topratedmovies.append(contentsOf: responseFieldDictionary)
//self.refreshControl.endRefreshing()
// This is where you will store the returned array of posts in your posts property
// self.feeds = responseFieldDictionary["posts"] as! [NSDictionary]
self.table_view.reloadData()
}
}
else{
self.networkerrorview.isHidden = false
self.table_view.addSubview(self.networkerrorview)
self.table_view.bringSubview(toFront: self.networkerrorview)
}
self.refreshControl.endRefreshing()
//Hide HUD once the network request come back
MBProgressHUD.hide(for:self.view,animated:true)
});
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return topratedmovies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TopRatedCell") as! TopRatedMovieTableViewCell
cell.image_view.frame = CGRect(x: 0, y: 0, width: Int(tableView.frame.width * 0.3), height: Int(tableView.rowHeight * 0.9))
let post = topratedmovies[indexPath.row]
if let posterPath = post.value(forKey: "poster_path") as? String{
let posterUrl = URL(string: (self.baseUrl + self.posterSmall + posterPath))
cell.posterPath = posterPath
cell.image_view.setImageWith(posterUrl!)
cell.image_view.frame = CGRect(x: 5, y: 5, width: 80, height: 90)
}else{
}
if let movietitle = post.value(forKey: "title") as? String{
cell.movie_title.text = movietitle
}else{
}
if let movieoverview = post.value(forKey: "overview") as? String{
cell.movie_overview.text = movieoverview
//cell.movie_overview.sizeToFit()
}else{
}
if let movieid = post.value(forKey: "id") as? Int{
cell.movieId = movieid
}else{
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationViewController = segue.destination as! MovieDetailViewController
let posterUrl = URL(string: (self.baseUrl + self.posterLarge + (sender! as! TopRatedMovieTableViewCell).posterPath!))
let posterData = try? Data(contentsOf: posterUrl!)
destinationViewController.detailImage = UIImage(data: posterData!)
destinationViewController.movie_id = (sender! as! TopRatedMovieTableViewCell).movieId
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.276995 | 136 | 0.614987 |
879d0b8526a20703edf2c18c65859c92b6f28fcf | 7,625 | //
// MapViewController.swift
// Virtual Tourist
//
// Created by Sebas on 3/1/16.
// Copyright © 2016 Sebas Mas. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class MapViewController: BaseViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var editButton: UIBarButtonItem!
@IBOutlet weak var messageLabel: UILabel!
let deletePinsMessage = "Tap on pin to delete"
let addPinsMessage = "Long press to add new pin"
var selectedPin:Pin!
var lastAddedPin:Pin? = nil
var isEditMode = false
var mapViewRegion:MapRegion?
override func viewDidLoad() {
super.viewDidLoad()
// Add a LongPressGestureRecognizer to add a new Pin
let longPress = UILongPressGestureRecognizer(target: self, action: "addPin:")
longPress.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPress)
loadMapRegion()
mapView.addAnnotations(fetchAllPins())
setUpAddPinsMessage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Core Data implementation
func fetchAllPins() -> [Pin] {
let fetchRequest = NSFetchRequest(entityName: "Pin")
var pins:[Pin] = []
do {
let results = try sharedContext.executeFetchRequest(fetchRequest)
pins = results as! [Pin]
} catch let error as NSError {
showAlert("Ooops", message: "Something went wrong when trying to load existing data")
print("An error occured accessing managed object context \(error.localizedDescription)")
}
return pins
}
// MARK: - Adding and removing Pins
func addPin(gestureRecognizer: UIGestureRecognizer) {
if isEditMode {
return
}
let locationInMap = gestureRecognizer.locationInView(mapView)
let coord:CLLocationCoordinate2D = mapView.convertPoint(locationInMap, toCoordinateFromView: mapView)
switch gestureRecognizer.state {
case UIGestureRecognizerState.Began:
lastAddedPin = Pin(coordinate: coord, context: sharedContext)
mapView.addAnnotation(lastAddedPin!)
case UIGestureRecognizerState.Changed:
lastAddedPin!.willChangeValueForKey("coordinate")
lastAddedPin!.coordinate = coord
lastAddedPin!.didChangeValueForKey("coordinate")
case UIGestureRecognizerState.Ended:
getPhotosForPin(lastAddedPin!) { (success, errorString) in
self.lastAddedPin!.isDownloading = false
if success == false {
self.showAlert("sorry, an error occurred", message: errorString!)
return
}
}
CoreDataStackManager.sharedInstance().saveContext()
default:
return
}
}
func deletePin(pin: Pin) {
mapView.removeAnnotation(pin)
sharedContext.deleteObject(pin)
CoreDataStackManager.sharedInstance().saveContext()
}
func setUpAddPinsMessage(){
messageLabel.text = addPinsMessage
messageLabel.backgroundColor = UIColor.darkGrayColor()
}
func setUpDeletePinsMessage(){
messageLabel.text = deletePinsMessage
messageLabel.backgroundColor = UIColor.redColor()
}
@IBAction func toggleEditMode(sender: AnyObject) {
if isEditMode {
isEditMode = false
editButton.title = "Edit"
setUpAddPinsMessage()
} else {
isEditMode = true
editButton.title = "Done"
setUpDeletePinsMessage()
}
}
// MARK - MKMapViewDelegate methods
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? Pin {
let identifier = "Pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = false
view.animatesDrop = true
view.draggable = false
}
return view
}
return nil
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
print("Pin selected")
let annotation = view.annotation as! Pin
selectedPin = annotation
if !isEditMode {
performSegueWithIdentifier("locationDetail", sender: self)
} else {
let alert = UIAlertController(title: "Delete Pin", message: "Do you want to remove this pin?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil))
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction) in
self.selectedPin = nil
self.deletePin(annotation)
}))
presentViewController(alert, animated: true, completion: nil)
}
}
// We need to detect any changes in region to store them
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
print("Saving Map Coordinates")
saveMapRegion()
}
// MARK - save and load map region
struct mapKeys {
static let centerLatitude = "CenterLatitudeKey"
static let centerLongitude = "CenterLongitude"
static let spanLatitude = "SpanLatitudeDeltaKey"
static let spanLongitude = "SpanLongitudeDeltaKey"
}
func saveMapRegion() {
if mapViewRegion == nil {
mapViewRegion = MapRegion(region: mapView.region, context: sharedContext)
} else {
mapViewRegion!.region = mapView.region
}
CoreDataStackManager.sharedInstance().saveContext()
}
func loadMapRegion() {
let fetchRequest = NSFetchRequest(entityName: "MapRegion")
var regions:[MapRegion] = []
do {
let results = try sharedContext.executeFetchRequest(fetchRequest)
regions = results as! [MapRegion]
} catch let error as NSError {
// only map region failed, so failing silent
print("An error occured accessing managed object context \(error.localizedDescription)")
}
if regions.count > 0 {
mapViewRegion = regions[0]
mapView.region = mapViewRegion!.region
} else {
mapViewRegion = MapRegion(region: mapView.region, context: sharedContext)
}
}
// 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?) {
if segue.identifier == "locationDetail" {
mapView.deselectAnnotation(selectedPin, animated: false)
let controller = segue.destinationViewController as! LocationDetailViewController
controller.pin = selectedPin
}
}
}
| 35.300926 | 130 | 0.617049 |
918cff6ff4924be528f1a943bd10527ed5ddd8ea | 2,753 | //
// UrlEntity.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** Represent the portion of text recognized as a URL, and its start and end position within the text. */
public struct UrlEntity: Codable {
/** Index (zero-based) at which position this entity starts. The index is inclusive. */
public var start: Int
/** Index (zero-based) at which position this entity ends. The index is exclusive. */
public var end: Int
/** A validly formatted URL. */
public var url: String
/** A validly formatted URL. */
public var expandedUrl: String?
/** The URL as displayed in the Twitter client. */
public var displayUrl: String?
/** Fully resolved url */
public var unwoundUrl: String?
/** HTTP Status Code. */
public var status: Int?
/** Title of the page the URL points to. */
public var title: String?
/** Description of the URL landing page. */
public var description: String?
public var images: [URLImage]?
public init(start: Int, end: Int, url: String, expandedUrl: String? = nil, displayUrl: String? = nil, unwoundUrl: String? = nil, status: Int? = nil, title: String? = nil, description: String? = nil, images: [URLImage]? = nil) {
self.start = start
self.end = end
self.url = url
self.expandedUrl = expandedUrl
self.displayUrl = displayUrl
self.unwoundUrl = unwoundUrl
self.status = status
self.title = title
self.description = description
self.images = images
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case start
case end
case url
case expandedUrl = "expanded_url"
case displayUrl = "display_url"
case unwoundUrl = "unwound_url"
case status
case title
case description
case images
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(start, forKey: .start)
try container.encode(end, forKey: .end)
try container.encode(url, forKey: .url)
try container.encodeIfPresent(expandedUrl, forKey: .expandedUrl)
try container.encodeIfPresent(displayUrl, forKey: .displayUrl)
try container.encodeIfPresent(unwoundUrl, forKey: .unwoundUrl)
try container.encodeIfPresent(status, forKey: .status)
try container.encodeIfPresent(title, forKey: .title)
try container.encodeIfPresent(description, forKey: .description)
try container.encodeIfPresent(images, forKey: .images)
}
}
| 34.848101 | 231 | 0.658191 |
f939f08d71531ce8f36310ac68e4d1470b0a87ae | 1,962 | //
// FiatUnit.swift
// BidWallet
//
// Created by Marcos Rodriguez on 11/20/20.
// Copyright © 2020 BidWallet. All rights reserved.
//
import Foundation
typealias FiatUnits = [FiatUnit]
struct FiatUnit: Codable {
let endPointKey: String
let symbol: String
let locale: String
let dataSource: String?
let rateKey: String?
var rateURL: URL? {
if let dataSource = dataSource {
return URL(string: "\(dataSource)/\(endPointKey)")
} else {
return URL(string:"https://api.coindesk.com/v1/bpi/currentprice/\(endPointKey).json");
}
}
func currentRate(json: Dictionary<String, Any>) -> WidgetDataStore? {
if dataSource == nil {
guard let bpi = json["bpi"] as? Dictionary<String, Any>, let preferredCurrency = bpi[endPointKey] as? Dictionary<String, Any>, let rateString = preferredCurrency["rate"] as? String, let rateDouble = preferredCurrency["rate_float"] as? Double, let time = json["time"] as? Dictionary<String, Any>, let lastUpdatedString = time["updatedISO"] as? String else {
return nil
}
return WidgetDataStore(rate: rateString, lastUpdate: lastUpdatedString, rateDouble: rateDouble)
} else {
guard let rateKey = rateKey, let rateDict = json[rateKey] as? [String: Any], let rateDouble = rateDict["price"] as? Double, let lastUpdated = json["timestamp"] as? Int else {
return nil
}
return WidgetDataStore(rate: String(rateDouble), lastUpdate: String(lastUpdated), rateDouble: rateDouble)
}
}
}
func fiatUnit(currency: String) -> FiatUnit? {
guard let file = Bundle.main.path(forResource: "FiatUnits", ofType: "plist") else {
return nil
}
let fileURL: URL = URL(fileURLWithPath: file)
var fiatUnits: FiatUnits?
if let data = try? Data(contentsOf: fileURL) {
let decoder = PropertyListDecoder()
fiatUnits = try? decoder.decode(FiatUnits.self, from: data)
}
return fiatUnits?.first(where: {$0.endPointKey == currency})
}
| 35.672727 | 362 | 0.687564 |
d9d757732365308330dd5d1f0515b3878865149b | 11,270 | import Quick
import Nimble
@testable import TradeItIosTicketSDK2
class TradeItAccountManagementViewControllerSpec: QuickSpec {
override func spec() {
var controller: TradeItAccountManagementViewController!
var accountManagementTableManager: FakeTradeItAccountManagementTableViewManager!
var window: UIWindow!
var nav: UINavigationController!
var linkedBroker: FakeTradeItLinkedBroker!
var alertManager: FakeTradeItAlertManager!
var linkedBrokerManager: FakeTradeItLinkedBrokerManager!
var linkBrokerUIFlow: FakeTradeItLinkBrokerUIFlow!
describe("initialization") {
beforeEach {
accountManagementTableManager = FakeTradeItAccountManagementTableViewManager()
window = UIWindow()
let bundle = Bundle(identifier: "TradeIt.TradeItIosTicketSDK2")
let storyboard: UIStoryboard = UIStoryboard(name: "TradeIt", bundle: bundle)
linkedBrokerManager = FakeTradeItLinkedBrokerManager()
TradeItSDK._linkedBrokerManager = linkedBrokerManager
linkBrokerUIFlow = FakeTradeItLinkBrokerUIFlow()
controller = storyboard.instantiateViewController(withIdentifier: TradeItStoryboardID.accountManagementView.rawValue) as? TradeItAccountManagementViewController
controller.accountManagementTableManager = accountManagementTableManager
controller.linkBrokerUIFlow = linkBrokerUIFlow
linkedBroker = FakeTradeItLinkedBroker(session: FakeTradeItSession(), linkedLogin: TradeItLinkedLogin())
let account1 = FakeTradeItLinkedBrokerAccount(linkedBroker: linkedBroker, accountName: "My account #1", accountNumber: "123456789", balance: nil, fxBalance: nil, positions: [])
let account2 = FakeTradeItLinkedBrokerAccount(linkedBroker: linkedBroker, accountName: "My account #2", accountNumber: "234567890", balance: nil, fxBalance: nil, positions: [])
linkedBroker.accounts = [account1, account2]
controller.linkedBroker = linkedBroker
alertManager = FakeTradeItAlertManager()
controller.alertManager = alertManager
nav = UINavigationController(rootViewController: controller)
window.addSubview(nav.view)
flushAsyncEvents()
}
it("sets up the accountsManagementTableManager") {
expect(accountManagementTableManager.accountsTableView).to(be(controller.accountsTableView))
}
it("populates the table with the linkedBrokerAccounts") {
expect(accountManagementTableManager.calls.forMethod("updateAccounts(withAccounts:)").count).to(equal(1))
}
describe("pull to refresh") {
var onRefreshCompleteWasCalled = false
var accountsArg: [TradeItLinkedBrokerAccount]?
beforeEach {
let onRefreshComplete: (_ withAccounts: [TradeItLinkedBrokerAccount]?)-> Void = { (withAccounts: [TradeItLinkedBrokerAccount]?) in
onRefreshCompleteWasCalled = true
accountsArg = withAccounts
}
accountManagementTableManager.calls.reset()
controller.refreshRequested(fromAccountManagementTableViewManager: accountManagementTableManager, onRefreshComplete: onRefreshComplete)
}
it("reauthenticates the linkedBroker") {
expect(linkedBroker.calls.forMethod("authenticate(onSuccess:onSecurityQuestion:onFailure:)").count).to(equal(1))
}
context("when authentication succeeds") {
beforeEach {
let onSuccess = linkedBroker.calls.forMethod("authenticate(onSuccess:onSecurityQuestion:onFailure:)")[0].args["onSuccess"] as! () -> Void
onSuccess()
}
it("calls refreshAccountBalances on the linkedBroker") {
expect(linkedBroker.calls.forMethod("refreshAccountBalances(onFinished:)").count).to(equal(1))
}
describe("when finishing to refresh balances") {
beforeEach {
let onFinished1 = linkedBroker.calls.forMethod("refreshAccountBalances(onFinished:)")[0].args["onFinished"] as! () -> Void
onFinished1()
}
it("calls onRefreshComplete with the accounts") {
expect(onRefreshCompleteWasCalled).to(beTrue())
expect(accountsArg).to(equal(linkedBroker.accounts))
}
}
}
context("when authentication fails") {
var error: TradeItErrorResult!
beforeEach {
error = TradeItErrorResult()
error.longMessages = ["My long message"]
let onFailure = linkedBroker.calls.forMethod("authenticate(onSuccess:onSecurityQuestion:onFailure:)")[0].args["onFailure"] as! (TradeItErrorResult) -> Void
onFailure(error)
}
xit("call showTradeItErrorResultAlert to display the error") {
let calls = alertManager.calls.forMethod("showTradeItErrorResultAlert(onViewController:errorResult:onAlertDismissed:)")
expect(calls.count).to(equal(1))
expect(calls[0].args["errorResult"] as! TradeItErrorResult).to(be(error))
}
xit("calls onRefreshComplete with nil") {
expect(onRefreshCompleteWasCalled).to(beTrue())
expect(accountsArg).to(beNil())
}
}
context("when there is a security question") {
//TODO
}
}
describe("unlinkAccountWasTapped") {
beforeEach {
controller.unlinkAccountWasTapped(controller)
}
xit("calls tradeItAlert to show a modal") {
let calls = alertManager.calls.forMethod("showValidationAlert(onViewController:title:message:actionTitle:onValidate:onCancel:)")
expect(calls.count).to(equal(1))
}
xdescribe("The user taps on unlink") {
context("When the user has other broker accounts") {
beforeEach {
let calls = alertManager.calls.forMethod("showValidationAlert(onViewController:title:message:actionTitle:onValidate:onCancel:)")
let onValidate = calls[0].args["onValidate"] as! () -> Void
onValidate()
}
it("calls unlink method on the linkedBrokerManager") {
expect(linkedBrokerManager.calls.forMethod("unlinkBroker").count).to(equal(1))
}
}
}
xdescribe("the user taps on cancel") {
var accounts: [TradeItLinkedBrokerAccount]!
beforeEach {
accounts = linkedBroker.accounts
let calls = alertManager.calls.forMethod("showValidationAlert(onViewController:title:message:actionTitle:onValidate:onCancel:)")
let onCancel = calls[0].args["onCancel"] as! () -> Void
onCancel()
}
it("stays on the account management screen with the same data") {
expect(nav.topViewController).toEventually(beAnInstanceOf(TradeItAccountManagementViewController.self))
expect(accounts).to(equal(linkedBroker.accounts))
}
}
}
describe("relinkAccountWasTapped") {
beforeEach {
controller.relinkAccountWasTapped(controller)
}
it("calls the presentRelinkBrokerFlow from the linkedBrokerFlow") {
let calls = linkBrokerUIFlow.calls.forMethod("presentRelinkBrokerFlow(inViewController:linkedBroker:onLinked:onFlowAborted:)")
expect(calls.count).to(equal(1))
}
xcontext("when linking is finished from the login screen") {
var fakeNavigationController: FakeUINavigationController!
beforeEach {
let calls = linkBrokerUIFlow.calls.forMethod("presentRelinkBrokerFlow(inViewController:linkedBroker:onLinked:onFlowAborted:)")
let onLinked = calls[0].args["onLinked"] as! (_ presentedNavController: UINavigationController) -> Void
fakeNavigationController = FakeUINavigationController()
onLinked(fakeNavigationController)
}
it ("dismiss the view controller") {
expect(fakeNavigationController.calls.forMethod("dismissViewControllerAnimated(_:completion:)").count).to(equal(1))
}
it("calls the refreshAccountBalances on the linkedBroker") {
expect(linkedBroker.calls.forMethod("refreshAccountBalances(onFinished:)").count).to(equal(1))
}
describe("when refreshing balances is finished") {
var account1: TradeItLinkedBrokerAccount!
beforeEach {
account1 = FakeTradeItLinkedBrokerAccount(linkedBroker: linkedBroker, accountName: "My account #11", accountNumber: "123456789", balance: nil, fxBalance: nil, positions: [])
linkedBroker.accounts = [account1]
let onFinished = linkedBroker.calls.forMethod("refreshAccountBalances(onFinished:)")[0].args["onFinished"] as! () -> Void
onFinished()
}
it("calls the update Account method on the accountManagementTableManager") {
let calls = accountManagementTableManager.calls.forMethod("updateAccounts(withAccounts:)")
expect(calls.count).to(equal(2))
let argAccounts = calls[1].args["withAccounts"] as! [TradeItLinkedBrokerAccount]
expect(argAccounts[0]).to(be(account1))
}
}
}
}
}
}
}
| 52.418605 | 201 | 0.55386 |
f73fbffcdebac0af32501cf1e5e13a8eb1363b1e | 2,790 | import Foundation
func _raiseExceptionMatcher<T>(message: String, matches: (NSException?) -> Bool) -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.actualValue = nil
failureMessage.postfixMessage = message
// It would be better if this was part of Expression, but
// Swift compiler crashes when expect() is inside a closure.
var exception: NSException?
var result: T?
var capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
capture.tryBlock {
actualExpression.evaluate()
return
}
return matches(exception)
}
}
public func raiseException(#named: String, #reason: String?) -> MatcherFunc<Any?> {
return _raiseExceptionMatcher("raise exception named <\(named)> and reason <\(reason)>") {
exception in return exception?.name == named && exception?.reason == reason
}
}
public func raiseException(#named: String) -> MatcherFunc<Any?> {
return _raiseExceptionMatcher("raise exception named <\(named)>") {
exception in return exception?.name == named
}
}
public func raiseException() -> MatcherFunc<Any?> {
return _raiseExceptionMatcher("raise any exception") {
exception in return exception != nil
}
}
@objc public class NMBObjCRaiseExceptionMatcher : NMBMatcher {
var _name: String?
var _reason: String?
init(name: String?, reason: String?) {
_name = name
_reason = reason
}
public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let block: () -> Any? = ({ actualBlock(); return nil })
let expr = Expression(expression: block, location: location)
if _name != nil && _reason != nil {
return raiseException(named: _name!, reason: _reason).matches(expr, failureMessage: failureMessage)
} else if _name != nil {
return raiseException(named: _name!).matches(expr, failureMessage: failureMessage)
} else {
return raiseException().matches(expr, failureMessage: failureMessage)
}
}
var named: (name: String) -> NMBObjCRaiseExceptionMatcher {
return ({ name in
return NMBObjCRaiseExceptionMatcher(name: name, reason: self._reason)
})
}
var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher {
return ({ reason in
return NMBObjCRaiseExceptionMatcher(name: self._name, reason: reason)
})
}
}
extension NMBObjCMatcher {
public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher {
return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil)
}
}
| 34.875 | 121 | 0.647312 |
91460b248b354eb9e32c2d8c2dbfc439dff52b01 | 1,283 | //
// English_News_ReaderUITests.swift
// English News ReaderUITests
//
// Created by yuji shimada on 2017/10/02.
// Copyright © 2017年 yuji shimada. All rights reserved.
//
import XCTest
class English_News_ReaderUITests: 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.
}
}
| 34.675676 | 182 | 0.671083 |
1c008cd6d635d8590441695a50d8db248f510a69 | 1,781 | //
// CreateFirstTableViewCell.swift
// inviti
//
// Created by Hannah.C on 17.05.21.
//
import UIKit
class CreateFirstCell: UITableViewCell {
@IBOutlet weak var subjectTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
var subjectCellEmpty: Bool = true
var locationCellEmpty: Bool = true
var viewModel: MeetingViewModel?
var createViewModel = CreateMeetingViewModel()
@IBAction func addSubject(_ sender: UITextField) {
guard let subject = sender.text else {
return
}
createViewModel.onSubjectChanged(text: subject)
}
@IBAction func addLocation(_ sender: UITextField) {
guard let location = sender.text else {
return
}
createViewModel.onLocationChanged(text: location)
}
func setup(viewModel: MeetingViewModel) {
subjectTextField.text = viewModel.subject
locationTextField.text = viewModel.location
}
override func awakeFromNib() {
super.awakeFromNib()
subjectTextField.delegate = self
locationTextField.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
extension CreateFirstCell: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
return updatedText.count <= 16
}
}
| 23.434211 | 129 | 0.654688 |
fcc4b0b6680e3fa797221bc6860d2c1fe0d6f187 | 2,492 | //
// SceneDelegate.swift
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var rootController: UINavigationController {
return self.window!.rootViewController as! UINavigationController
}
lazy var dependencyProvider = DependencyProvider(rootController: self.rootController)
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 }
self.dependencyProvider.start()
}
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.
}
}
| 46.148148 | 147 | 0.720706 |
d52721f1840bdbd4a548efd11ada3e6c2fcac3cb | 3,281 | //
// ViewController.swift
// FarmerMakert
//
// Created by Hemant Gore on 23/07/20.
// Copyright © 2020 Sci-Fi. All rights reserved.
//
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
@IBOutlet weak var mobileNoTextField: UITextField!
let isMFAEnabled = false
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
}
@IBAction func loginTaped(_ sender: Any) {
PhoneAuthProvider.provider().verifyPhoneNumber(mobileNoTextField.text!, uiDelegate: nil) { (verificationID, error) in
if let error = error {
self.showMessage(title: NSLocalizedString("Error", comment: "Title for Error"), message: error.localizedDescription, actionTitle: NSLocalizedString("Ok", comment: "Ok"))
return
}
UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
// Sign in using the verificationID and the code sent to the user
self.promptVerificationCode()
}
}
private func promptVerificationCode() {
showInputDialog(title: NSLocalizedString("Add verification code", comment: "Add verification code"),
subtitle: NSLocalizedString("Please enter the one time code received in SMS", comment: "Please enter the one time code received in SMS"),
actionTitle: NSLocalizedString("Submit", comment: "Submit"),
cancelTitle: NSLocalizedString("Cancel", comment: "Cancel"),
inputPlaceholder: NSLocalizedString("code", comment: "placeholder for code"),
inputKeyboardType: .numberPad) { (input: String?) in
print("Code is \(input ?? "")")
if let verificationCode = input,
verificationCode.count == 6,
let verificationID = UserDefaults.standard.string(forKey: "authVerificationID") {
let credential = PhoneAuthProvider.provider().credential(
withVerificationID: verificationID,
verificationCode: verificationCode)
self.signIn(credential: credential)
}
}
}
private func signIn(credential: PhoneAuthCredential) {
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
let authError = error as NSError
if (self.isMFAEnabled && authError.code == AuthErrorCode.secondFactorRequired.rawValue) {
} else {
self.showMessage(title: NSLocalizedString("Error", comment: "Title for Error"), message: error.localizedDescription, actionTitle: NSLocalizedString("Ok", comment: "Ok"))
return
}
return
}
if let dashboardVC = DashboardViewController.controllerInStoryboard() {
let navVC = UINavigationController(rootViewController: dashboardVC)
navVC.modalPresentationStyle = .fullScreen
self.present(navVC, animated: true, completion: nil)
}
}
}
}
| 42.064103 | 185 | 0.594331 |
bb50c7f78711fd1bddaf5818f3e015da87a435d1 | 9,203 | import Foundation
import GeoJSONKit
extension GeoJSON.LineString {
var coordinates: [GeoJSON.Position] { positions }
/// Returns a new `.LineString` based on bezier transformation of the input line.
///
/// ported from https://github.com/Turfjs/turf/blob/1ea264853e1be7469c8b7d2795651c9114a069aa/packages/turf-bezier-spline/index.ts
public func bezier(resolution: Int = 10000, sharpness: Double = 0.85) -> GeoJSON.LineString? {
let points = coordinates.map {
SplinePoint(coordinate: $0)
}
guard let spline = Spline(points: points, duration: resolution, sharpness: sharpness) else {
return nil
}
let coords = stride(from: 0, to: resolution, by: 10)
.filter { Int(floor(Double($0) / 100)) % 2 == 0 }
.map { spline.position(at: $0).coordinate }
return GeoJSON.LineString(positions: coords)
}
/// Returns a `.LineString` along a `.LineString` within a distance from a coordinate.
public func trimmed(from coordinate: GeoJSON.Position, distance: GeoJSON.Distance) -> GeoJSON.LineString? {
let startVertex = closestCoordinate(to: coordinate)
guard startVertex != nil && distance != 0 else {
return nil
}
var vertices: [GeoJSON.Position] = [startVertex!.coordinate]
var cumulativeDistance: GeoJSON.Distance = 0
let addVertex = { (vertex: GeoJSON.Position) -> Bool in
let lastVertex = vertices.last!
let incrementalDistance = lastVertex.distance(to: vertex)
if cumulativeDistance + incrementalDistance <= abs(distance) {
vertices.append(vertex)
cumulativeDistance += incrementalDistance
return true
} else {
let remainingDistance = abs(distance) - cumulativeDistance
let direction = lastVertex.direction(to: vertex)
let endpoint = lastVertex.coordinate(at: remainingDistance, facing: direction)
vertices.append(endpoint)
cumulativeDistance += remainingDistance
return false
}
}
if distance > 0 {
for vertex in coordinates.suffix(from: startVertex!.index) {
if !addVertex(vertex) {
break
}
}
} else {
for vertex in coordinates.prefix(through: startVertex!.index).reversed() {
if !addVertex(vertex) {
break
}
}
}
assert(round(cumulativeDistance) <= round(abs(distance)))
return GeoJSON.LineString(positions: vertices)
}
/// `IndexedCoordinate` is a coordinate with additional information such as
/// the index from its position in the polyline and distance from the start
/// of the polyline.
public struct IndexedCoordinate {
/// The coordinate
public let coordinate: Array<GeoJSON.Position>.Element
/// The index of the coordinate
public let index: Array<GeoJSON.Position>.Index
/// The coordinate’s distance from the start of the polyline
public let distance: GeoJSON.Distance
}
/// Returns a coordinate along a `.LineString` at a certain distance from the start of the polyline.
public func coordinateFromStart(distance: GeoJSON.Distance) -> GeoJSON.Position? {
return indexedCoordinateFromStart(distance: distance)?.coordinate
}
/// Returns an indexed coordinate along a `.LineString` at a certain distance from the start of the polyline.
///
/// Ported from https://github.com/Turfjs/turf/blob/142e137ce0c758e2825a260ab32b24db0aa19439/packages/turf-along/index.js
public func indexedCoordinateFromStart(distance: GeoJSON.Distance) -> IndexedCoordinate? {
var traveled: GeoJSON.Distance = 0
guard let firstCoordinate = coordinates.first else {
return nil
}
guard distance >= 0 else {
return IndexedCoordinate(coordinate: firstCoordinate, index: 0, distance: 0)
}
for i in 0..<coordinates.count {
guard distance < traveled || i < coordinates.count - 1 else {
break
}
if traveled >= distance {
let overshoot = distance - traveled
if overshoot == 0 {
return IndexedCoordinate(coordinate: coordinates[i], index: i, distance: traveled)
}
let direction = coordinates[i].direction(to: coordinates[i - 1]) - 180
let coordinate = coordinates[i].coordinate(at: overshoot, facing: direction)
return IndexedCoordinate(coordinate: coordinate, index: i - 1, distance: distance)
}
traveled += coordinates[i].distance(to: coordinates[i + 1])
}
return IndexedCoordinate(coordinate: coordinates.last!, index: coordinates.endIndex - 1, distance: traveled)
}
/// Returns the distance along a slice of a `.LineString` with the given endpoints.
///
/// Ported from https://github.com/Turfjs/turf/blob/142e137ce0c758e2825a260ab32b24db0aa19439/packages/turf-line-slice/index.js
public func distance(from start: GeoJSON.Position? = nil, to end: GeoJSON.Position? = nil) -> GeoJSON.Distance? {
guard !coordinates.isEmpty else { return nil }
guard let slicedCoordinates = sliced(from: start, to: end)?.coordinates else {
return nil
}
let zippedCoordinates = zip(slicedCoordinates.prefix(upTo: slicedCoordinates.count - 1), slicedCoordinates.suffix(from: 1))
return zippedCoordinates.map { $0.distance(to: $1) }.reduce(0, +)
}
/// Returns a subset of the `.LineString` between given coordinates.
///
/// Ported from https://github.com/Turfjs/turf/blob/142e137ce0c758e2825a260ab32b24db0aa19439/packages/turf-line-slice/index.js
public func sliced(from start: GeoJSON.Position? = nil, to end: GeoJSON.Position? = nil) -> GeoJSON.LineString? {
guard !coordinates.isEmpty else { return nil }
let startVertex = (start != nil ? closestCoordinate(to: start!) : nil) ?? IndexedCoordinate(coordinate: coordinates.first!, index: 0, distance: 0)
let endVertex = (end != nil ? closestCoordinate(to: end!) : nil) ?? IndexedCoordinate(coordinate: coordinates.last!, index: coordinates.indices.last!, distance: 0)
let ends: (IndexedCoordinate, IndexedCoordinate)
if startVertex.index <= endVertex.index {
ends = (startVertex, endVertex)
} else {
ends = (endVertex, startVertex)
}
var coords = ends.0.index == ends.1.index ? [] : Array(coordinates[ends.0.index + 1...ends.1.index])
coords.insert(ends.0.coordinate, at: 0)
if coords.last != ends.1.coordinate {
coords.append(ends.1.coordinate)
}
return GeoJSON.LineString(positions: coords)
}
/// Returns the geographic coordinate along the `.LineString` that is closest to the given coordinate as the crow flies.
/// The returned coordinate may not correspond to one of the polyline’s vertices, but it always lies along the polyline.
///
/// Ported from https://github.com/Turfjs/turf/blob/142e137ce0c758e2825a260ab32b24db0aa19439/packages/turf-point-on-line/index.js
public func closestCoordinate(to coordinate: GeoJSON.Position) -> IndexedCoordinate? {
guard let startCoordinate = coordinates.first else { return nil }
guard coordinates.count > 1 else {
return IndexedCoordinate(coordinate: startCoordinate, index: 0, distance: coordinate.distance(to: startCoordinate))
}
var closestCoordinate: IndexedCoordinate?
var closestDistance: GeoJSON.Distance?
for index in 0..<coordinates.count - 1 {
let segment = (coordinates[index], coordinates[index + 1])
let distances = (coordinate.distance(to: segment.0), coordinate.distance(to: segment.1))
let maxDistance = max(distances.0, distances.1)
let direction = segment.0.direction(to: segment.1)
let perpendicularPoint1 = coordinate.coordinate(at: maxDistance, facing: direction + 90)
let perpendicularPoint2 = coordinate.coordinate(at: maxDistance, facing: direction - 90)
let intersectionPoint = intersection((perpendicularPoint1, perpendicularPoint2), segment)
let intersectionDistance: GeoJSON.Distance? = intersectionPoint != nil ? coordinate.distance(to: intersectionPoint!) : nil
if distances.0 < closestDistance ?? .greatestFiniteMagnitude {
closestCoordinate = IndexedCoordinate(coordinate: segment.0,
index: index,
distance: startCoordinate.distance(to: segment.0))
closestDistance = distances.0
}
if distances.1 < closestDistance ?? .greatestFiniteMagnitude {
closestCoordinate = IndexedCoordinate(coordinate: segment.1,
index: index+1,
distance: startCoordinate.distance(to: segment.1))
closestDistance = distances.1
}
if intersectionDistance != nil && intersectionDistance! < closestDistance ?? .greatestFiniteMagnitude {
closestCoordinate = IndexedCoordinate(coordinate: intersectionPoint!,
index: index,
distance: startCoordinate.distance(to: intersectionPoint!))
closestDistance = intersectionDistance!
}
}
return closestCoordinate
}
}
| 44.245192 | 167 | 0.673259 |
dd39cfe464f28c241c4d20fda3ca6594589a40dc | 948 | import Foundation
/**
A query allowing to define scripts as queries. They are typically used in a filter context.
[More information](https://www.elastic.co/guide/en/elasticsearch/reference/6.3/query-dsl-script-query.html)
*/
public struct ScriptQuery: QueryElement {
/// :nodoc:
public static var typeKey = QueryElementMap.script
public let script: Script
enum CodingKeys: String, CodingKey {
case script
}
public init(script: Script) {
self.script = script
}
/// :nodoc:
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(script, forKey: .script)
}
/// :nodoc:
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.script = try container.decode(Script.self, forKey: .script)
}
}
| 27.882353 | 108 | 0.660338 |
23ddf15ea1ad83feec13fdfa3542684cf578e0d2 | 1,931 | import UIKit
import SnapKit
class RateDiffView: UIView {
private let imageView = UIImageView()
private let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
imageView.snp.makeConstraints { maker in
maker.leading.equalToSuperview()
maker.centerY.equalToSuperview()
}
imageView.setContentCompressionResistancePriority(.required, for: .horizontal)
addSubview(label)
label.snp.makeConstraints { maker in
maker.leading.equalTo(imageView.snp.trailing).offset(CGFloat.margin1x)
maker.top.trailing.bottom.equalToSuperview()
}
label.setContentCompressionResistancePriority(.required, for: .horizontal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var font: UIFont {
get {
label.font
}
set {
label.font = newValue
}
}
func set(value: Decimal?, highlightText: Bool = true) {
guard let value = value else {
label.text = nil
imageView.image = nil
return
}
let color: UIColor = value.isSignMinus ? .themeLucian : .themeRemus
let imageName = value.isSignMinus ? "Down" : "Up"
imageView.image = UIImage(named: imageName)?.tinted(with: color)
let formattedDiff = RateDiffView.formatter.string(from: abs(value) as NSNumber)
label.textColor = highlightText ? color : .themeGray
label.text = formattedDiff.map { "\($0)%" }
}
}
extension RateDiffView {
private static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.groupingSeparator = ""
return formatter
}()
}
| 27.197183 | 87 | 0.619368 |
2104dd501e446b730c1810e01853d3332ec41583 | 2,168 | //
// AppDelegate.swift
// EggKit
//
// Created by Limon-O-O on 03/20/2017.
// Copyright (c) 2017 Limon-O-O. 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.12766 | 285 | 0.752306 |
11d4bc8de8388efb94737b6400c5f4d9d24588ec | 2,076 | //
// AppDelegate.swift
// Calculator
//
// Created by Marisa WONG on 16/05/2016.
// Copyright © 2016 PW. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 44.170213 | 281 | 0.776012 |
2f66211b6f6481710604571cca6ca073797f51bf | 19 | import Algorithms
| 6.333333 | 17 | 0.842105 |
db643b63f18973f677336af57398efe3f687817d | 3,380 | //
// TurnipsChartView.swift
// ACHNBrowserUI
//
// Created by Renaud JENNY on 02/05/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
struct TurnipsChartView: View {
private struct ChartHeightPreferenceKey: PreferenceKey {
static var defaultValue: CGFloat?
static func reduce(value: inout CGFloat?, nextValue: () -> CGFloat?) {
if let newValue = nextValue() { value = newValue }
}
}
typealias PredictionCurve = TurnipsChart.PredictionCurve
static let verticalLinesCount: CGFloat = 9
var predictions: TurnipPredictions
@Binding var animateCurves: Bool
@Environment(\.presentationMode) var presentation
@State private var chartFrame: CGRect?
@State private var chartHeight: CGFloat?
var body: some View {
VStack {
TurnipsChartTopLegendView()
HStack(alignment: .top) {
TurnipsChartVerticalLegend(predictions: predictions)
.frame(width: 30, height: chartHeight)
.padding(.top)
ScrollView(.horizontal, showsIndicators: false) {
chart.frame(width: 600, height: 500)
}
}
}
.onHeightPreferenceChange(ChartHeightPreferenceKey.self, storeValueIn: $chartHeight)
}
private var chart: some View {
VStack(spacing: 10) {
curves
.propagateHeight(ChartHeightPreferenceKey.self)
TurnipsChartBottomLegendView(predictions: predictions)
}
.padding()
}
private var curves: some View {
ZStack(alignment: .leading) {
TurnipsChartGrid(predictions: predictions)
.stroke()
.opacity(0.5)
TurnipsChartMinBuyPriceCurve(predictions: predictions)
.stroke(style: StrokeStyle(dash: [Self.verticalLinesCount]))
.foregroundColor(PredictionCurve.minBuyPrice.color)
.saturation(3)
.blendMode(.screen)
TurnipsChartMinMaxCurves(predictions: predictions, animationStep: animateCurves ? 1 : 0.1)
.foregroundColor(PredictionCurve.minMax.color)
.opacity(0.25)
.blendMode(.darken)
TurnipsChartAverageCurve(predictions: predictions, animationStep: animateCurves ? 1 : 0)
.stroke(lineWidth: 3)
.foregroundColor(PredictionCurve.average.color)
.saturation(5)
.blendMode(.screen)
}.animation(.spring())
}
}
struct TurnipsChartView_Previews: PreviewProvider {
static var previews: some View {
TurnipsChartView(
predictions: predictions,
animateCurves: .constant(true)
)
}
static let predictions = TurnipPredictions(
minBuyPrice: 83,
averagePrices: averagePrices,
minMax: minMax,
averageProfits: averageProfits
)
static let averagePrices = [89, 85, 88, 104, 110, 111, 111, 111, 106, 98, 82, 77]
static let minMax = [[38, 142], [33, 142], [29, 202], [24, 602], [19, 602], [14, 602], [9, 602], [29, 602], [24, 602], [19, 602], [14, 202], [9, 201]]
static let averageProfits = [89, 85, 88, 104, 110, 111, 111, 111, 106, 98, 82, 77]
}
| 34.489796 | 154 | 0.597633 |
1d6c7aa34842325401a738dc7bd39b51d166af06 | 1,815 | //
// SettingsViewController.swift
// tippy
//
// Created by Maria De la Rosa on 8/14/17.
// Copyright © 2017 Maria De la Rosa. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var tipSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func ValueChanged(_ sender: Any) {
let currentTip = tipSlider.value
tipLabel.text = String(format: "%.2f%%",currentTip)
let defaults = UserDefaults.standard // Swift 3 syntax, previously NSUserDefaults.standardUserDefaults()
defaults.set(currentTip, forKey: "tipDefault")
defaults.synchronize()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("view will appear")
let defaults = UserDefaults.standard
let storedValue = defaults.object(forKey: "tipDefault")
if(storedValue != nil){
let defaultTipValue = storedValue as! Float
tipSlider.setValue(defaultTipValue, animated: false)
tipLabel.text = String(format: "%.2f%%",defaultTipValue)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 30.762712 | 112 | 0.655096 |
f4b0a51e3802b8de5c329037cff94d1a798e6368 | 459 | //
// Copyright (c) 2021 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
@testable import AdyenCard
final class CardPublicKeyProviderMock: AnyCardPublicKeyProvider {
let apiContext: APIContext = Dummy.context
var onFetch: ((_ completion: @escaping CompletionHandler) -> Void)?
func fetch(completion: @escaping CompletionHandler) {
onFetch?(completion)
}
}
| 24.157895 | 100 | 0.712418 |
2f988c3a6c1768fdb9600ddd27acf6e76ceaf2b9 | 882 | //
// ImageUploadCell.swift
// SCWeibo
//
// Created by 王书超 on 2021/5/16.
//
import UIKit
class ImageUploadCell: UICollectionViewCell {
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func layoutSubviews() {
super.layoutSubviews()
setupLayout()
}
}
// MARK: - Private Methods
private extension ImageUploadCell {
func setupSubviews() {
layer.borderWidth = 1
layer.borderColor = UIColor.sc.color(RGB: 0xD8D8D8).cgColor
imageView.clipsToBounds = true
imageView.image = UIImage(named: "UploadImage_Normal")
contentView.addSubview(imageView)
}
func setupLayout() {
imageView.anchorInCenter(width: 50, height: 50)
}
}
| 19.6 | 67 | 0.634921 |
f5f12a483434c7d9aa799ce6a359e33f36e46ef7 | 1,423 | //
// ExampleUITests.swift
// ExampleUITests
//
// Created by Tianzhu Qiao on 9/7/21.
//
import XCTest
class ExampleUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.093023 | 182 | 0.654954 |
391dfb8863fd9349de35bfe72f01d7f0c057959a | 8,219 | //
// WriteNoteController+Onboarding.swift
// Jotify
//
// Created by Harrison Leath on 10/5/19.
// Copyright © 2019 Harrison Leath. All rights reserved.
//
import UIKit
extension WriteNoteController {
func presentOnboarding() {
// check to see if the user is new, updated, or neither
let standard = UserDefaults.standard
let shortVersionKey = "CFBundleShortVersionString"
guard let currentVersion = Bundle.main.infoDictionary![shortVersionKey] as? String else {
print("Current version could not be found")
return
}
let previousVersion = standard.object(forKey: shortVersionKey) as? String
if previousVersion == currentVersion {
// same version, no update
print("same version")
} else {
// replace with `if let previousVersion = previousVersion {` if you need the exact value
if previousVersion != nil {
// new version
print("new version")
// presentUpdateOnboarding(viewController: self, tintColor: StoredColors.noteColor)
// if user has premium, go ahead and enable automatic light/dark mode
if UserDefaults.standard.bool(forKey: "com.austinleath.Jotify.Premium") {
UserDefaults.standard.set(true, forKey: "useSystemMode")
}
} else {
// first launch, restore purchases
print("first launch")
presentFirstLaunchOnboarding(viewController: self, tintColor: StoredColors.noteColor)
JotifyProducts.store.restorePurchases()
}
standard.set(currentVersion, forKey: shortVersionKey)
}
}
func presentUpdateOnboarding(viewController: UIViewController, tintColor: UIColor) {
// Jotify v1.2.2 Onboarding
let whatsNew = WhatsNew(
title: "What's New - v1.2.2",
items: [
WhatsNew.Item(
title: "Major Changes - SALE!",
subtitle: "• There is a limited time sale on Jotify Premium! Get it for only 99 cents (50% off)!\n• Jotify now has a 6th color scheme, \"Scarlet Azure\", check it out in settings!",
image: UIImage(named: "bell")
),
WhatsNew.Item(
title: "Minor Improvements",
subtitle: "• Added dark icon support for iPad! If you own Jotify Premium, you can enable this by settings -> about -> click on the Jotify icon.",
image: UIImage(named: "add")
),
WhatsNew.Item(
title: "Bug Fixes",
subtitle: "• Fixed a bug where using mass delete would not correctly update the app badge.\n• Fixed a bug that would incorrectly sort notes when searching.",
image: UIImage(named: "bugFix")
),
]
)
var configuration = WhatsNewViewController.Configuration()
if UserDefaults.standard.bool(forKey: "darkModeEnabled") {
configuration.apply(theme: .darkDefault)
configuration.backgroundColor = UIColor.grayBackground
} else {
configuration.apply(theme: .default)
}
configuration.titleView.insets = UIEdgeInsets(top: 40, left: 20, bottom: 15, right: 15)
configuration.itemsView.titleFont = .boldSystemFont(ofSize: 17)
configuration.itemsView.imageSize = .preferred
configuration.completionButton.hapticFeedback = .impact(.medium)
configuration.completionButton.insets.bottom = 30
configuration.apply(animation: .fade)
if UserDefaults.standard.bool(forKey: "useRandomColor") {
configuration.titleView.titleColor = StoredColors.noteColor
configuration.detailButton?.titleColor = StoredColors.noteColor
configuration.completionButton.backgroundColor = StoredColors.noteColor
} else {
configuration.titleView.titleColor = StoredColors.staticNoteColor
configuration.detailButton?.titleColor = StoredColors.staticNoteColor
configuration.completionButton.backgroundColor = StoredColors.staticNoteColor
}
let whatsNewViewController = WhatsNewViewController(
whatsNew: whatsNew,
configuration: configuration
)
DispatchQueue.main.async {
viewController.present(whatsNewViewController, animated: true)
}
}
func presentFirstLaunchOnboarding(viewController: UIViewController, tintColor: UIColor) {
let whatsNew = WhatsNew(
title: "Welcome!",
items: [
WhatsNew.Item(
title: "Notes",
subtitle: "Creating notes is simple: type and enter. Your notes are automatically saved and synced to all of your devices. Swipe right to view your notes.",
image: UIImage(named: "write")
),
WhatsNew.Item(
title: "Reminders",
subtitle: "Set reminders on all of your notes with ease. Simply tap on the alarm icon, set a date, and wait.",
image: UIImage(named: "reminder")
),
WhatsNew.Item(
title: "Privacy",
subtitle: "Jotify does not have access to any of your data and never will. All of your notes are just that, yours.",
image: UIImage(named: "lock")
),
WhatsNew.Item(
title: "No Accounts. Ever.",
subtitle: "Jotify uses your iCloud account to store notes, so no annoying emails or extra passwords to worry about.",
image: UIImage(named: "person")
),
WhatsNew.Item(
title: "Dark Mode",
subtitle: "It looks pretty good. You should check it out.",
image: UIImage(named: "moon")
),
WhatsNew.Item(
title: "Open Source",
subtitle: "Jotify is open source, so you know exactly what is running on your device. Feel free to check it out on GitHub.",
image: UIImage(named: "github")
),
]
)
var configuration = WhatsNewViewController.Configuration()
if UserDefaults.standard.bool(forKey: "darkModeEnabled") {
configuration.apply(theme: .darkDefault)
configuration.backgroundColor = UIColor.grayBackground
} else {
configuration.apply(theme: .default)
}
configuration.titleView.insets = UIEdgeInsets(top: 40, left: 20, bottom: 15, right: 15)
configuration.itemsView.titleFont = .boldSystemFont(ofSize: 17)
configuration.itemsView.imageSize = .preferred
configuration.completionButton.hapticFeedback = .impact(.medium)
configuration.completionButton.insets.bottom = 30
configuration.apply(animation: .fade)
if UserDefaults.standard.bool(forKey: "useRandomColor") {
configuration.titleView.titleColor = StoredColors.noteColor
configuration.detailButton?.titleColor = StoredColors.noteColor
configuration.completionButton.backgroundColor = StoredColors.noteColor
} else {
configuration.titleView.titleColor = StoredColors.staticNoteColor
configuration.detailButton?.titleColor = StoredColors.staticNoteColor
configuration.completionButton.backgroundColor = StoredColors.staticNoteColor
}
let whatsNewViewController = WhatsNewViewController(
whatsNew: whatsNew,
configuration: configuration
)
DispatchQueue.main.async {
viewController.present(whatsNewViewController, animated: true)
}
}
}
| 44.912568 | 201 | 0.587298 |
1d5b7379d6172bb16d437a3d27c100440b8082f2 | 1,125 | //
// V_ColorTests.swift
// V_ColorTests
//
// Created by Gokhan Gultekin on 8.10.2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import XCTest
@testable import VCommon
class V_ColorTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testHexColorNotNil() {
let example = "FC5450"
XCTAssertNotNil(UIColor().hex(string: example))
}
func testemptyHexCode() {
let example = ""
XCTAssertNotNil(UIColor().hex(string: example))
}
func testWithOrWithoutPrefix() {
XCTAssertEqual(UIColor().hex(string: "FC5450"), UIColor().hex(string: "#FC5450"))
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.568182 | 111 | 0.621333 |
9070b13a8cd7916c70c6cd12832ea2fe22ceec9c | 2,738 | import UIKit
import WebKit
class WebViewController: UIViewController
{
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var busyDiv: UIActivityIndicatorView!
var profile: Profile?
var sessionId: String?
override func viewDidLoad()
{
super.viewDidLoad()
loadURL()
}
func loadURL()
{
setCookies()
// Get host from environment variables
let dict = NSProcessInfo.processInfo().environment
let host = dict["HOST"] as? String
//////////////////////
// load our RF page //
//////////////////////
var url = NSURL(string:host!)
var req = NSURLRequest(URL:url!)
self.webView.loadRequest(req)
}
func setCookies()
{
////////////////////
// set our cookie //
////////////////////
var cookieProperties = NSMutableDictionary()
cookieProperties.setObject("sessionId", forKey:NSHTTPCookieName);
cookieProperties.setObject(sessionId!, forKey:NSHTTPCookieValue);
// Get host from environment variables
let dict = NSProcessInfo.processInfo().environment
let host = dict["HOST"] as? String
cookieProperties.setObject(host!, forKey:NSHTTPCookieDomain);
cookieProperties.setObject("/", forKey:NSHTTPCookiePath);
var cookie = NSHTTPCookie(properties: cookieProperties as [NSObject : AnyObject])
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
storage.setCookie(cookie!)
}
func webViewDidStartLoad(webView: UIWebView)
{
if((webView.request?.URL) != nil)
{
var request = webView.request!
var url = request.URL
println("in webViewDidStartLoad : went to page [\(url)] as [\(request.HTTPMethod)]")
}
}
func webViewDidFinishLoad(webView: UIWebView)
{
if((webView.request?.URL) != nil)
{
var request = webView.request!
var url = request.URL
println("in webViewDidFinishLoad : went to page [\(url)] as [\(request.HTTPMethod)] : with last Path Component [\(url!.lastPathComponent)]")
if(url!.lastPathComponent?.hasSuffix("logout") == true || url!.lastPathComponent?.hasSuffix("login") == true)
{
var loggedOutViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loggedOutViewController") as! LoggedOutViewController
self.presentViewController(loggedOutViewController, animated: false, completion: nil)
}
}
}
} | 29.12766 | 157 | 0.575603 |
89dee4c69fa6038be7586b9cbea35d399ba5b81a | 15,340 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 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/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension Outposts {
// MARK: Enums
// MARK: Shapes
public struct CreateOutpostInput: AWSEncodableShape {
public let availabilityZone: String?
public let availabilityZoneId: String?
public let description: String?
public let name: String
public let siteId: String
/// The tags to apply to the Outpost.
public let tags: [String: String]?
public init(availabilityZone: String? = nil, availabilityZoneId: String? = nil, description: String? = nil, name: String, siteId: String, tags: [String: String]? = nil) {
self.availabilityZone = availabilityZone
self.availabilityZoneId = availabilityZoneId
self.description = description
self.name = name
self.siteId = siteId
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.availabilityZone, name: "availabilityZone", parent: name, max: 1000)
try self.validate(self.availabilityZone, name: "availabilityZone", parent: name, min: 1)
try self.validate(self.availabilityZone, name: "availabilityZone", parent: name, pattern: "[a-z\\d-]+")
try self.validate(self.availabilityZoneId, name: "availabilityZoneId", parent: name, max: 255)
try self.validate(self.availabilityZoneId, name: "availabilityZoneId", parent: name, min: 1)
try self.validate(self.availabilityZoneId, name: "availabilityZoneId", parent: name, pattern: "[a-z]+[0-9]+-az[0-9]+")
try self.validate(self.description, name: "description", parent: name, max: 1000)
try self.validate(self.description, name: "description", parent: name, min: 1)
try self.validate(self.description, name: "description", parent: name, pattern: "^[\\S ]+$")
try self.validate(self.name, name: "name", parent: name, max: 255)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "^[\\S ]+$")
try self.validate(self.siteId, name: "siteId", parent: name, max: 255)
try self.validate(self.siteId, name: "siteId", parent: name, min: 1)
try self.validate(self.siteId, name: "siteId", parent: name, pattern: "os-[a-f0-9]{17}")
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^[\\S \\n]+$")
}
}
private enum CodingKeys: String, CodingKey {
case availabilityZone = "AvailabilityZone"
case availabilityZoneId = "AvailabilityZoneId"
case description = "Description"
case name = "Name"
case siteId = "SiteId"
case tags = "Tags"
}
}
public struct CreateOutpostOutput: AWSDecodableShape {
public let outpost: Outpost?
public init(outpost: Outpost? = nil) {
self.outpost = outpost
}
private enum CodingKeys: String, CodingKey {
case outpost = "Outpost"
}
}
public struct DeleteOutpostInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "outpostId", location: .uri(locationName: "OutpostId"))
]
public let outpostId: String
public init(outpostId: String) {
self.outpostId = outpostId
}
public func validate(name: String) throws {
try self.validate(self.outpostId, name: "outpostId", parent: name, max: 180)
try self.validate(self.outpostId, name: "outpostId", parent: name, min: 1)
try self.validate(self.outpostId, name: "outpostId", parent: name, pattern: "^(arn:aws([a-z-]+)?:outposts:[a-z\\d-]+:\\d{12}:outpost/)?op-[a-f0-9]{17}$")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteOutpostOutput: AWSDecodableShape {
public init() {}
}
public struct DeleteSiteInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "siteId", location: .uri(locationName: "SiteId"))
]
public let siteId: String
public init(siteId: String) {
self.siteId = siteId
}
public func validate(name: String) throws {
try self.validate(self.siteId, name: "siteId", parent: name, max: 255)
try self.validate(self.siteId, name: "siteId", parent: name, min: 1)
try self.validate(self.siteId, name: "siteId", parent: name, pattern: "os-[a-f0-9]{17}")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteSiteOutput: AWSDecodableShape {
public init() {}
}
public struct GetOutpostInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "outpostId", location: .uri(locationName: "OutpostId"))
]
public let outpostId: String
public init(outpostId: String) {
self.outpostId = outpostId
}
public func validate(name: String) throws {
try self.validate(self.outpostId, name: "outpostId", parent: name, max: 180)
try self.validate(self.outpostId, name: "outpostId", parent: name, min: 1)
try self.validate(self.outpostId, name: "outpostId", parent: name, pattern: "^(arn:aws([a-z-]+)?:outposts:[a-z\\d-]+:\\d{12}:outpost/)?op-[a-f0-9]{17}$")
}
private enum CodingKeys: CodingKey {}
}
public struct GetOutpostInstanceTypesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken")),
AWSMemberEncoding(label: "outpostId", location: .uri(locationName: "OutpostId"))
]
public let maxResults: Int?
public let nextToken: String?
public let outpostId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, outpostId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.outpostId = outpostId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1005)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: ".*\\S.*")
try self.validate(self.outpostId, name: "outpostId", parent: name, max: 180)
try self.validate(self.outpostId, name: "outpostId", parent: name, min: 1)
try self.validate(self.outpostId, name: "outpostId", parent: name, pattern: "^(arn:aws([a-z-]+)?:outposts:[a-z\\d-]+:\\d{12}:outpost/)?op-[a-f0-9]{17}$")
}
private enum CodingKeys: CodingKey {}
}
public struct GetOutpostInstanceTypesOutput: AWSDecodableShape {
public let instanceTypes: [InstanceTypeItem]?
public let nextToken: String?
public let outpostArn: String?
public let outpostId: String?
public init(instanceTypes: [InstanceTypeItem]? = nil, nextToken: String? = nil, outpostArn: String? = nil, outpostId: String? = nil) {
self.instanceTypes = instanceTypes
self.nextToken = nextToken
self.outpostArn = outpostArn
self.outpostId = outpostId
}
private enum CodingKeys: String, CodingKey {
case instanceTypes = "InstanceTypes"
case nextToken = "NextToken"
case outpostArn = "OutpostArn"
case outpostId = "OutpostId"
}
}
public struct GetOutpostOutput: AWSDecodableShape {
public let outpost: Outpost?
public init(outpost: Outpost? = nil) {
self.outpost = outpost
}
private enum CodingKeys: String, CodingKey {
case outpost = "Outpost"
}
}
public struct InstanceTypeItem: AWSDecodableShape {
public let instanceType: String?
public init(instanceType: String? = nil) {
self.instanceType = instanceType
}
private enum CodingKeys: String, CodingKey {
case instanceType = "InstanceType"
}
}
public struct ListOutpostsInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken"))
]
public let maxResults: Int?
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1005)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: ".*\\S.*")
}
private enum CodingKeys: CodingKey {}
}
public struct ListOutpostsOutput: AWSDecodableShape {
public let nextToken: String?
public let outposts: [Outpost]?
public init(nextToken: String? = nil, outposts: [Outpost]? = nil) {
self.nextToken = nextToken
self.outposts = outposts
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case outposts = "Outposts"
}
}
public struct ListSitesInput: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "MaxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "NextToken"))
]
public let maxResults: Int?
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1005)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: ".*\\S.*")
}
private enum CodingKeys: CodingKey {}
}
public struct ListSitesOutput: AWSDecodableShape {
public let nextToken: String?
public let sites: [Site]?
public init(nextToken: String? = nil, sites: [Site]? = nil) {
self.nextToken = nextToken
self.sites = sites
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case sites = "Sites"
}
}
public struct Outpost: AWSDecodableShape {
public let availabilityZone: String?
public let availabilityZoneId: String?
public let description: String?
public let lifeCycleStatus: String?
public let name: String?
public let outpostArn: String?
public let outpostId: String?
public let ownerId: String?
public let siteId: String?
/// The Outpost tags.
public let tags: [String: String]?
public init(availabilityZone: String? = nil, availabilityZoneId: String? = nil, description: String? = nil, lifeCycleStatus: String? = nil, name: String? = nil, outpostArn: String? = nil, outpostId: String? = nil, ownerId: String? = nil, siteId: String? = nil, tags: [String: String]? = nil) {
self.availabilityZone = availabilityZone
self.availabilityZoneId = availabilityZoneId
self.description = description
self.lifeCycleStatus = lifeCycleStatus
self.name = name
self.outpostArn = outpostArn
self.outpostId = outpostId
self.ownerId = ownerId
self.siteId = siteId
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case availabilityZone = "AvailabilityZone"
case availabilityZoneId = "AvailabilityZoneId"
case description = "Description"
case lifeCycleStatus = "LifeCycleStatus"
case name = "Name"
case outpostArn = "OutpostArn"
case outpostId = "OutpostId"
case ownerId = "OwnerId"
case siteId = "SiteId"
case tags = "Tags"
}
}
public struct Site: AWSDecodableShape {
public let accountId: String?
public let description: String?
public let name: String?
public let siteId: String?
/// The site tags.
public let tags: [String: String]?
public init(accountId: String? = nil, description: String? = nil, name: String? = nil, siteId: String? = nil, tags: [String: String]? = nil) {
self.accountId = accountId
self.description = description
self.name = name
self.siteId = siteId
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case accountId = "AccountId"
case description = "Description"
case name = "Name"
case siteId = "SiteId"
case tags = "Tags"
}
}
}
| 40.474934 | 301 | 0.600326 |
eb27115436f39608d3eabb6c189406665b886c63 | 110 | import OrchardNestKit
public extension EntryCategory {
var elClass: String {
return type.elClass
}
}
| 13.75 | 32 | 0.736364 |
901d28665910bcc3525aacf1ebec31254e31c539 | 4,020 | import UIKit
public class DateHelper {
static let instance = DateHelper()
static let hoursForDetermining: Double = 12
static var formatters = [String: DateFormatter]()
private static let twelveHoursAllowed: [String] = ["en"]
private static var systemHourFormat: String = {
if let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current), dateFormat.firstIndex(of: "a") == nil {
return "HH"
}
return "hh"
}()
static var correctedSystemHourFormat: String {
return DateHelper.twelveHoursAllowed.contains(App.shared.languageManager.currentLanguage) ? DateHelper.systemHourFormat : "HH"
}
private func getFormatter(forFormat format: String) -> DateFormatter {
if let formatter = DateHelper.formatters[format] {
return formatter
}
let formatter = DateFormatter()
formatter.locale = Locale.appCurrent
formatter.setLocalizedDateFormatFromTemplate(format)
DateHelper.formatters[format] = formatter
return formatter
}
private func timeOnly() -> DateFormatter {
getFormatter(forFormat: "\(DateHelper.correctedSystemHourFormat):mm")
}
private func dateOnly(forDate date: Date, short: Bool = true) -> DateFormatter {
if date.isDateInCurrentYear(date: date) {
return getFormatter(forFormat: short ? "d MMM" : "MMMM d")
}
return getFormatter(forFormat: short ? "MM/dd/yy" : "MMMM d, yyyy")
}
private func dateTimeFormatter(interval: DateInterval, forDate date: Date, shortWeek: Bool = false) -> DateFormatter {
switch interval {
case .future, .today: return timeOnly()
case .yesterday, .inWeek, .inYear: return getFormatter(forFormat: "d MMMM")
case .more: return getFormatter(forFormat: "MM/dd/yy")
}
}
func formatTransactionDate(from date: Date) -> String {
let correctDate = min(date, Date())
let interval = date.interval(forDate: correctDate)
let format = interval == .more ? "yyyy MMM d" : "MMM d"
return getFormatter(forFormat: format).string(from: date)
}
public func formatTransactionTime(from date: Date, useYesterday: Bool = false) -> String {
getFormatter(forFormat: "\(DateHelper.correctedSystemHourFormat):mm").string(from: date)
}
public func formatRateListTitle(from date: Date) -> String {
getFormatter(forFormat: "MMM d").string(from: date)
}
public func formatTimeOnly(from date: Date) -> String {
timeOnly().string(from: date)
}
public func formatFullTime(from date: Date) -> String {
let formatter = getFormatter(forFormat: "MMM d, yyyy, \(DateHelper.correctedSystemHourFormat):mm")
return formatter.string(from: date)
}
public func formatFullDateOnly(from date: Date) -> String {
let formatter = getFormatter(forFormat: "MMM d, yyyy")
return formatter.string(from: date)
}
public func formatFullDateWithHour(from date: Date) -> String {
let formatter = getFormatter(forFormat: "MMM d, yyyy, \(DateHelper.correctedSystemHourFormat)")
return formatter.string(from: date)
}
public func formatDayOfWeek(from date: Date) -> String {
let formatter = getFormatter(forFormat: "E")
return formatter.string(from: date)
}
public func formatMonthOfYear(from date: Date) -> String {
let formatter = getFormatter(forFormat: "MMM")
return formatter.string(from: date)
}
func formatLockoutExpirationDate(from date: Date) -> String {
getFormatter(forFormat: "\(DateHelper.correctedSystemHourFormat):mm:ss").string(from: date)
}
func formatSyncedThroughDate(from date: Date) -> String {
getFormatter(forFormat: "yyyy MMM d").string(from: date)
}
func formatDebug(date: Date) -> String {
getFormatter(forFormat: "MM/dd/yy, HH:mm:ss").string(from: date)
}
}
| 36.216216 | 148 | 0.661443 |
e42db7249f374d04120dbdb5a605cf9b43c6b644 | 4,267 | //
// UIImage+.swift
// FSNotes iOS
//
// Created by Oleksandr Glushchenko on 6/5/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import UIKit
extension UIImage {
func alpha(_ value:CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func resize(maxWidthHeight : Double)-> UIImage? {
let actualHeight = Double(size.height)
let actualWidth = Double(size.width)
var maxWidth = 0.0
var maxHeight = 0.0
if actualWidth > actualHeight {
maxWidth = maxWidthHeight
let per = (100.0 * maxWidthHeight / actualWidth)
maxHeight = (actualHeight * per) / 100.0
}else{
maxHeight = maxWidthHeight
let per = (100.0 * maxWidthHeight / actualHeight)
maxWidth = (actualWidth * per) / 100.0
}
let hasAlpha = true
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(CGSize(width: maxWidth, height: maxHeight), !hasAlpha, scale)
self.draw(in: CGRect(origin: .zero, size: CGSize(width: maxWidth, height: maxHeight)))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
return scaledImage
}
func resize(height : Double)-> UIImage? {
let actualHeight = Double(size.height)
let actualWidth = Double(size.width)
var maxWidth = 0.0
var maxHeight = 0.0
var per: Double = 0
if actualWidth < actualHeight {
per = (70 / actualWidth)
maxWidth = (actualWidth * per)
maxHeight = (actualHeight * per)
} else{
per = (70 / actualHeight)
maxWidth = (actualWidth * per)
maxHeight = (actualHeight * per)
}
let newSize = CGSize(width: maxWidth, height: maxHeight)
let renderer = UIGraphicsImageRenderer(size: newSize)
let image = renderer.image { (context) in
self.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
}
return image
}
func croppedInRect(rect: CGRect) -> UIImage {
func rad(_ degree: Double) -> CGFloat {
return CGFloat(degree / 180.0 * .pi)
}
var rectTransform: CGAffineTransform
switch imageOrientation {
case .left:
rectTransform = CGAffineTransform(rotationAngle: rad(90)).translatedBy(x: 0, y: -self.size.height)
case .right:
rectTransform = CGAffineTransform(rotationAngle: rad(-90)).translatedBy(x: -self.size.width, y: 0)
case .down:
rectTransform = CGAffineTransform(rotationAngle: rad(-180)).translatedBy(x: -self.size.width, y: -self.size.height)
default:
rectTransform = .identity
}
rectTransform = rectTransform.scaledBy(x: self.scale, y: self.scale)
let imageRef = self.cgImage!.cropping(to: rect.applying(rectTransform))
let result = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)
return result
}
public func getScale() -> Int {
let actualHeight = Double(size.height)
let actualWidth = Double(size.width)
if actualWidth < actualHeight {
return Int(70 / actualWidth)
} else{
return Int(70 / actualHeight)
}
}
public var jpgData: Data? {
return self.jpegData(compressionQuality: 1)
}
public static func emptyImage(with size: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(size)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func rounded(radius: CGFloat) -> UIImage {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
draw(in: rect)
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
| 34.136 | 127 | 0.613311 |
db852fb4c2e2dd3e8f5cbdd2d24859107c1bfe07 | 1,217 | //
// PreworkTests.swift
// PreworkTests
//
// Created by Rodas Jateno on 04/02/2022.
//
import XCTest
@testable import Prework
class PreworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
// Any test you write for XCTest can be annotated as throws and async.
// Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
// Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 32.891892 | 130 | 0.682827 |
0823f9a7b0f23409c7e9b39b2fcfd9fcd68fea84 | 1,873 | //
// UBLocationManagerProtocol.swift
// UBFoundation iOS Tests
//
// Created by Zeno Koller on 17.01.20.
// Copyright © 2020 Ubique. All rights reserved.
//
import CoreLocation
/// Enables supplying a mock location manager to `UBLocationManager`
public protocol UBLocationManagerProtocol {
// Properties
var location: CLLocation? { get }
var delegate: CLLocationManagerDelegate? { get set }
var distanceFilter: CLLocationDistance { get set }
var desiredAccuracy: CLLocationAccuracy { get set }
var headingFilter: CLLocationDegrees { get set }
var activityType: CLActivityType { get set }
var allowsBackgroundLocationUpdates: Bool { get set }
var pausesLocationUpdatesAutomatically: Bool { get set }
@available(iOS 11.0, *)
var showsBackgroundLocationIndicator: Bool { get set }
// Starting / stopping updates
func startUpdatingLocation()
func stopUpdatingLocation()
func startMonitoringSignificantLocationChanges()
func stopMonitoringSignificantLocationChanges()
func startMonitoringVisits()
func stopMonitoringVisits()
func startUpdatingHeading()
func stopUpdatingHeading()
// Authorization
func requestWhenInUseAuthorization()
func requestAlwaysAuthorization()
func authorizationStatus() -> CLAuthorizationStatus
func locationServicesEnabled() -> Bool
func significantLocationChangeMonitoringAvailable() -> Bool
}
extension CLLocationManager: UBLocationManagerProtocol {
public func authorizationStatus() -> CLAuthorizationStatus {
CLLocationManager.authorizationStatus()
}
public func locationServicesEnabled() -> Bool {
CLLocationManager.locationServicesEnabled()
}
public func significantLocationChangeMonitoringAvailable() -> Bool {
CLLocationManager.significantLocationChangeMonitoringAvailable()
}
}
| 32.859649 | 72 | 0.748532 |
9c784ff5542ebc53674244ec9ef318919a376870 | 2,567 | //
// AddArticleViewController.swift
// Masiuk2021
//
// Created by Anton M on 6/24/21.
//
import UIKit
import Masiuk2021
// MARK: - AddArticle ViewController
class AddArticleViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak private var titleTextField: UITextField!
@IBOutlet weak private var contentTextView: UITextView!
// MARK: - ViewController Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
setupSettings()
setupViews()
}
// MARK: - Setup Methods
private func setupSettings() {
titleTextField.delegate = self
view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing)))
}
private func setupViews() {
contentTextView.textContainer.lineBreakMode = .byTruncatingTail
navigationItem.rightBarButtonItem = UIBarButtonItem(title: Const.AddArticleViewController.barButtontitle,
style: .plain,
target: self, action: #selector(doneEditingArticle))
}
// MARK: - IBActions
@objc private func doneEditingArticle() {
validateAndCreateArticleModel()
}
// MARK: - Private Methods
private func validateAndCreateArticleModel() {
guard let title = titleTextField.text, title != "" else {
presentAlert(message: Const.AddArticleViewController.noTitleMessage)
return
}
guard let content = contentTextView.text, content != "" else {
presentAlert(message: Const.AddArticleViewController.noContentMessage)
return
}
let _ = ArticleManager.shared.newArticle(title: title,
content: content,
language: Const.AddArticleViewController.language,
image: nil)
navigationController?.popViewController(animated: true)
}
private func presentAlert(message: String) {
let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Const.AddArticleViewController.alertActionTitle, style: .cancel, handler: nil))
present(alert, animated: true)
}
}
// MARK: - UITextFieldDelegate Extension
extension AddArticleViewController: UITextFieldDelegate {
internal func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
return updatedText.count <= 20
}
}
| 29.505747 | 118 | 0.719907 |
deb22de7b59ae89b4e9815693c3bbb5997dbdacb | 1,790 | //
// ViewController.swift
// 1002practice2
//
// Created by Maru on 02/10/2018.
// Copyright © 2018 Maru. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var firstLabel: UILabel!
@IBAction func unwindToViewController(_ sender: UIStoryboardSegue) {
guard let sourceVC = sender.source as? SecondViewController else { return }
self.firstLabel.text = "\(Int(sourceVC.secondLabel.text!)! + 10)"
// let destinationViewController = sender.destination
// let sourceViewController = sender.source
// Use data from the view controller which initiated the unwind segue
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// guard let destination = segue.destination as? SecondViewController else { return }
// error
// destination.secondLabel.text = "\(Int(firstLabel.text!)! + 1)"
// ok
// destination.data = Int(firstLabel.text!)! + 1
// segue.destination // second
}
// 조건을 줘서 화면이 더 이상 넘어가지 말지 정해주는 것
// override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// super.shouldPerformSegue(withIdentifier: identifier, sender: sender)
//
//
// return Int(firstLabel.text!)! < 50 ? true : false
//
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 27.538462 | 97 | 0.620112 |
cc7df82d4331d067d413300a757f666943233f25 | 447 | // autogenerated
// swiftlint:disable all
import Foundation
public struct ScmProviderResponse: Hashable, Codable {
public var data: ScmProvider
public var links: DocumentLinks
public init(
data: ScmProvider,
links: DocumentLinks
) {
self.data = data
self.links = links
}
private enum CodingKeys: String, CodingKey {
case data
case links
}
}
// swiftlint:enable all
| 17.192308 | 54 | 0.637584 |
e45873db2abe9e531b67452aeb7af6c3d9dd20cb | 5,864 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import CocoaMarkdown
extension NSColor {
var hex: String {
if let color = self.usingColorSpace(.sRGB) {
return "#" +
String(format: "%X", Int(color.redComponent * 255)) +
String(format: "%X", Int(color.greenComponent * 255)) +
String(format: "%X", Int(color.blueComponent * 255)) +
String(format: "%X", Int(color.alphaComponent * 255))
} else {
return self.description
}
}
func brightening(by factor: CGFloat) -> NSColor {
guard let color = self.usingColorSpace(.sRGB) else {
// TODO: what to do?
return self
}
let h = color.hueComponent
let s = color.saturationComponent
let b = color.brightnessComponent
let a = color.alphaComponent
return NSColor(hue: h, saturation: s, brightness: b * factor, alpha: a)
}
}
extension NSImage {
func tinting(with color: NSColor) -> NSImage {
let result: NSImage = self.copy() as! NSImage
result.lockFocus()
color.set()
CGRect(origin: .zero, size: self.size).fill(using: .sourceAtop)
result.unlockFocus()
return result
}
}
extension NSButton {
var boolState: Bool {
get {
return self.state == .on ? true : false
}
set {
self.state = newValue ? .on : .off
}
}
}
extension NSMenuItem {
var boolState: Bool {
get {
return self.state == .on ? true : false
}
set {
self.state = newValue ? .on : .off
}
}
}
extension NSAttributedString {
func draw(at point: CGPoint, angle: CGFloat) {
var translation = AffineTransform.identity
var rotation = AffineTransform.identity
translation.translate(x: point.x, y: point.y)
rotation.rotate(byRadians: angle)
(translation as NSAffineTransform).concat()
(rotation as NSAffineTransform).concat()
self.draw(at: CGPoint.zero)
rotation.invert()
translation.invert()
(rotation as NSAffineTransform).concat()
(translation as NSAffineTransform).concat()
}
var wholeRange: NSRange {
return NSRange(location: 0, length: self.length)
}
static func infoLabel(markdown: String) -> NSAttributedString {
let size = NSFont.smallSystemFontSize
let document = CMDocument(data: markdown.data(using: .utf8), options: .normalize)
let attrs = CMTextAttributes()
attrs?.textAttributes = [
NSAttributedStringKey.font: NSFont.systemFont(ofSize: size),
NSAttributedStringKey.foregroundColor: NSColor.gray,
]
attrs?.inlineCodeAttributes = [
NSAttributedStringKey.font: NSFont.userFixedPitchFont(ofSize: size)!,
NSAttributedStringKey.foregroundColor: NSColor.gray,
]
let renderer = CMAttributedStringRenderer(document: document, attributes: attrs)
renderer?.register(CMHTMLStrikethroughTransformer())
renderer?.register(CMHTMLSuperscriptTransformer())
renderer?.register(CMHTMLUnderlineTransformer())
guard let result = renderer?.render() else {
preconditionFailure("Wrong markdown: \(markdown)")
}
return result
}
}
extension NSView {
func removeAllSubviews() {
self.subviews.forEach { $0.removeFromSuperview() }
}
func removeAllConstraints() {
self.removeConstraints(self.constraints)
}
@objc var isFirstResponder: Bool {
return self.window?.firstResponder == self
}
func beFirstResponder() {
self.window?.makeFirstResponder(self)
}
}
extension NSTableView {
static func standardTableView() -> NSTableView {
let tableView = NSTableView(frame: CGRect.zero)
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("name"))
column.isEditable = false
tableView.addTableColumn(column)
tableView.rowSizeStyle = .default
tableView.sizeLastColumnToFit()
tableView.allowsEmptySelection = false
tableView.allowsMultipleSelection = false
tableView.headerView = nil
tableView.focusRingType = .none
return tableView
}
static func standardSourceListTableView() -> NSTableView {
let tableView = self.standardTableView()
tableView.selectionHighlightStyle = .sourceList
return tableView
}
}
extension NSOutlineView {
static func standardOutlineView() -> NSOutlineView {
let outlineView = NSOutlineView(frame: CGRect.zero)
NSOutlineView.configure(toStandard: outlineView)
return outlineView
}
static func configure(toStandard outlineView: NSOutlineView) {
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("name"))
column.resizingMask = .autoresizingMask
column.isEditable = false
outlineView.addTableColumn(column)
outlineView.outlineTableColumn = column
outlineView.allowsEmptySelection = false
outlineView.allowsMultipleSelection = false
outlineView.headerView = nil
outlineView.focusRingType = .none
}
/**
The selected item. When the selection is empty, then returns `nil`. When multiple items are selected, then returns
the last selected item.
*/
var selectedItem: Any? {
if self.selectedRow < 0 {
return nil
}
return self.item(atRow: self.selectedRow)
}
var clickedItem: Any? {
if self.clickedRow < 0 {
return nil
}
return self.item(atRow: self.clickedRow)
}
func toggle(item: Any) {
if self.isItemExpanded(item) {
self.collapseItem(item)
} else {
self.expandItem(item)
}
}
}
extension NSScrollView {
static func standardScrollView() -> NSScrollView {
let scrollView = NSScrollView(frame: CGRect.zero)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = true
scrollView.autohidesScrollers = true
scrollView.borderType = .bezelBorder
return scrollView
}
}
| 24.33195 | 117 | 0.687415 |
79e16618c5a740dc8d160363528e326a9444af24 | 264 | //
// Copyright © 2020 Tamas Dancsi. All rights reserved.
//
import SwiftUI
struct FullScreenModalHandlingViewModifier: ViewModifier {
public func body(content: Content) -> some View {
FullScreenModalWrapper {
content
}
}
}
| 17.6 | 58 | 0.651515 |
6131dd9dfc6fa8851ab08b50de447ac85597799b | 5,307 | //
// Created by Swen van Zanten on 25/10/2018.
// Copyright (c) 2018 Verge Currency. All rights reserved.
//
import UIKit
class AbstractContactsTableViewController: UITableViewController {
var contacts: [[Contact]] = []
var letters:[String] = []
let addressBookManager: AddressBookRepository = AddressBookRepository()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if searchController.isActive {
TorStatusIndicator.shared.hide()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
TorStatusIndicator.shared.show()
}
func setupView() {
if addressBookManager.isEmpty() {
if let placeholder = Bundle.main.loadNibNamed(
"NoContactsPlaceholderView",
owner: self,
options: nil
)?.first as? NoContactsPlaceholderView {
placeholder.frame = tableView.frame
tableView.backgroundView = placeholder
tableView.backgroundView?.backgroundColor = ThemeManager.shared.backgroundGrey()
tableView.tableFooterView = UIView()
navigationItem.searchController = nil
}
return
}
tableView.backgroundView = nil
tableView.backgroundView?.backgroundColor = ThemeManager.shared.backgroundGrey()
tableView.tableFooterView = nil
// Setup the Search Controller
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "transactions.contacts.search".localized
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
edgesForExtendedLayout = UIRectEdge.all
extendedLayoutIncludesOpaqueBars = true
// Setup the Scope Bar
searchController.searchBar.delegate = self
searchController.delegate = self
}
func loadContacts(_ searchText: String = "") {
contacts.removeAll()
letters.removeAll()
let addresses = addressBookManager.all().filter { address in
if searchText == "" {
return true
}
return address.address.lowercased().contains(searchText.lowercased())
|| address.name.lowercased().contains(searchText.lowercased())
}
let items = Dictionary(grouping: addresses, by: {
return String($0.name).first?.description ?? ""
}).sorted(by: { $0.key < $1.key })
for item in items {
letters.append(item.key)
contacts.append(item.value.sorted { thule, thule2 in
return thule.name < thule2.name
})
}
}
func sectionLetter(bySection section: Int) -> String {
return letters[section]
}
func contacts(bySection section: Int) -> [Contact] {
return contacts[section]
}
func contact(byIndexpath indexPath: IndexPath) -> Contact {
let items = contacts(bySection: indexPath.section)
return items[indexPath.row]
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return contacts.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return contacts(bySection: section).count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionLetter(bySection: section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "addressBookCell")!
let address = contact(byIndexpath: indexPath)
cell.textLabel?.text = address.name
cell.detailTextLabel?.text = address.address
return cell
}
}
extension AbstractContactsTableViewController: UISearchBarDelegate {
// MARK: - UISearchBar Delegate
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
loadContacts(searchBar.text!)
tableView.reloadData()
}
}
extension AbstractContactsTableViewController: UISearchResultsUpdating, UISearchControllerDelegate {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
loadContacts(searchController.searchBar.text!)
tableView.reloadData()
}
public func willPresentSearchController(_ searchController: UISearchController) {
TorStatusIndicator.shared.hide()
}
public func willDismissSearchController(_ searchController: UISearchController) {
TorStatusIndicator.shared.show()
}
}
| 32.962733 | 109 | 0.666667 |
0e02895d6cece86e6db45931c2786802825d9a12 | 1,177 | //
// Settings.swift
// Nutshell
//
// Created by Brian King on 9/15/15.
// Copyright © 2015 Tidepool. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
class Settings: CommonData {
override class func fromJSON(_ json: JSON, moc: NSManagedObjectContext) -> Settings? {
if let entityDescription = NSEntityDescription.entity(forEntityName: "Settings", in: moc) {
let me = Settings(entity: entityDescription, insertInto: nil)
me.activeSchedule = json["activeSchedule"].string
me.unitsCarb = json["unitsCarb"].string
me.unitsBG = json["unitsBG"].string
me.basalSchedulesJSON = json["basalSchedules"].string
me.carbRatioJSON = json["carbRatio"].string
me.carbRatiosJSON = json["carbRatios"].string
me.insulinSensitivityJSON = json["insulinSensitivity"].string
me.insulinSensitivitiesJSON = json["insulinSensitivities"].string
me.bgTargetJSON = json["bgTarget"].string
me.bgTargetsJSON = json["bgTargets"].string
return me
}
return nil
}
}
| 33.628571 | 99 | 0.631266 |
de9d58c70934571489d37259087e38044fe5490e | 12,804 | //===--------------- JobExecutor.swift - Swift Job Execution --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
import enum TSCUtility.Diagnostics
import Foundation
import Dispatch
public final class MultiJobExecutor {
/// The context required during job execution.
struct Context {
/// This contains mapping from an output to the index(in the jobs array) of the job that produces that output.
let producerMap: [VirtualPath: Int]
/// All the jobs being executed.
let jobs: [Job]
/// The resolver for argument template.
let argsResolver: ArgsResolver
/// The environment variables.
let env: [String: String]
/// The file system.
let fileSystem: FileSystem
/// The job executor delegate.
let executorDelegate: JobExecutionDelegate
/// Queue for executor delegate.
let delegateQueue: DispatchQueue = DispatchQueue(label: "org.swift.driver.job-executor-delegate")
/// Operation queue for executing tasks in parallel.
let jobQueue: OperationQueue
/// The process set to use when launching new processes.
let processSet: ProcessSet?
/// If true, always use response files to pass command line arguments.
let forceResponseFiles: Bool
/// The last time each input file was modified, recorded at the start of the build.
public let recordedInputModificationDates: [TypedVirtualPath: Date]
/// The diagnostics engine to use when reporting errors.
let diagnosticsEngine: DiagnosticsEngine
/// The type to use when launching new processes. This mostly serves as an override for testing.
let processType: ProcessProtocol.Type
init(
argsResolver: ArgsResolver,
env: [String: String],
fileSystem: FileSystem,
producerMap: [VirtualPath: Int],
jobs: [Job],
executorDelegate: JobExecutionDelegate,
jobQueue: OperationQueue,
processSet: ProcessSet?,
forceResponseFiles: Bool,
recordedInputModificationDates: [TypedVirtualPath: Date],
diagnosticsEngine: DiagnosticsEngine,
processType: ProcessProtocol.Type = Process.self
) {
self.producerMap = producerMap
self.jobs = jobs
self.argsResolver = argsResolver
self.env = env
self.fileSystem = fileSystem
self.executorDelegate = executorDelegate
self.jobQueue = jobQueue
self.processSet = processSet
self.forceResponseFiles = forceResponseFiles
self.recordedInputModificationDates = recordedInputModificationDates
self.diagnosticsEngine = diagnosticsEngine
self.processType = processType
}
}
/// The list of jobs that we may need to run.
let jobs: [Job]
/// The argument resolver.
let argsResolver: ArgsResolver
/// The job executor delegate.
let executorDelegate: JobExecutionDelegate
/// The number of jobs to run in parallel.
let numParallelJobs: Int
/// The process set to use when launching new processes.
let processSet: ProcessSet?
/// If true, always use response files to pass command line arguments.
let forceResponseFiles: Bool
/// The last time each input file was modified, recorded at the start of the build.
public let recordedInputModificationDates: [TypedVirtualPath: Date]
/// The diagnostics engine to use when reporting errors.
let diagnosticsEngine: DiagnosticsEngine
/// The type to use when launching new processes. This mostly serves as an override for testing.
let processType: ProcessProtocol.Type
public init(
jobs: [Job],
resolver: ArgsResolver,
executorDelegate: JobExecutionDelegate,
diagnosticsEngine: DiagnosticsEngine,
numParallelJobs: Int? = nil,
processSet: ProcessSet? = nil,
forceResponseFiles: Bool = false,
recordedInputModificationDates: [TypedVirtualPath: Date] = [:],
processType: ProcessProtocol.Type = Process.self
) {
self.jobs = jobs
self.argsResolver = resolver
self.executorDelegate = executorDelegate
self.diagnosticsEngine = diagnosticsEngine
self.numParallelJobs = numParallelJobs ?? 1
self.processSet = processSet
self.forceResponseFiles = forceResponseFiles
self.recordedInputModificationDates = recordedInputModificationDates
self.processType = processType
}
/// Execute all jobs.
public func execute(env: [String: String], fileSystem: FileSystem) throws {
let context = createContext(jobs, env: env, fileSystem: fileSystem)
let delegate = JobExecutorBuildDelegate(context)
let engine = LLBuildEngine(delegate: delegate)
let result = try engine.build(key: ExecuteAllJobsRule.RuleKey())
// Throw the stub error the build didn't finish successfully.
if !result.success {
throw Diagnostics.fatalError
}
}
/// Create the context required during the execution.
func createContext(_ jobs: [Job], env: [String: String], fileSystem: FileSystem) -> Context {
var producerMap: [VirtualPath: Int] = [:]
for (index, job) in jobs.enumerated() {
for output in job.outputs {
assert(!producerMap.keys.contains(output.file), "multiple producers for output \(output): \(job) \(producerMap[output.file]!)")
producerMap[output.file] = index
}
}
let jobQueue = OperationQueue()
jobQueue.name = "org.swift.driver.job-execution"
jobQueue.maxConcurrentOperationCount = numParallelJobs
return Context(
argsResolver: argsResolver,
env: env,
fileSystem: fileSystem,
producerMap: producerMap,
jobs: jobs,
executorDelegate: executorDelegate,
jobQueue: jobQueue,
processSet: processSet,
forceResponseFiles: forceResponseFiles,
recordedInputModificationDates: recordedInputModificationDates,
diagnosticsEngine: diagnosticsEngine,
processType: processType
)
}
}
struct JobExecutorBuildDelegate: LLBuildEngineDelegate {
let context: MultiJobExecutor.Context
init(_ context: MultiJobExecutor.Context) {
self.context = context
}
func lookupRule(rule: String, key: Key) -> Rule {
switch rule {
case ExecuteAllJobsRule.ruleName:
return ExecuteAllJobsRule(key, jobs: context.jobs, fileSystem: context.fileSystem)
case ExecuteJobRule.ruleName:
return ExecuteJobRule(key, context: context)
default:
fatalError("Unknown rule \(rule)")
}
}
}
/// The build value for driver build tasks.
struct DriverBuildValue: LLBuildValue {
enum Kind: String, Codable {
case jobExecution
}
/// If the build value was a success.
var success: Bool
/// The kind of build value.
var kind: Kind
static func jobExecution(success: Bool) -> DriverBuildValue {
return .init(success: success, kind: .jobExecution)
}
}
class ExecuteAllJobsRule: LLBuildRule {
struct RuleKey: LLBuildKey {
typealias BuildValue = DriverBuildValue
typealias BuildRule = ExecuteAllJobsRule
}
override class var ruleName: String { "\(ExecuteAllJobsRule.self)" }
private let key: RuleKey
private let jobs: [Job]
/// True if any of the inputs had any error.
private var allInputsSucceeded: Bool = true
init(_ key: Key, jobs: [Job], fileSystem: FileSystem) {
self.key = RuleKey(key)
self.jobs = jobs
super.init(fileSystem: fileSystem)
}
override func start(_ engine: LLTaskBuildEngine) {
for index in jobs.indices {
let key = ExecuteJobRule.RuleKey(index: index)
engine.taskNeedsInput(key, inputID: index)
}
}
override func isResultValid(_ priorValue: Value) -> Bool {
return false
}
override func provideValue(_ engine: LLTaskBuildEngine, inputID: Int, value: Value) {
do {
let buildValue = try DriverBuildValue(value)
allInputsSucceeded = allInputsSucceeded && buildValue.success
} catch {
allInputsSucceeded = false
}
}
override func inputsAvailable(_ engine: LLTaskBuildEngine) {
engine.taskIsComplete(DriverBuildValue.jobExecution(success: allInputsSucceeded))
}
}
class ExecuteJobRule: LLBuildRule {
struct RuleKey: LLBuildKey {
typealias BuildValue = DriverBuildValue
typealias BuildRule = ExecuteJobRule
let index: Int
}
override class var ruleName: String { "\(ExecuteJobRule.self)" }
private let key: RuleKey
private let context: MultiJobExecutor.Context
/// True if any of the inputs had any error.
private var allInputsSucceeded: Bool = true
init(_ key: Key, context: MultiJobExecutor.Context) {
self.key = RuleKey(key)
self.context = context
super.init(fileSystem: context.fileSystem)
}
override func start(_ engine: LLTaskBuildEngine) {
for (idx, input) in context.jobs[key.index].inputs.enumerated() {
if let producingJobIndex = context.producerMap[input.file] {
let key = ExecuteJobRule.RuleKey(index: producingJobIndex)
engine.taskNeedsInput(key, inputID: idx)
}
}
}
override func isResultValid(_ priorValue: Value) -> Bool {
return false
}
override func provideValue(_ engine: LLTaskBuildEngine, inputID: Int, value: Value) {
do {
let buildValue = try DriverBuildValue(value)
allInputsSucceeded = allInputsSucceeded && buildValue.success
} catch {
allInputsSucceeded = false
}
}
override func inputsAvailable(_ engine: LLTaskBuildEngine) {
// Return early any of the input failed.
guard allInputsSucceeded else {
return engine.taskIsComplete(DriverBuildValue.jobExecution(success: false))
}
context.jobQueue.addOperation {
self.executeJob(engine)
}
}
private func executeJob(_ engine: LLTaskBuildEngine) {
let context = self.context
let resolver = context.argsResolver
let job = context.jobs[key.index]
let env = context.env.merging(job.extraEnvironment, uniquingKeysWith: { $1 })
let value: DriverBuildValue
var pid = 0
do {
let arguments: [String] = try resolver.resolveArgumentList(for: job,
forceResponseFiles: context.forceResponseFiles)
try job.verifyInputsNotModified(since: context.recordedInputModificationDates, fileSystem: engine.fileSystem)
let process = try context.processType.launchProcess(
arguments: arguments, env: env
)
pid = Int(process.processID)
// Add it to the process set if it's a real process.
if case let realProcess as TSCBasic.Process = process {
try context.processSet?.add(realProcess)
}
// Inform the delegate.
context.delegateQueue.async {
context.executorDelegate.jobStarted(job: job, arguments: arguments, pid: pid)
}
let result = try process.waitUntilExit()
let success = result.exitStatus == .terminated(code: EXIT_SUCCESS)
if !success {
switch result.exitStatus {
case let .terminated(code):
if !job.kind.isCompile || code != EXIT_FAILURE {
context.diagnosticsEngine.emit(.error_command_failed(kind: job.kind, code: code))
}
case let .signalled(signal):
context.diagnosticsEngine.emit(.error_command_signalled(kind: job.kind, signal: signal))
}
}
// Inform the delegate about job finishing.
context.delegateQueue.async {
context.executorDelegate.jobFinished(job: job, result: result, pid: pid)
}
value = .jobExecution(success: success)
} catch {
if error is DiagnosticData {
context.diagnosticsEngine.emit(error)
}
context.delegateQueue.async {
let result = ProcessResult(
arguments: [],
environment: env,
exitStatus: .terminated(code: EXIT_FAILURE),
output: Result.success([]),
stderrOutput: Result.success([])
)
context.executorDelegate.jobFinished(job: job, result: result, pid: 0)
}
value = .jobExecution(success: false)
}
engine.taskIsComplete(value)
}
}
extension Job: LLBuildValue { }
private extension Diagnostic.Message {
static func error_command_failed(kind: Job.Kind, code: Int32) -> Diagnostic.Message {
.error("\(kind.rawValue) command failed with exit code \(code) (use -v to see invocation)")
}
static func error_command_signalled(kind: Job.Kind, signal: Int32) -> Diagnostic.Message {
.error("\(kind.rawValue) command failed due to signal \(signal) (use -v to see invocation)")
}
}
| 31.693069 | 135 | 0.691815 |
23ef6b74671c19db3327b4448d3f1c6d3e888ba9 | 8,765 | /*
*
* Copyright 2018 APPNEXUS 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 XCTest
class ANInstreamVideoAdTestCase: XCTestCase, ANInstreamVideoAdLoadDelegate {
var instreamVideoAd: ANInstreamVideoAd!
var expectationLoadVideoAd: XCTestExpectation!
var request: URLRequest!
var jsonRequestBody = [String : Any]()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
ANHTTPStubbingManager.shared().enable()
ANHTTPStubbingManager.shared().ignoreUnstubbedRequests = true
ANHTTPStubbingManager.shared().broadcastRequests = true
NotificationCenter.default.addObserver(self, selector: #selector(self.requestCompleted(_:)), name: NSNotification.Name.anhttpStubURLProtocolRequestDidLoad, object: nil)
request = nil
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
instreamVideoAd = nil
expectationLoadVideoAd = nil
ANHTTPStubbingManager.shared().disable()
ANHTTPStubbingManager.shared().removeAllStubs()
ANHTTPStubbingManager.shared().broadcastRequests = false
ANSDKSettings.sharedInstance().httpsEnabled = false
NotificationCenter.default.removeObserver(self)
}
func requestCompleted(_ notification: Notification?) {
var incomingRequest = notification?.userInfo![kANHTTPStubURLProtocolRequest] as? URLRequest
let requestString = incomingRequest?.url?.absoluteString
let searchString = ANSDKSettings.sharedInstance().baseUrlConfig.utAdRequestBaseUrl()
if request == nil && requestString?.range(of:searchString!) != nil{
request = notification!.userInfo![kANHTTPStubURLProtocolRequest] as? URLRequest
jsonRequestBody = ANHTTPStubbingManager.jsonBodyOfURLRequest(asDictionary: request) as! [String : Any]
}
}
// MARK: - Test methods.
//Test video duration of InstreamVideoAd
func test_TC32_AdDuration() {
initializeInstreamVideoWithAllProperties()
print("reached here")
XCTAssertNotNil(instreamVideoAd)
let duration = instreamVideoAd.getDuration()
XCTAssertNotEqual(duration, 0)
}
//Test without setting the video duration of InstreamVideoAd
func test_TC33_AdDurationNotSet() {
initializeInstreamVideoWithNoProperties()
XCTAssertNotNil(instreamVideoAd)
let duration = instreamVideoAd.getDuration()
XCTAssertEqual(duration, 0)
}
//Test vast url content of InstreamVideoAd
func test_TC34_VastCreativeURL() {
initializeInstreamVideoWithAllProperties()
print("reached here")
XCTAssertNotNil(instreamVideoAd)
let vastcreativeTag = instreamVideoAd.getVastURL()
XCTAssertNotNil(vastcreativeTag)
XCTAssertNotEqual(vastcreativeTag?.count, 0)
XCTAssertNotNil(vastcreativeTag)
XCTAssertEqual(vastcreativeTag, "http://sampletag.com")
}
//Test without setting vast url content of InstreamVideoAd
func test_TC35_VastCreativeValuesNotSet() {
initializeInstreamVideoWithNoProperties()
XCTAssertNotNil(instreamVideoAd)
let vastcreativeTag = instreamVideoAd.getVastURL()
XCTAssertEqual(vastcreativeTag?.count, 0)
}
//Test vast xml content of InstreamVideoAd
func test_TC36_VastCreativeXML() {
initializeInstreamVideoWithAllProperties()
XCTAssertNotNil(instreamVideoAd)
let vastcreativeXMLTag = instreamVideoAd.getVastXML()
XCTAssertNotNil(vastcreativeXMLTag)
XCTAssertNotEqual(vastcreativeXMLTag?.count, 0)
XCTAssertNotNil(vastcreativeXMLTag)
XCTAssertEqual(vastcreativeXMLTag, "http://sampletag.com")
}
//Test without setting the vast xml content of InstreamVideoAd
func test_TC37_VastCreativeXMLValuesNotSet() {
initializeInstreamVideoWithNoProperties()
XCTAssertNotNil(instreamVideoAd)
let vastcreativeXMLTag = instreamVideoAd.getVastXML()
XCTAssertEqual(vastcreativeXMLTag?.count, 0)
}
//Test creative tag of InstreamVideoAd
func test_TC38_CreativeTag() {
initializeInstreamVideoWithAllProperties()
XCTAssertNotNil(instreamVideoAd)
let creativeTag = instreamVideoAd.getCreativeURL()
XCTAssertNotEqual(creativeTag?.count, 0)
XCTAssertNotNil(creativeTag)
XCTAssertEqual(creativeTag, "http://sampletag.com")
}
//Test without setting the creative tag of InstreamVideoAd
func test_TC39_CreativeValuesNotSet() {
initializeInstreamVideoWithNoProperties()
XCTAssertNotNil(instreamVideoAd)
let creativeTag = instreamVideoAd.getCreativeURL()
XCTAssertEqual(creativeTag?.count, 0)
}
//Test play head time for InstreamVideoAd
func test_TC40_PlayHeadTimeForVideoSet() {
initializeInstreamVideoWithNoProperties()
XCTAssertNotNil(instreamVideoAd)
let duration = instreamVideoAd.getPlayElapsedTime()
XCTAssertNotEqual(duration, 0)
}
//Test creative tag of InstreamVideoAd
func test_TC63_CustomKeywordsAdded() {
instreamVideoAd = ANInstreamVideoAd(placementId: "12534678")
instreamVideoAd.addCustomKeyword(withKey: "force_creative_id", value: "123456789")
stubRequestWithResponse("SuccessfulInstreamVideoAdResponse")
instreamVideoAd.load(with: self)
expectationLoadVideoAd = expectation(description: "\(#function)")
waitForExpectations(timeout: 30, handler: nil)
XCTAssertEqual(instreamVideoAd.placementId, "12534678")
if let arr = jsonRequestBody["keywords"] as? [Any], let dic = arr[0] as? [String : Any], let key = dic["key"] as? String
{
XCTAssertEqual(key, "force_creative_id")
}
if let arr = jsonRequestBody["keywords"] as? [Any], let dic = arr[0] as? [String : Any], let arr2 = dic["value"] as? [Any], let value = arr2[0] as? String
{
XCTAssertEqual(value, "123456789")
}
}
// MARK: - Helper methods.
func initializeInstreamVideoWithAllProperties() {
instreamVideoAd = ANInstreamVideoAd()
instreamVideoAd.adPlayer = ANVideoAdPlayer()
instreamVideoAd.adPlayer.videoDuration = 10
instreamVideoAd.adPlayer.creativeURL = "http://sampletag.com"
instreamVideoAd.adPlayer.vastURLContent = "http://sampletag.com"
instreamVideoAd.adPlayer.vastXMLContent = "http://sampletag.com"
}
func initializeInstreamVideoWithNoProperties() {
instreamVideoAd = ANInstreamVideoAd()
instreamVideoAd.adPlayer = ANVideoAdPlayer()
}
// MARK: - Stubbing
func stubRequestWithResponse(_ responseName: String?) {
let currentBundle = Bundle(for: type(of: self))
let baseResponse = try? String(contentsOfFile: currentBundle.path(forResource: responseName, ofType: "json") ?? "", encoding: .utf8)
let requestStub = ANURLConnectionStub()
requestStub.requestURL = ANSDKSettings.sharedInstance().baseUrlConfig.utAdRequestBaseUrl()
requestStub.responseCode = 200
requestStub.responseBody = baseResponse
ANHTTPStubbingManager.shared().add(requestStub)
}
@objc func fulfillExpectation(_ expectation: XCTestExpectation?) {
expectation?.fulfill()
}
func waitForTimeInterval(_ delay: TimeInterval) {
let expectation: XCTestExpectation = self.expectation(description: "wait")
perform(#selector(self.fulfillExpectation(_:)), with: expectation, afterDelay: delay)
waitForExpectations(timeout: TimeInterval(delay + 1), handler: nil)
}
// MARK: - ANInstreamVideoAdLoadDelegate.
func adDidReceiveAd(_ ad: ANAdProtocol!) {
expectationLoadVideoAd.fulfill()
}
func ad(_ ad: Any!, requestFailedWithError error: Error!)
{
print(error.localizedDescription)
}
}
| 41.150235 | 176 | 0.695608 |
69c5672a9f8ceade04d6a1db73eb504f3833a299 | 331 | //
// UITableColumn.swift
// UITable
//
// Created by Yasin Akbaş on 9/23/20.
//
import Foundation
public struct UITableColumn {
let title: String
let values: [UITableCellContent]
public init(title: String = "", values: [UITableCellContent]) {
self.title = title
self.values = values
}
}
| 17.421053 | 67 | 0.628399 |
1c03f6afc124dfce0457c658f8bb87bdd578c125 | 4,634 | //
// FlagNode.swift
// SCNGeometries-Part2
//
// Created by Max Cobb on 30/10/2018.
// Copyright © 2018 Max Cobb. All rights reserved.
//
import SceneKit
class FlagNode: SCNNode {
private var xyCount: CGSize
private var geometrySize: CGSize
private var vertices: [SCNVector3]
private var timer: Timer? = nil
private var indices: SCNGeometryElement
var material = SCNMaterial()
private var textureCoord: SCNGeometrySource
private var flagAction: SCNAction!
/// Create a plane of width, height, vertex count and material diffuse
///
/// - Parameters:
/// - frameSize: physical width and height of the geometry
/// - xyCount: number of horizontal and vertical vertices
/// - diffuse: diffuse to be applied to the geometry; a color, image, or source of animated content.
public init(frameSize: CGSize, xyCount: CGSize, diffuse: Any? = UIColor.white) {
let (verts, textureMap, inds) = SCNGeometry.PlaneParts(size: frameSize, xyCount: xyCount)
self.xyCount = xyCount
self.textureCoord = textureMap
self.geometrySize = frameSize
self.indices = inds
self.vertices = verts
super.init()
self.updateGeometry()
self.flagAction = SCNAction.customAction(duration: 100000) { (_, elapsedTime) in
// using duration: Double.infinity or Double.greatestFiniteMagnitude breaks `elapsedTime`
// I'll try find some alternative that's nicer than `100000` later
self.animateFlagXY(elapsedTime: elapsedTime)
}
self.material.diffuse.contents = diffuse
self.runAction(SCNAction.repeatForever(self.flagAction))
}
/// Update the geometry of this node with the vertices, texture coordinates and indices
private func updateGeometry() {
let src = SCNGeometrySource(vertices: vertices)
let geo = SCNGeometry(sources: [src, self.textureCoord], elements: [self.indices])
geo.materials = [self.material]
self.geometry = geo
}
// I appreciate the next few functions are not very DRY, it's annoying me (author)
// but am keeping the math clear for the tutorial
/// Wave the flag using just the x coordinate
///
/// - Parameter elapsedTime: time since animation started [0-duration] in seconds
private func animateFlag(elapsedTime: CGFloat) {
let yCount = Int(xyCount.height)
let xCount = Int(xyCount.width)
let furthest = Float((yCount - 1) + (xCount - 1))
let tNow = elapsedTime
let waveScale = Float(0.1 * (min(tNow / 10, 1)))
for x in 0..<xCount {
let distance = Float(x) / furthest
let newZ = waveScale * (sinf(15 * (Float(tNow) - distance)) * distance)
// only the x position is effecting the translation here,
// that's why we calculate before going to the second while loop
for y in 0..<yCount {
self.vertices[y * xCount + x].z = newZ
}
}
self.updateGeometry()
}
/// Wave the flag, using x and y coordinates
///
/// - Parameter elapsedTime: time since animation started [0-duration] in seconds
private func animateFlagXY(elapsedTime: CGFloat) {
let yCount = Int(xyCount.height)
let xCount = Int(xyCount.width)
let furthest = Float((yCount - 1) + (xCount - 1))
let tNow = elapsedTime
let waveScale = Float(0.1 * (min(tNow / 10, 1)))
for x in 0..<xCount {
let distanceX = Float(x) / furthest
for y in 0..<yCount {
let distance = distanceX + Float(y) / furthest
let newZ = waveScale * (sinf(15 * (Float(tNow) - distance)) * distanceX)
self.vertices[y * xCount + x].z = newZ
}
}
self.updateGeometry()
}
/// Wave the flag looks a little crazy but interesting to watch
///
/// - Parameter elapsedTime: time since animation started [0-duration] in seconds
private func animateFlagMadness(elapsedTime: CGFloat) {
let yCount = Int(xyCount.height)
let xCount = Int(xyCount.width)
let furthest = sqrt(Float((yCount - 1)*(yCount - 1) + (xCount - 1)*(xCount - 1)))
let tNow = elapsedTime
let waveScale = Float(0.1 * (min(tNow / 10, 1)))
for x in 0..<xCount {
let distanceX = Float(x) / Float(xCount - 1)
for y in 0..<yCount {
let distance = Float(x * x + y * y) / furthest
let newZ = waveScale * (sinf(15 * (Float(tNow) - distance)) * distanceX)
self.vertices[y * xCount + x].z = newZ
}
}
self.updateGeometry()
}
/// Adds a shader to the geometry instead of an animation
private func addShader() {
let waveShader = "_geometry.position.z = " +
"0.1 *" +
" sin(15 * (u_time - _geometry.position.x))" +
" * (0.5 + _geometry.position.x / \(self.geometrySize.width)); \n"
self.geometry?.shaderModifiers = [SCNShaderModifierEntryPoint.geometry: waveShader]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 35.922481 | 103 | 0.693353 |
48a3e06668117d72131695834ccf7ae284c7916d | 1,835 | //
// BloodPressureSysPublisher.swift
// WatchLandmarks Extension
//
// Created by Christian Bartram on 5/6/20.
// Copyright © 2020 Apple. All rights reserved.
//
import Foundation
import HealthKit
class BloodPressureSysPublisher: WebSocketPublisher, Publisher {
func publish(healthStore: HKHealthStore) {
guard let bloodPressureType = HKSampleType.quantityType(forIdentifier: .bloodPressureSystolic) else {
fatalError("*** This method should never fail ***")
}
let query = HKObserverQuery(sampleType: bloodPressureType, predicate: nil) { (query, completionHandler, errorOrNil) in
if let error = errorOrNil {
print("Error thrown when executing HK Observer query: ", error)
return
}
let anchorQuery = HKAnchoredObjectQuery(type: bloodPressureType, predicate: nil, anchor: nil, limit: HKObjectQueryNoLimit) { (query, samplesOrNil, deletedObjectsOrNil, newAnchor, errorOrNil) in
guard let samples = samplesOrNil as? [HKQuantitySample] else {
return
}
if(samples.endIndex > 0) {
let lastSample = samples[samples.endIndex - 1]
let sampleValue = lastSample.quantity.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
let roundedValue = Double(round( 1 * sampleValue ) / 1)
print("Publishing Blood Pressure Systolic value: ", roundedValue)
self.publishMetric(forMetric: HKQuantityTypeIdentifier.bloodPressureSystolic, value: roundedValue)
}
}
healthStore.execute(anchorQuery)
}
healthStore.execute(query)
}
}
| 41.704545 | 205 | 0.608719 |
5b676e82faf8936be0c5d32d41c651ff144a4af9 | 363 | //
// testCollectionReusableView.swift
// YXWCustomCollectionLayout
//
// Created by 原晓文 on 2017/11/22.
// Copyright © 2017年 原晓文. All rights reserved.
//
import UIKit
class testCollectionReusableView: UICollectionReusableView {
@IBOutlet weak var contentLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
| 18.15 | 60 | 0.69697 |
14b7ba1125cc6f1a707ce38e427c89d8bcde3735 | 1,253 | //
// KaeruDemoUITests.swift
// KaeruDemoUITests
//
// Created by Hirose.Yudai on 2017/03/09.
// Copyright © 2017年 Hirose.Yudai. All rights reserved.
//
import XCTest
class KaeruDemoUITests: 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.864865 | 182 | 0.664804 |
7aee06e634ae37192f9824ef08d1ffd8754cd440 | 1,273 | import UIKit
public struct Edge: Equatable {
let layoutAttribute: NSLayoutConstraint.Attribute
let insetMultiplier: CGFloat
public static let top = Edge(layoutAttribute: .top, insetMultiplier: 1)
public static let bottom = Edge(layoutAttribute: .bottom, insetMultiplier: -1)
public static let leading = Edge(layoutAttribute: .leading, insetMultiplier: 1)
public static let trailing = Edge(layoutAttribute: .trailing, insetMultiplier: -1)
public static let all: [Edge] = [.top, .bottom, .leading, .trailing]
func offset(equivalentToInset inset: CGFloat) -> CGFloat {
return inset * insetMultiplier
}
}
internal extension NSLayoutConstraint.Axis {
var from: Edge {
switch self {
case .horizontal:
return .leading
case .vertical:
return .top
@unknown default:
fatalError("NovodaConstraints internal error - \(self) is an unknown axis")
}
}
var to: Edge {
switch self {
case .horizontal:
return .trailing
case .vertical:
return .bottom
@unknown default:
fatalError("NovodaConstraints internal error - \(self) is an unknown axis")
}
}
}
| 28.931818 | 87 | 0.62608 |
72891b1ccfcf7010151c69dd2533edc1ffcba9f9 | 385 | @propertyWrapper
public struct Inject<T> {
@Lazy
private var value: T
public init(resolver: Resolver) {
assert(resolver.isAdded(T.self))
$value = resolver.resolve
}
public var wrappedValue: T {
get { value }
set { value = newValue }
}
public var projectedValue: T? {
get { value }
set {
if let validValue = newValue {
value = validValue
}
}
}
}
| 14.807692 | 34 | 0.636364 |
ac48201000db543167b6cf618d4e3837dfe65410 | 16,686 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A utility class that provides processed depth information.
*/
import Foundation
import SwiftUI
import Combine
import ARKit
import Accelerate
import MetalPerformanceShaders
// Wrap the `MTLTexture` protocol to reference outputs from ARKit.
final class MetalTextureContent {
var texture: MTLTexture?
}
// Enable `CVPixelBuffer` to output an `MTLTexture`.
extension CVPixelBuffer {
func texture(withFormat pixelFormat: MTLPixelFormat, planeIndex: Int, addToCache cache: CVMetalTextureCache) -> MTLTexture? {
let width = CVPixelBufferGetWidthOfPlane(self, planeIndex)
let height = CVPixelBufferGetHeightOfPlane(self, planeIndex)
var cvtexture: CVMetalTexture?
_ = CVMetalTextureCacheCreateTextureFromImage(nil, cache, self, nil, pixelFormat, width, height, planeIndex, &cvtexture)
let texture = CVMetalTextureGetTexture(cvtexture!)
return texture
}
}
// Collect AR data using a lower-level receiver. This class converts AR data
// to a Metal texture, optionally upscaling depth data using a guided filter,
// and implements `ARDataReceiver` to respond to `onNewARData` events.
final class ARProvider: ARDataReceiver, ObservableObject {
// Set the destination resolution for the upscaled algorithm.
let upscaledWidth = 960
let upscaledHeight = 760
// Set the original depth size.
let origDepthWidth = 256
let origDepthHeight = 192
// Set the original color size.
let origColorWidth = 1920
let origColorHeight = 1440
// Set the guided filter constants.
let guidedFilterEpsilon: Float = 0.004
let guidedFilterKernelDiameter = 5
let arReceiver = ARReceiver()
@Published var lastArData: ARData?
let depthContent = MetalTextureContent()
let confidenceContent = MetalTextureContent()
let colorYContent = MetalTextureContent()
let colorCbCrContent = MetalTextureContent()
let upscaledCoef = MetalTextureContent()
let downscaledRGB = MetalTextureContent()
let upscaledConfidence = MetalTextureContent()
let coefTexture: MTLTexture
let destDepthTexture: MTLTexture
let destConfTexture: MTLTexture
let colorRGBTexture: MTLTexture
let colorRGBTextureDownscaled: MTLTexture
let colorRGBTextureDownscaledLowRes: MTLTexture
// Enable or disable depth upsampling.
public var isToUpsampleDepth: Bool = false {
didSet {
processLastArData()
}
}
// Enable or disable smoothed-depth upsampling.
public var isUseSmoothedDepthForUpsampling: Bool = false {
didSet {
processLastArData()
}
}
var textureCache: CVMetalTextureCache?
let metalDevice: MTLDevice?
let guidedFilter: MPSImageGuidedFilter?
let mpsScaleFilter: MPSImageBilinearScale?
let commandQueue: MTLCommandQueue?
var pipelineStateCompute: MTLComputePipelineState?
// Create an empty texture.
static func createTexture(metalDevice: MTLDevice, width: Int, height: Int, usage: MTLTextureUsage, pixelFormat: MTLPixelFormat) -> MTLTexture {
let descriptor: MTLTextureDescriptor = MTLTextureDescriptor()
descriptor.pixelFormat = pixelFormat
descriptor.width = width
descriptor.height = height
descriptor.usage = usage
let resTexture = metalDevice.makeTexture(descriptor: descriptor)
return resTexture!
}
// Start or resume the stream from ARKit.
func start() {
arReceiver.start()
}
// Pause the stream from ARKit.
func pause() {
arReceiver.pause()
}
// Initialize the MPS filters, metal pipeline, and Metal textures.
init?() {
do {
metalDevice = MTLCreateSystemDefaultDevice()
CVMetalTextureCacheCreate(nil, nil, metalDevice!, nil, &textureCache)
guidedFilter = MPSImageGuidedFilter(device: metalDevice!, kernelDiameter: guidedFilterKernelDiameter)
guidedFilter?.epsilon = guidedFilterEpsilon
mpsScaleFilter = MPSImageBilinearScale(device: metalDevice!)
commandQueue = metalDevice!.makeCommandQueue()
let lib = metalDevice!.makeDefaultLibrary()
let convertYUV2RGBFunc = lib!.makeFunction(name: "convertYCbCrToRGBA")
pipelineStateCompute = try metalDevice!.makeComputePipelineState(function: convertYUV2RGBFunc!)
// Initialize the working textures.
coefTexture = ARProvider.createTexture(metalDevice: metalDevice!, width: origDepthWidth, height: origDepthHeight,
usage: [.shaderRead, .shaderWrite], pixelFormat: .rgba32Float)
destDepthTexture = ARProvider.createTexture(metalDevice: metalDevice!, width: upscaledWidth, height: upscaledHeight,
usage: [.shaderRead, .shaderWrite], pixelFormat: .r32Float)
destConfTexture = ARProvider.createTexture(metalDevice: metalDevice!, width: upscaledWidth, height: upscaledHeight,
usage: [.shaderRead, .shaderWrite], pixelFormat: .r8Unorm)
colorRGBTexture = ARProvider.createTexture(metalDevice: metalDevice!, width: origColorWidth, height: origColorHeight,
usage: [.shaderRead, .shaderWrite], pixelFormat: .rgba32Float)
colorRGBTextureDownscaled = ARProvider.createTexture(metalDevice: metalDevice!, width: upscaledWidth, height: upscaledHeight,
usage: [.shaderRead, .shaderWrite], pixelFormat: .rgba32Float)
colorRGBTextureDownscaledLowRes = ARProvider.createTexture(metalDevice: metalDevice!, width: origDepthWidth, height: origDepthHeight,
usage: [.shaderRead, .shaderWrite], pixelFormat: .rgba32Float)
upscaledCoef.texture = coefTexture
upscaledConfidence.texture = destConfTexture
downscaledRGB.texture = colorRGBTextureDownscaled
// Set the delegate for ARKit callbacks.
arReceiver.delegate = self
} catch {
print("Unexpected error: \(error).")
return nil
}
}
// Save a reference to the current AR data and process it.
func onNewARData(arData: ARData) {
//Lines 159 - 168 are for printing the depth at a single point
let depthPixelBuffer = arData.depthImage
let point = CGPoint(x: 35, y: 25)
let width = CVPixelBufferGetWidth(depthPixelBuffer!)
let height = CVPixelBufferGetHeight(depthPixelBuffer!)
CVPixelBufferLockBaseAddress(depthPixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
let depthPointer = unsafeBitCast(CVPixelBufferGetBaseAddress(depthPixelBuffer!), to: UnsafeMutablePointer<Float32>.self)
let distanceAtXYPoint = depthPointer[Int(point.y * CGFloat(width) + point.x)]
// Uncomment the below line to print the distance at a single pixel to the console.
// print(distanceAtXYPoint)
//Lines 172 - 195 are for exporting depth data to a csv
func convert(length: Int, data: UnsafeMutablePointer<Float32>) -> [Float32] {
let buffer = UnsafeBufferPointer(start: data, count: length);
return Array(buffer)
}
let depthPointerArray = convert(length: 49152, data: depthPointer)
let depthPointArraySeperated = (depthPointerArray.map{String($0)}).joined(separator:",\n")
let fileName = "depthData.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Point\n"
print("Creating csv text")
//uncomment below line to see how the depth data is stored
// print(depthPointArraySeperated)
csvText.append(depthPointArraySeperated)
// print(csvText)
print("Starting to write...")
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print(path ?? "not found")
print("Write complete")
//Process color
let colorImage = arData.capturedImage
CVPixelBufferLockBaseAddress(colorImage!, CVPixelBufferLockFlags(rawValue: 0))
let colorPointer = unsafeBitCast(CVPixelBufferGetBaseAddress(colorImage!), to: UnsafeMutablePointer<Float32>.self)
let colorAtXYPoint = colorPointer[Int(point.y * CGFloat(width) + point.x)]
let colorWidth1 = CVPixelBufferGetWidth(colorImage!)
let colorHeight1 = CVPixelBufferGetHeight(colorImage!)
//Lines 212 - 213 are for processing the extrinsic matrix. Uncomment line 213 to get it for every frame
let cameraExtrinsics = arData.cameraExtrinsics
// print(cameraExtrinsics)
//Lines 216 - 217 are for processing euler angles. Uncomment line 217 to get it for every frame
let eulerAngles = arData.eulerAngles
// print(eulerAngles)
// let colorRGBTexture = ARProvider.createTexture(metalDevice: metalDevice!, width: origColorWidth, height: origColorHeight,
// usage: [.shaderRead, .shaderWrite], pixelFormat: .rgba32Float)
//
// let colorWidth = colorRGBTexture.width
// let colorHeight = colorRGBTexture.height
// let bytesPerRow = colorWidth * 4
//
// let data = UnsafeMutableRawPointer.allocate(byteCount: bytesPerRow * colorHeight, alignment: 4)
// defer {
// data.deallocate(bytes: bytesPerRow * colorHeight, alignedTo: 4)
// }
// func getDocumentsDirectory() -> URL {
// let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
// return paths[0]
// }
// func textureToImage(texture: MTLTexture) -> Void {
// let kciOptions: [CIImageOption:Any] = [.colorSpace: CGColorSpaceCreateDeviceRGB()]
// let ciImage = CIImage(mtlTexture: texture, options: kciOptions)!
// let transform = CGAffineTransform.identity
// .scaledBy(x: 1, y: -1)
// .translatedBy(x: 0, y: ciImage.extent.height)
// let transformed = ciImage.transformed(by: transform)
//
// let image = UIImage(ciImage: transformed)
// print(image.pngData())
// if let data = image.pngData() {
// let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
// try? data.write(to: filename)
// }
//
//// let image = UIImage(ciImage: transformed)
//// if let data = image.jpegData(compressionQuality: 0.8) {
//// let filename = getDocumentsDirectory().appendingPathComponent("copy.jpeg")
//// try? data.write(to: filename)
//// }
// }
// let pngData = textureToImage(texture: colorRGBTexture)
// print(pngData)
// let region = MTLRegionMake2D(0, 0, colorWidth, colorHeight)
// let realData = colorRGBTexture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
//
// print(realData)
// colorRGBTexture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
// let bind = data.assumingMemoryBound(to: UInt8.self)
//
// print(bind)
// CVPixelBufferLockBaseAddress(colorRGBTexture!, CVPixelBufferLockFlags(rawValue: 0))
// let rgbPointer = unsafeBitCast(CVPixelBufferGetBaseAddress(colorImage!), to: UnsafeMutablePointer<Float32>.self)
// let rgbColorAtXYPoint = rgbPointer[Int(point.y * CGFloat(width) + point.x)]
// print("color", rgbColorAtXYPoint)
//
// print("colorBuffer:", colorRGBTexture)
// print(arData.depthImage as Any)
// CVPixelBufferLockBaseAddress(arData.depthImage!, .readOnly)
// print(CVPixelBufferGetBaseAddress(arData.depthImage!))
// CVPixelBufferUnlockBaseAddress(arData.depthImage!, .readOnly)
lastArData = arData
processLastArData()
}
// Copy the AR data to Metal textures and, if the user enables the UI, upscale the depth using a guided filter.
func processLastArData() {
colorYContent.texture = lastArData?.colorImage?.texture(withFormat: .r8Unorm, planeIndex: 0, addToCache: textureCache!)!
colorCbCrContent.texture = lastArData?.colorImage?.texture(withFormat: .rg8Unorm, planeIndex: 1, addToCache: textureCache!)!
if isUseSmoothedDepthForUpsampling {
depthContent.texture = lastArData?.depthSmoothImage?.texture(withFormat: .r32Float, planeIndex: 0, addToCache: textureCache!)!
confidenceContent.texture = lastArData?.confidenceSmoothImage?.texture(withFormat: .r8Unorm, planeIndex: 0, addToCache: textureCache!)!
} else {
depthContent.texture = lastArData?.depthImage?.texture(withFormat: .r32Float, planeIndex: 0, addToCache: textureCache!)!
confidenceContent.texture = lastArData?.confidenceImage?.texture(withFormat: .r8Unorm, planeIndex: 0, addToCache: textureCache!)!
}
if isToUpsampleDepth {
guard let commandQueue = commandQueue else { return }
guard let cmdBuffer = commandQueue.makeCommandBuffer() else { return }
guard let computeEncoder = cmdBuffer.makeComputeCommandEncoder() else { return }
// Convert YUV to RGB because the guided filter needs RGB format.
computeEncoder.setComputePipelineState(pipelineStateCompute!)
computeEncoder.setTexture(colorYContent.texture, index: 0)
computeEncoder.setTexture(colorCbCrContent.texture, index: 1)
computeEncoder.setTexture(colorRGBTexture, index: 2)
let threadgroupSize = MTLSizeMake(pipelineStateCompute!.threadExecutionWidth,
pipelineStateCompute!.maxTotalThreadsPerThreadgroup / pipelineStateCompute!.threadExecutionWidth, 1)
let threadgroupCount = MTLSize(width: Int(ceil(Float(colorRGBTexture.width) / Float(threadgroupSize.width))),
height: Int(ceil(Float(colorRGBTexture.height) / Float(threadgroupSize.height))),
depth: 1)
computeEncoder.dispatchThreadgroups(threadgroupCount, threadsPerThreadgroup: threadgroupSize)
computeEncoder.endEncoding()
// print(colorRGBTexture)
// Downscale the RGB data. Pass in the target resoultion.
mpsScaleFilter?.encode(commandBuffer: cmdBuffer, sourceTexture: colorRGBTexture,
destinationTexture: colorRGBTextureDownscaled)
// Match the input depth resolution.
mpsScaleFilter?.encode(commandBuffer: cmdBuffer, sourceTexture: colorRGBTexture,
destinationTexture: colorRGBTextureDownscaledLowRes)
// Upscale the confidence data. Pass in the target resolution.
mpsScaleFilter?.encode(commandBuffer: cmdBuffer, sourceTexture: confidenceContent.texture!,
destinationTexture: destConfTexture)
// Encode the guided filter.
guidedFilter?.encodeRegression(to: cmdBuffer, sourceTexture: depthContent.texture!,
guidanceTexture: colorRGBTextureDownscaledLowRes, weightsTexture: nil,
destinationCoefficientsTexture: coefTexture)
// Optionally, process `coefTexture` here.
guidedFilter?.encodeReconstruction(to: cmdBuffer, guidanceTexture: colorRGBTextureDownscaled,
coefficientsTexture: coefTexture, destinationTexture: destDepthTexture)
cmdBuffer.commit()
// Override the original depth texture with the upscaled version.
depthContent.texture = destDepthTexture
}
}
}
| 48.365217 | 147 | 0.643114 |
29b71356cc4138b65d909b211668c421cab23c44 | 2,450 | /*
SBDownload.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 Foundation
class SBDownload: NSObject {
var identifier: Int = -1
private var _name: String?
var name: String? {
get {
return _name ?? URL?.absoluteString
}
set(name) { _name = name }
}
var URL: NSURL? {
return download?.request.URL
}
var download: NSURLDownload?
var path: String?
var bytes: String?
var downloading = false
var receivedLength: Int = 0
var expectedLength: Int = 0
var status: SBStatus = .Processing
convenience init(URL: NSURL) {
let download = NSURLDownload(request: NSURLRequest(URL: URL), delegate: SBDownloads.sharedDownloads)
self.init(download: download)
}
init(download: NSURLDownload) {
self.download = download
downloading = true
}
var progress: Float {
return (status == .Done) ? 1.0 : ((expectedLength == 0) ? 0 : Float(receivedLength) / Float(expectedLength))
}
// MARK: Actions
func stop() {
download?.cancel()
download = nil
downloading = false
}
} | 34.027778 | 116 | 0.710612 |
b92d0aec9f690ff23163bf0d718c2aff1ed0e656 | 219 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
&[_?
| 31.285714 | 87 | 0.744292 |
18affde00fb82696fb1bf2200c12cecae1aa53de | 1,607 | //
// MockCollectionViewCell.swift
// RecipeBookTests
//
// Created by Christian Slanzi on 09.05.21.
//
import Foundation
import XCTest
@testable import RecipeBook
/*
class MockCollectionViewCell: CollectionViewCellProtocol {
var expectationForLoadImage: (XCTestExpectation, String?)?
var expectationForSetCaption: (XCTestExpectation, String?)?
var expectationForSetupRecipeDetails: (XCTestExpectation, String?)?
func loadImage(resourceName: String) {
guard let (expectation, expectedValue) = self.expectationForLoadImage else {
return
}
if let expectedValue = expectedValue {
if (resourceName.compare(expectedValue) != .orderedSame) {
return
}
}
expectation.fulfill()
}
func setCaption(captionText:String) {
guard let (expectation, expectedValue) = self.expectationForSetCaption else {
return
}
if let expectedValue = expectedValue {
if (captionText.compare(expectedValue) != .orderedSame) {
return
}
}
expectation.fulfill()
}
func setRecipeDetails(recipeDetailsText: String) {
guard let (expectation, expectedValue) = self.expectationForSetupRecipeDetails else {
return
}
if let expectedValue = expectedValue {
if (recipeDetailsText.compare(expectedValue) != .orderedSame) {
return
}
}
expectation.fulfill()
}
}
*/
| 25.919355 | 93 | 0.598631 |
e6f7ce77c4453ceb149d3dbbe6901127b2e2a895 | 102 | import XCTest
@testable import RingBufferTests
XCTMain([
testCase(RingBufferTests.allTests),
])
| 14.571429 | 40 | 0.77451 |
dbe17c9f838e597b9464b25ca7f29a3eeca8c8b2 | 3,034 | //
// DevicesView.swift
// Blue-Falcon
//
// Created by Andrew Reed on 16/08/2019.
// Copyright © 2019 Andrew Reed. All rights reserved.
//
import SwiftUI
import BlueFalcon
import Combine
struct DevicesView : View {
@ObservedObject var viewModel = DevicesViewModel()
var body: some View {
NavigationView {
VStack(alignment: .leading) {
HStack {
Text("Bluetooth Status:")
Text(viewModel.status == .scanning ? "Scanning" : "Not Scanning")
if viewModel.status == .scanning {
ActivityIndicator(isAnimating: .constant(true), style: .medium)
}
}.padding()
List(viewModel.devicesViewModels) { deviceViewModel in
NavigationLink(
destination: DeviceView(
deviceViewModel: DeviceViewModel(
device: deviceViewModel.device
)
)
) {
DevicesViewCell(
name: deviceViewModel.name,
deviceId: deviceViewModel.id
)
}
}
.navigationBarTitle(Text("Blue Falcon Devices"))
}
.onAppear {
self.viewModel.onAppear()
self.scan()
}
.onDisappear {
self.viewModel.onDisapear()
}
}
.colorScheme(.dark)
}
//the old way would be to perform this in the uiview controller.
private func scan() {
do {
try viewModel.scan()
} catch {
let error = error as NSError
switch error.userInfo["KotlinException"] {
case is BluetoothPermissionException:
showError(message: Strings.Errors.Bluetooth.permission)
case is BluetoothNotEnabledException:
showError(message: Strings.Errors.Bluetooth.notEnabled)
case is BluetoothUnsupportedException:
showError(message: Strings.Errors.Bluetooth.unsupported)
case is BluetoothResettingException:
showError(message: Strings.Errors.Bluetooth.resetting)
default:
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.scan()
}
}
}
}
private func showError(message: String) {
let alert = UIAlertController(
title: "Bluetooth Error",
message: message,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
SceneDelegate.instance.window?.rootViewController?.present(alert, animated: true)
}
}
#if DEBUG
struct DevicesView_Previews : PreviewProvider {
static var previews: some View {
DevicesView()
}
}
#endif
| 31.604167 | 89 | 0.518128 |
c1bf3cb6ff22aefb41d6783312753502767a1749 | 3,898 | // Copyright (c) 2016-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
import Instructions
// Controller used to test Instructions behavior during background fetches.
// Unleash the Network Link Conditioner!
internal class BackgroundNetworkingViewController: DefaultViewController {
// MARK: - Private properties
private lazy var urlSession: Foundation.URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: "BackgroundNetworking")
configuration.sessionSendsLaunchEvents = true
configuration.isDiscretionary = true
return Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}()
private var downloadTask: URLSessionDownloadTask?
var stopInstructions: Bool = false
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
coachMarksController.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
stopInstructions = false
startDownload()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopInstructions = true
}
// MARK: - Internal Methods
override func startInstructions() {
// Do nothing and override super.
}
func startDownload() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
if let url = URL(string: "https://ephread.com/assets/videos/instructions.mp4") {
downloadTask = urlSession.downloadTask(with: url)
downloadTask?.resume()
}
}
// MARK: CoachMarksControllerDelegate
override func coachMarksController(_ coachMarksController: CoachMarksController,
willShow coachMark: inout CoachMark,
beforeChanging change: ConfigurationChange,
at index: Int) {
if index == 2 && change == .nothing {
coachMarksController.flow.pause()
startDownload()
}
}
}
// MARK: - NSURLSessionDownloadDelegate
extension BackgroundNetworkingViewController: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Finished.")
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if self.stopInstructions { return }
if !self.coachMarksController.flow.isStarted {
self.coachMarksController.start(in: .window(over: self))
} else {
self.coachMarksController.flow.resume()
}
}
}
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
let size = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite,
countStyle: ByteCountFormatter.CountStyle.binary)
print(String(format: "%.1f%% of %@", progress * 100, size))
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
guard let completionHandler = appDelegate.backgroundSessionCompletionHandler else { return }
appDelegate.backgroundSessionCompletionHandler = nil
DispatchQueue.main.async(execute: {
completionHandler()
})
}
}
| 35.436364 | 120 | 0.658543 |
2166e424c4471f31ddc4eb94e5d9d62f8eab27d5 | 279 | //
// MockResource.swift
// TABResourceLoaderTests
//
// Created by Luciano Marisi on 10/09/2016.
// Copyright © 2016 Kin + Carta. All rights reserved.
//
import Foundation
@testable import TABResourceLoader
struct MockResource: ResourceType {
typealias Model = String
}
| 18.6 | 54 | 0.738351 |
4a91f55c1c36584b31c42ccdebf3092155c8ae3b | 8,560 | // RUN: %target-parse-verify-swift
infix operator ==== {}
infix operator <<<< {}
infix operator <><> {}
// <rdar://problem/13782566>
// Check that func op<T>() parses without a space between the name and the
// generic parameter list.
func ====<T>(x: T, y: T) {}
func <<<<<T>(x: T, y: T) {}
func <><><T>(x: T, y: T) {}
//===--- Check that we recover when the parameter tuple is missing.
func recover_missing_parameter_tuple_1 { // expected-error {{expected '(' in argument list of function declaration}}
}
func recover_missing_parameter_tuple_1a // expected-error {{expected '(' in argument list of function declaration}}
{
}
func recover_missing_parameter_tuple_2<T> { // expected-error {{expected '(' in argument list of function declaration}} expected-error {{generic parameter 'T' is not used in function signature}}
}
func recover_missing_parameter_tuple_3 -> Int { // expected-error {{expected '(' in argument list of function declaration}}
}
func recover_missing_parameter_tuple_4<T> -> Int { // expected-error {{expected '(' in argument list of function declaration}} expected-error {{generic parameter 'T' is not used in function signature}}
}
//===--- Check that we recover when the function return type is missing.
// Note: Don't move braces to a different line here.
func recover_missing_return_type_1() -> // expected-error {{expected type for function result}}
{
}
func recover_missing_return_type_2() -> // expected-error {{expected type for function result}} expected-error{{expected '{' in body of function declaration}}
// Note: Don't move braces to a different line here.
func recover_missing_return_type_3 -> // expected-error {{expected '(' in argument list of function declaration}} expected-error {{expected type for function result}}
{
}
//===--- Check that we recover if ':' was used instead of '->' to specify the return type.
func recover_colon_arrow_1() : Int { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=->}}
func recover_colon_arrow_2() : { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=->}} expected-error {{expected type for function result}}
func recover_colon_arrow_3 : Int { } // expected-error {{expected '->' after function parameter tuple}} {{28-29=->}} expected-error {{expected '(' in argument list of function declaration}}
func recover_colon_arrow_4 : { } // expected-error {{expected '->' after function parameter tuple}} {{28-29=->}} expected-error {{expected '(' in argument list of function declaration}} expected-error {{expected type for function result}}
//===--- Check that we recover if the function does not have a body, but the
//===--- context requires the function to have a body.
func recover_missing_body_1() // expected-error {{expected '{' in body of function declaration}}
func recover_missing_body_2() // expected-error {{expected '{' in body of function declaration}}
-> Int
// Ensure that we don't skip over the 'func g' over to the right paren in
// function g, while recovering from parse error in f() parameter tuple. We
// should produce the error about missing right paren.
//
// FIXME: The errors are awful. We should produce just the error about paren.
func f_recover_missing_tuple_paren(a: Int // expected-error {{expected parameter type following ':'}} expected-note {{to match this opening '('}} expected-error{{expected '{' in body of function declaration}} expected-error {{expected ')' in parameter}} expected-error 2{{expected ',' separator}} {{42-42=,}} {{42-42=,}}
func g_recover_missing_tuple_paren(b: Int) {
}
//===--- Parse errors.
func parseError1a(a: ) {} // expected-error {{type annotation missing in pattern}} expected-error {{expected parameter type following ':'}}
func parseError1b(a: // expected-error {{type annotation missing in pattern}} expected-error {{expected parameter type following ':'}}
) {}
func parseError2(a: Int, b: ) {} // expected-error {{type annotation missing in pattern}} expected-error {{expected parameter type following ':'}}
func parseError3(a: unknown_type, b: ) {} // expected-error {{use of undeclared type 'unknown_type'}} expected-error {{type annotation missing in pattern}} expected-error {{expected parameter type following ':'}}
func parseError4(a: , b: ) {} // expected-error 2{{type annotation missing in pattern}} expected-error 2{{expected parameter type following ':'}}
func parseError5(a: b: ) {} // expected-error {{use of undeclared type 'b'}} expected-error 2{{expected ',' separator}} {{22-22=,}} {{22-22=,}} expected-error {{expected parameter type following ':'}}
func parseError6(a: unknown_type, b: ) {} // expected-error {{use of undeclared type 'unknown_type'}} expected-error {{type annotation missing in pattern}} expected-error {{expected parameter type following ':'}}
func parseError7(a: Int, goo b: unknown_type) {} // expected-error {{use of undeclared type 'unknown_type'}}
public func foo(a: Bool = true) -> (b: Bar, c: Bar) {} // expected-error {{use of undeclared type 'Bar'}}
// expected-error@+1{{unnamed parameters must be written}} {{24-24=_: }}
func parenPatternInArg((a): Int) -> Int { // expected-error {{use of undeclared type 'a'}} expected-error 2{{expected ',' separator}} {{27-27=,}} {{27-27=,}} expected-error {{expected parameter type following ':'}}
return a
}
parenPatternInArg(0)
var nullaryClosure: Int -> Int = {_ in 0}
nullaryClosure(0)
// rdar://16737322 - This argument is an unnamed argument that has a labeled
// tuple type as the type. Because the labels are in the type, they are not
// parameter labels, and they are thus not in scope in the body of the function.
// expected-error@+1{{unnamed parameters must be written}} {{27-27=_: }}
func destructureArgument( (result: Int, error: Bool) ) -> Int {
return result // expected-error {{use of unresolved identifier 'result'}}
}
// The former is the same as this:
func destructureArgument2(a: (result: Int, error: Bool) ) -> Int {
return result // expected-error {{use of unresolved identifier 'result'}}
}
class ClassWithObjCMethod {
@objc
func someMethod(x : Int) {}
}
func testObjCMethodCurry(a : ClassWithObjCMethod) -> (Int) -> () {
return a.someMethod
}
// We used to crash on this.
func rdar16786220(var let c: Int) -> () { // expected-error {{Use of 'var' binding here is not allowed}} {{19-22=}} expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}}
var c = c
c = 42
_ = c
}
// <rdar://problem/17763388> ambiguous operator emits same candidate multiple times
infix operator !!! {}
func !!!<T>(lhs: Array<T>, rhs: Array<T>) -> Bool { return false }
func !!!<T>(lhs: UnsafePointer<T>, rhs: UnsafePointer<T>) -> Bool { return false }
[1] !!! [1] // unambiguously picking the array overload.
// <rdar://problem/16786168> Functions currently permit 'var inout' parameters
func inout_inout_error(inout inout x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{30-36=}}
// expected-error@+1 {{Use of 'var' binding here is not allowed}} {{22-25=}}
func var_inout_error(var inout x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{26-32=}}
var x = x
x = 2
_ = x
}
// Unnamed parameters require the name "_":
func unnamed(Int) { } // expected-error{{unnamed parameters must be written with the empty name '_'}}{{14-14=_: }}
// Test fixits on curried functions.
func testCurryFixits() {
func f1(x: Int)(y: Int) {} // expected-warning{{curried function declaration syntax will be removed in a future version of Swift; use a single parameter list}} {{17-19=, }}
func f1a(x: Int, y: Int) {}
func f2(x: Int)(y: Int)(z: Int) {} // expected-warning{{curried function declaration syntax will be removed in a future version of Swift; use a single parameter list}} {{17-19=, }} {{25-27=, }}
func f2a(x: Int, y: Int, z: Int) {}
func f3(x: Int)() {} // expected-warning{{curried function declaration syntax will be removed in a future version of Swift; use a single parameter list}} {{17-19=}}
func f3a(x: Int) {}
func f4()(x: Int) {} // expected-warning{{curried function declaration syntax will be removed in a future version of Swift; use a single parameter list}} {{11-13=}}
func f4a(x: Int) {}
func f5(x: Int)()(y: Int) {} // expected-warning{{curried function declaration syntax will be removed in a future version of Swift; use a single parameter list}} {{17-19=}} {{19-21=, }}
func f5a(x: Int, y: Int) {}
}
| 52.195122 | 320 | 0.695678 |
fc1da7fe74351deba0dae692637a34fcd9540627 | 2,186 | //
// AppDelegate.swift
// PODDIGIPROSDK
//
// Created by AlexArroyo2104 on 07/25/2019.
// Copyright (c) 2019 AlexArroyo2104. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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.510638 | 285 | 0.755718 |
f4cf51cf681e8ea614469ce3ae2c3427ea93aff8 | 7,747 | //
// AdUnitTableViewController.swift
//
// Copyright 2018-2021 Twitter, Inc.
// Licensed under the MoPub SDK License Agreement
// http://www.mopub.com/legal/sdk-license-agreement/
//
import UIKit
import AVFoundation
struct AdUnitTableViewControllerSegueIdentifier {
static let ModallyPresentCameraInterfaceSegueIdentifier = "modallyPresentCameraInterfaceViewController"
static let ModallyPresentManualEntryInterfaceSegueIdentifier = "modallyPresentManualEntryInterfaceViewController"
}
class AdUnitTableViewController: UIViewController {
// Outlets from `Main.storyboard`
@IBOutlet weak var tableView: UITableView!
@IBOutlet var addButton: UIBarButtonItem?
@IBOutlet weak var drawerButton: UIBarButtonItem!
// Table data source.
internal var dataSource: AdUnitDataSource? = nil
// MARK: - Initialization
/**
Initializes the view controller's data source. This must be performed before
`viewDidLoad()` is called.
- Parameter dataSource: Data source for the view controller.
*/
func initialize(with dataSource: AdUnitDataSource) {
self.dataSource = dataSource
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Register reusable table cells and delegates
AdUnitTableViewCell.register(with: tableView)
AdUnitTableViewHeader.register(with: tableView)
tableView.dataSource = self
tableView.delegate = self
// Set up background color for Dark Mode
if #available(iOS 13.0, *) {
tableView.dragDelegate = self
view.backgroundColor = .systemBackground
tableView.backgroundColor = .systemBackground
}
}
// MARK: - Ad Loading
public func loadAd(with adUnit: AdUnit) {
guard let vcClass = NSClassFromString(adUnit.viewControllerClassName) as? AdViewController.Type,
let destination: UIViewController = vcClass.instantiateFromNib(adUnit: adUnit) as? UIViewController else {
return
}
// Push the destination ad view controller onto the navigation stack.
navigationController?.pushViewController(destination, animated: true)
}
/**
Reloads the data source's data and refreshes the table view with the updated
contents.
*/
public func reloadData() {
dataSource?.reloadData()
tableView.reloadData()
}
// MARK: - IBActions
@IBAction func drawerButtonAction(_ sender: Any) {
containerViewController?.swipeMenuOpen(sender)
}
@IBAction func addButtonAction(_ sender: Any) {
let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: QRCodeCameraInterfaceViewController.defaultMediaType)
let showCameraButton = cameraAuthorizationStatus == .authorized || cameraAuthorizationStatus == .notDetermined ? true : false
// If camera use is not authorized, show the manual interface without giving a choice
if !showCameraButton {
performSegue(withIdentifier: AdUnitTableViewControllerSegueIdentifier.ModallyPresentManualEntryInterfaceSegueIdentifier, sender: self)
return
}
// If camera use is authorized, show action sheet with a choice between manual interface and camera interface
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Enter Ad Unit ID Manually", style: .default, handler: { [unowned self] _ in
self.performSegue(withIdentifier: AdUnitTableViewControllerSegueIdentifier.ModallyPresentManualEntryInterfaceSegueIdentifier, sender: self)
}))
actionSheet.addAction(UIAlertAction(title: "Use QR Code", style: .default, handler: { [unowned self] _ in
self.performSegue(withIdentifier: AdUnitTableViewControllerSegueIdentifier.ModallyPresentCameraInterfaceSegueIdentifier, sender: self)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let popoverPresentationController = actionSheet.popoverPresentationController {
guard let barButtonItem = sender as? UIBarButtonItem else {
assertionFailure("\(#function) sender is not `UIBarButtonItem` as expected")
return
}
// ADF-4094: app will crash if popover source is not set for popover presentation
popoverPresentationController.barButtonItem = barButtonItem
}
present(actionSheet, animated: true, completion: nil)
}
}
extension AdUnitTableViewController: UITableViewDataSource {
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource?.sections.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource?.items(for: section)?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let adUnit: AdUnit = dataSource?.item(at: indexPath) else {
return UITableViewCell()
}
let adUnitCell = tableView.dequeueCellFromNib(cellType: AdUnitTableViewCell.self)
adUnitCell.accessibilityIdentifier = adUnit.id
adUnitCell.refresh(adUnit: adUnit)
adUnitCell.setNeedsLayout()
return adUnitCell
}
}
extension AdUnitTableViewController: UITableViewDelegate {
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Intentionally not to deselect cell to help user to keep track of the long list
guard let adUnit: AdUnit = dataSource?.item(at: indexPath) else {
return
}
loadAd(with: adUnit)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header: AdUnitTableViewHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: AdUnitTableViewHeader.reuseId) as? AdUnitTableViewHeader,
let title = dataSource?.sections[section] else {
return nil
}
header.refresh(title: title)
return header
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 8 // leave some space between section headers if a section is below an empty section
}
}
// MARK: - UITableViewDragDelegate
@available(iOS 11, *)
extension AdUnitTableViewController: UITableViewDragDelegate {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
// Drag & Drop is available since iOS 11, but multi-scene is available since iOS 13.
guard
#available(iOS 13, *),
let adUnit: AdUnit = dataSource?.item(at: indexPath)else {
return []
}
let itemProvider = NSItemProvider()
itemProvider.registerObject(adUnit.openAdViewActivity , visibility: .all)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = adUnit
return [dragItem]
}
}
| 39.126263 | 165 | 0.683232 |
4a7b1e15ec49e8328a5a8212079bde762e5455d3 | 3,698 | //
// CaptureViewController.swift
// CPUInstagramUsingParse
//
// Created by Juan Hernandez on 3/5/16.
// Copyright © 2016 ccsf. All rights reserved.
//
import UIKit
import Parse
class CaptureViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var displayedImageView: UIImageView!
@IBOutlet weak var captionTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
// let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
// view.addGestureRecognizer(tap)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogOut(sender: AnyObject) {
PFUser.logOut()
//AppDelegate.onLogOut
}
@IBAction func onSelecting(sender: AnyObject) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
vc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(vc, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage
// Do something with the images (based on your use case)
displayedImageView.image = editedImage
// Dismiss UIImagePickerController to go back to your original view controller
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func onSubmit(sender: AnyObject) {
//Resizing the image required by Parse
let newImage = resize(displayedImageView.image!, newSize: CGSize(width: 300, height: 500))
Post.postUserImage(newImage, withCaption: captionTextField.text!) { (success: Bool, erro: NSError?) -> Void in
// code
if success{
print("Posted")
self.displayedImageView.image = nil
self.captionTextField.text = nil
} else {
print("not posted")
}
}
}
func resize(image: UIImage, newSize: CGSize) -> UIImage {
let resizeImageView = UIImageView(frame: CGRectMake(0, 0, newSize.width, newSize.height))
resizeImageView.contentMode = UIViewContentMode.ScaleAspectFill
resizeImageView.image = image
UIGraphicsBeginImageContext(resizeImageView.frame.size)
resizeImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
/*
// 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.
}
*/
}
| 31.87931 | 118 | 0.637642 |
bbfcfb66fe13a4ace08f6bab8658a5258dcf2c67 | 1,639 | //
// apiRequest.swift
//
//
// Created by Tomasz on 02/03/2021.
//
import Foundation
import SwiftUI
import SwiftyJSON
import KeychainAccess
@available (iOS 14, macOS 11, watchOS 7, tvOS 14, *)
public func apiRequest(endpointURL: String, id: String) -> URLRequest {
var request = URLRequest(url: URL(string: endpointURL)!)
request.httpMethod = "GET"
let keychain = Keychain()
let account = keychain[id] ?? "[]"
let data = Data(account.utf8)
let accountJSON = try! JSON(data: data)
let fingerprint: String = "\(accountJSON["fingerprint"])"
let privateKeyStringString: String = "\(accountJSON["privateKeyString"])"
let privateKeyString: Data = Data(privateKeyStringString.utf8)
let deviceModel: String = "\(accountJSON["deviceModel"])"
let now = Date()
var vDate: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return "\(dateFormatter.string(from: now)) GMT"
}
let signatures = getSignatures(request: request, fingerprint: fingerprint, privateKeyString: privateKeyString)
request.setValue("\(signatures)", forHTTPHeaderField: "Signature")
request.allHTTPHeaderFields = [
"User-Agent": "wulkanowy/1 CFNetwork/1220.1 Darwin/20.1.0",
"vOS": "iOS",
"vDeviceModel": deviceModel,
"vAPI": "1",
"vDate": vDate,
"vCanonicalUrl": "api%2fmobile%2fregister%2fhebe"
]
return request
}
| 29.8 | 114 | 0.655278 |
71c68d0a9d5b1575899e2f51dfa02f67704c01d4 | 3,230 | //
// Copyright (c) 2019 Plausible Labs Cooperative, Inc.
// All rights reserved.
//
import Combine
import SwiftUI
import PLRelational
import PLRelationalCombine
final class DetailViewModel: ObservableObject {
private let model: Model
let tagsViewModel: TagsViewModel
@TwoWay(onSet: .commit) var itemCompleted: Bool = false
@TwoWay var itemTitle: String = ""
@Published var itemTags: String = ""
@TwoWay var itemNotes: String = ""
@Published var createdOn: String = ""
private var cancellableBag = CancellableBag()
init(model: Model) {
self.model = model
// TODO: Initialize this lazily?
self.tagsViewModel = TagsViewModel(model: model)
// REQ-7
// The item's completion status. This is a two-way property that
// is backed by UndoableDatabase.
model.selectedItems
.project(Item.completed)
.bind(to: \._itemCompleted, on: self, strategy: model.itemCompleted())
.store(in: &cancellableBag)
// REQ-8
// The item's title. This is a two-way property that is backed
// by UndoableDatabase, so any changes made to it in the text field
// can be rolled back by the user.
model.selectedItems
.project(Item.title)
.bind(to: \._itemTitle, on: self, strategy: model.itemTitle())
.store(in: &cancellableBag)
// REQ-10
// The tags associated with the selected to-do item, sorted by name.
model.tagsForSelectedItem
.sortedStrings(for: Tag.name)
.replaceError(with: [])
.map{ $0.joined(separator: ", ") }
.bind(to: \.itemTags, on: self)
.store(in: &cancellableBag)
// REQ-11
// The item's notes. This is a two-way property that is backed
// by UndoableDatabase, so any changes made to it in the text view
// can be rolled back by the user.
model.selectedItems
.project(Item.notes)
.bind(to: \._itemNotes, on: self, strategy: model.itemNotes())
.store(in: &cancellableBag)
// REQ-12
// The text that appears in the "Created on <date>" label. This
// demonstrates the use of `map` to convert the raw timestamp string
// (as stored in the relation) to a display-friendly string.
model.selectedItems
.project(Item.created)
.oneString()
.replaceError(with: "unknown date")
.map{ "Created on \(displayString(from: $0))".uppercased() }
.bind(to: \.createdOn, on: self)
.store(in: &cancellableBag)
}
deinit {
cancellableBag.cancel()
}
/// REQ-8
/// Commits the current value of `itemTitle` to the underlying relation. This should be
/// called from the associated TextField's `onCommit` function.
func commitItemTitle() {
_itemTitle.commit()
}
/// REQ-11
/// Commits the current value of `itemNotes` to the underlying relation. This should be
/// called from the associated TextView's `onCommit` function.
func commitItemNotes() {
_itemNotes.commit()
}
}
| 33.298969 | 92 | 0.603715 |
1e825abdda04024977c7a8f457ce8a7caab6f38b | 377 | //
// MockTraitCollection.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-19.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
class MockTraitCollection: UITraitCollection {
var userInterfaceStyleValue: UIUserInterfaceStyle = .light
override var userInterfaceStyle: UIUserInterfaceStyle { userInterfaceStyleValue }
}
| 22.176471 | 85 | 0.745358 |
0a35b3ce6aebedd80704d5c64d0efe04c428eb3a | 1,579 | //
// VTViewController.swift
// VirtualTourist
//
// Implements shared methods used by VT View Controllers to update the UI in order to prevent the user from modifying the data model while it's still being updated elsewhere. For example, images may still be downloading in the background context, so we don't want to allow the user to delete items, which would cause the context to save while it's in a possibly invalid state.
//
// If subclasses use the willLoadFromNetwork and didLoadFromNetwork methods, they must call super. They can check the downloadsActive property to determine whether to enable or disable UI elements.
//
// Created by Chris Leung on 5/13/17.
// Copyright © 2017 Chris Leung. All rights reserved.
//
import UIKit
class VTViewController: UIViewController {
var numActiveDownloads = 0
var downloadsActive = false
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(VTViewController.willLoadFromNetwork(_:)), name: Notification.Name("willDownloadData"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(VTViewController.didLoadFromNetwork(_:)), name: Notification.Name("didDownloadData"), object: nil)
}
func willLoadFromNetwork(_ notification:Notification) {
numActiveDownloads += 1
downloadsActive = true
}
func didLoadFromNetwork(_ notification:Notification) {
numActiveDownloads -= 1
if numActiveDownloads == 0 {
downloadsActive = false
}
}
}
| 41.552632 | 377 | 0.727042 |
d7cdb4bed5e6b496dc9f230d4a764cbec8d4b005 | 2,760 | //
// CGGeometry+Additions.swift
// DLSuggestionsTextField
//
// Created by David Livadaru on 08/07/16.
// Copyright © 2016 Community. All rights reserved.
//
import CoreGraphics
public protocol CeilApplicable {
mutating func ceil()
func ceiling() -> Self
}
extension CeilApplicable {
mutating public func ceil() {
self = ceiling()
}
}
public protocol FloorApplicable {
mutating func floor()
func floored() -> Self
}
extension FloorApplicable {
mutating public func floor() {
self = floored()
}
}
public protocol RoundApplicable {
mutating func round()
func rounded() -> Self
}
extension RoundApplicable {
mutating public func round() {
self = rounded()
}
}
extension CGRect: RoundApplicable, FloorApplicable, CeilApplicable {
public func ceiling() -> CGRect {
return CGRect(x: Darwin.ceil(self.origin.x), y: Darwin.ceil(origin.y),
width: Darwin.ceil(width), height: Darwin.ceil(height))
}
public func floored() -> CGRect {
return CGRect(x: Darwin.floor(self.origin.x), y: Darwin.floor(origin.y),
width: Darwin.floor(width), height: Darwin.floor(height))
}
public func rounded() -> CGRect {
return CGRect(x: Darwin.round(self.origin.x), y: Darwin.round(origin.y),
width: Darwin.round(width), height: Darwin.round(height))
}
}
extension CGSize: RoundApplicable, FloorApplicable, CeilApplicable {
public func ceiling() -> CGSize {
return CGSize(width: Darwin.ceil(width), height: Darwin.ceil(height))
}
public func floored() -> CGSize {
return CGSize(width: Darwin.floor(width), height: Darwin.floor(height))
}
public func rounded() -> CGSize {
return CGSize(width: Darwin.round(width), height: Darwin.round(height))
}
}
extension CGPoint: RoundApplicable, FloorApplicable, CeilApplicable {
public func ceiling() -> CGPoint {
return CGPoint(x: Darwin.ceil(x), y: Darwin.ceil(y))
}
public func floored() -> CGPoint {
return CGPoint(x: Darwin.floor(x), y: Darwin.floor(y))
}
public func rounded() -> CGPoint {
return CGPoint(x: Darwin.round(x), y: Darwin.round(y))
}
}
extension CGRect {
mutating public func insetBy(point: CGPoint) {
insetBy(dx: point.x, dy: point.y)
}
public func insetedBy(point: CGPoint) -> CGRect {
var rect = self
rect.insetBy(point: point)
return rect
}
mutating public func insetUsing(insets: UIEdgeInsets) {
self = insetedUsing(insets: insets)
}
public func insetedUsing(insets: UIEdgeInsets) -> CGRect {
return UIEdgeInsetsInsetRect(self, insets)
}
}
| 25.555556 | 80 | 0.636232 |
5d841b1dc6a76dd81434f3b0eb6d56b3305a8d05 | 8,789 | //
// Copyright © 2020 Anonyome Labs, Inc. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
import SudoLogging
import AWSCognitoIdentityProvider
/// Identity provider that uses Cognito user pool.
public class CognitoUserPoolIdentityProvider: IdentityProvider {
/// Configuration parameter names.
public struct Config {
// AWS region hosting Secure Vault service.
static let region = "region"
// AWS Cognito user pool ID of Secure Vault service.
static let poolId = "poolId"
// ID of the client configured to access the user pool.
static let clientId = "clientId"
}
private struct Constants {
static let secureVaultServiceName = "com.sudoplatform.securevaultservice"
struct ServiceError {
static let message = "message"
static let decodingError = "sudoplatform.DecodingError"
static let serviceError = "sudoplatform.ServiceError"
static let alreadyRegisteredError = "sudoplatform.vault.AlreadyRegistered"
}
struct ValidationData {
static let idToken = "idToken"
static let authenticationSalt = "authenticationSalt"
static let encryptionSalt = "encryptionSalt"
static let pbkdfRounds = "pbkdfRounds"
}
}
private var userPool: AWSCognitoIdentityUserPool
private var serviceConfig: AWSServiceConfiguration
private unowned var logger: Logger
/// Initializes and returns a `CognitoUserPoolIdentityProvider` object.
///
/// - Parameters:
/// - config: Configuration parameters for this identity provider.
/// - logger: Logger used for logging.
init(config: [String: Any],
logger: Logger = Logger.sudoSecureVaultLogger) throws {
self.logger = logger
self.logger.debug("Initializing with config: \(config)")
// Validate the config.
guard let region = config[Config.region] as? String,
let poolId = config[Config.poolId] as? String,
let clientId = config[Config.clientId] as? String else {
throw IdentityProviderError.invalidConfig
}
guard let regionType = AWSEndpoint.regionTypeFrom(name: region) else {
throw IdentityProviderError.invalidConfig
}
// Initialize the user pool instance.
guard let serviceConfig = AWSServiceConfiguration(region: regionType, credentialsProvider: nil) else {
throw IdentityProviderError.fatalError(description: "Failed to initialize AWS service configuration.")
}
self.serviceConfig = serviceConfig
AWSCognitoIdentityProvider.register(with: self.serviceConfig, forKey: Constants.secureVaultServiceName)
let poolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: clientId, clientSecret: nil, poolId: poolId)
AWSCognitoIdentityUserPool.register(with: serviceConfig, userPoolConfiguration: poolConfiguration, forKey: Constants.secureVaultServiceName)
guard let userPool = AWSCognitoIdentityUserPool(forKey: Constants.secureVaultServiceName) else {
throw IdentityProviderError.fatalError(description: "Failed to locate user pool instance with service name: \(Constants.secureVaultServiceName)")
}
self.userPool = userPool
}
public func register(uid: String, password: String,
token: String,
authenticationSalt: String,
encryptionSalt: String,
pbkdfRounds: UInt32,
completion: @escaping (Swift.Result<String, Error>) -> Void) throws {
let validationData = [
AWSCognitoIdentityUserAttributeType(name: Constants.ValidationData.idToken, value: token),
AWSCognitoIdentityUserAttributeType(name: Constants.ValidationData.authenticationSalt, value: authenticationSalt),
AWSCognitoIdentityUserAttributeType(name: Constants.ValidationData.encryptionSalt, value: encryptionSalt),
AWSCognitoIdentityUserAttributeType(name: Constants.ValidationData.pbkdfRounds, value: "\(pbkdfRounds)")
]
self.logger.debug("Signing up user \"\(uid)\".")
self.userPool.signUp(uid, password: password, userAttributes: nil, validationData: validationData).continueWith {(task) -> Any? in
if let error = task.error as NSError? {
if let message = error.userInfo[Constants.ServiceError.message] as? String {
if message.contains(Constants.ServiceError.decodingError) {
completion(.failure(IdentityProviderError.invalidInput))
} else if message.contains(Constants.ServiceError.alreadyRegisteredError) {
completion(.failure(IdentityProviderError.alreadyRegistered))
} else if message.contains(Constants.ServiceError.serviceError) {
completion(.failure(IdentityProviderError.serviceError))
} else {
completion(.failure(error))
}
} else {
completion(.failure(error))
}
} else if let result = task.result, let userConfirmed = result.userConfirmed {
if userConfirmed.boolValue {
completion(.success(uid))
} else {
completion(.failure(IdentityProviderError.identityNotConfirmed))
}
} else {
completion(.failure(IdentityProviderError.fatalError(description: "Sign up result did not contain user confirmation status.")))
}
return nil
}
}
public func signIn(uid: String, password: String, completion: @escaping (Swift.Result<AuthenticationTokens, Error>) -> Void) throws {
let user = self.userPool.getUser(uid)
user.getSession(uid,
password: password,
validationData: nil,
clientMetaData: nil,
isInitialCustomChallenge: false).continueWith { (task) -> Any? in
if let error = task.error as NSError? {
switch error.code {
case AWSCognitoIdentityProviderErrorType.notAuthorized.rawValue:
return completion(.failure(IdentityProviderError.notAuthorized))
default:
return completion(.failure(error))
}
} else if let result = task.result {
guard let idToken = result.idToken?.tokenString,
let accessToken = result.accessToken?.tokenString,
let refreshToken = result.refreshToken?.tokenString,
let expiration = result.expirationTime else {
return completion(.failure(IdentityProviderError.authTokenMissing))
}
return completion(.success(AuthenticationTokens(idToken: idToken, accessToken: accessToken, refreshToken: refreshToken, lifetime: Int(floor(expiration.timeIntervalSince(Date()))))))
} else {
return completion(.failure(IdentityProviderError.fatalError(description: "Sign in completed successfully but result is missing.")))
}
}
}
public func changePassword(uid: String,
oldPassword: String,
newPassword: String,
completion: @escaping (Swift.Result<String, Error>) -> Void) throws {
let user = self.userPool.getUser(uid)
user.changePassword(oldPassword, proposedPassword: newPassword).continueWith { (task) -> Any? in
if let error = task.error as NSError? {
switch error.code {
case AWSCognitoIdentityProviderErrorType.notAuthorized.rawValue:
return completion(.failure(IdentityProviderError.notAuthorized))
default:
return completion(.failure(error))
}
} else if task.result != nil {
return completion(.success(uid))
} else {
return completion(.failure(IdentityProviderError.fatalError(description: "Change password completed successfully but result is missing.")))
}
}
}
}
| 46.75 | 213 | 0.604392 |
fe10e243e8c91be6a4a09b1c930e3fea3a327f50 | 7,101 | //
// ViewController.swift
// SwiftAutoCellHeight
//
// Created by WhatsXie on 2017/9/14.
// Copyright © 2017年 StevenXie. All rights reserved.
//
import UIKit
let customcellIdentifier:String = "customcell"
class ViewController: UIViewController {
var arrayList = NSArray()
var titleDic = NSDictionary()
var picDic = NSDictionary()
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
tableView.delegate = self
tableView.dataSource = self
tableView.register(AutoMHTableViewCell.self , forCellReuseIdentifier: customcellIdentifier)
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
arrangeData()
self.view.addSubview(tableView)
updateViewConstraints()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Data
func arrangeData() {
arrayList = [
["Logo","Workplace"],
["Watermark"],
["Logo","Workplace"],
["Watermark"],
["Logo","Workplace"],
["Watermark"]
]
titleDic = [
"Logo":"GAVTH is a design & development studio.Determined to open the best products and constantly improve the design.",
"Workplace":"Definition of GAVTH in old language is deep pit. The logotype, in fact, composed exclusively of contour and curved lines that inspired from topographic lines. The choice of the color is not random; blue is a represent the figure of depth and clean, gray is an earth surface color and it gives neutrality and quiet.",
"Watermark":"The choice of the color is not random; blue is a represent the figure of depth and clean, gray is an earth surface color and it gives neutrality and quiet."
]
picDic = [
"Logo":"Icon.png",
"Workplace":"PicImg.png",
"Watermark":"PicText.png"
]
}
func openDetailView(type:String) {
let vc:UIViewController = (NSClassFromString("SwiftAutoCellHeight."+type) as! UIViewController.Type).init()
self.navigationController?.pushViewController(vc, animated: true)
//storyboard 跳转
// self.performSegue(withIdentifier:type, sender: self)
}
override func updateViewConstraints() {
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
self.tableView.snp.makeConstraints { (make) in
if #available(iOS 11.0, *) {
make.top.equalTo(self.view.safeAreaLayoutGuide)
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.view.safeAreaLayoutGuide)
} else {
make.size.equalTo(self.view)
make.center.equalTo(self.view)
}}
super.updateViewConstraints()
}
}
// MARK:- UITableView的代理方法
//extension:类扩展只能扩充方法,不能扩充属性
extension ViewController : UITableViewDelegate, UITableViewDataSource {
//DataSource
func numberOfSections(in tableView: UITableView) -> Int {
return arrayList.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (arrayList[section] as AnyObject).count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// return self.systemTableView(tableView, cellForRowAt: indexPath)
// return self.customCodeTableView(tableView, cellForRowAt: indexPath)
return self.customXIBTableView(tableView, cellForRowAt: indexPath)
}
//Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let titleKey = (arrayList[indexPath.section] as! NSArray)
let tky = titleKey[indexPath.row]
openDetailView(type: tky as! String)
}
}
extension ViewController {
/// 系统级
func systemTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "systemcell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "systemcell")
}
let titleKey = (arrayList[indexPath.section] as! NSArray)
let tky = titleKey[indexPath.row]
cell?.textLabel?.text = tky as? String
return cell ?? UITableViewCell()
}
/// 纯代码自定义 Cell
func customCodeTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:customcellIdentifier) as! AutoMHTableViewCell
cell.selectionStyle = .none
let titleKey = (arrayList[indexPath.section] as! NSArray)
let tky = titleKey[indexPath.row]
cell.labelTitle.text = self.titleDic[tky] as? String
cell.imagePhone.image = UIImage(named: self.picDic[tky] as! String)
cell.labelContronter.text = self.titleDic[tky] as? String
cell.setNeedsUpdateConstraints()//系统调用updateConstraints
cell.updateConstraintsIfNeeded()//立即触发约束更新,自动更新布局
return cell
}
/// XIB自定义 Cell
func customXIBTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifierhot = "NewsBigPictrueCell"
//重用写法
var cell = tableView.dequeueReusableCell(withIdentifier: identifierhot) as? NewsBigPictrueCell
if cell == nil {
tableView.register(UINib(nibName: identifierhot, bundle: nil), forCellReuseIdentifier: identifierhot)
cell = tableView.dequeueReusableCell(withIdentifier: identifierhot) as? NewsBigPictrueCell
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
}
// 防止重用写法
// var cell = tableView.cellForRow(at: indexPath) as? XIBTableViewCell
// if cell == nil {
// cell = Bundle.main.loadNibNamed(identifierhot, owner: self, options: nil)?.last as? XIBTableViewCell
// tableView.separatorStyle = UITableViewCellSeparatorStyle.none
// }
let titleKey = (arrayList[indexPath.section] as! NSArray)
let tky = titleKey[indexPath.row]
let modelAlg = Model()
modelAlg.title = self.titleDic[tky] as? String
modelAlg.picture = self.picDic[tky] as? String
modelAlg.label = self.titleDic[tky] as? String
cell?.model = modelAlg
return cell!
}
}
| 39.45 | 341 | 0.651458 |
de3ccc2f6199706e44744b02ea4a0163a06b29fb | 1,084 | //
// EnrollmentProcessingDelegate.swift
// FaceTec
//
// Created by Alex Serdukov on 12/21/20.
// Copyright © 2020 Facebook. All rights reserved.
//
class PromiseProcessingDelegate: NSObject, ProcessingDelegate {
private var promise: PromiseDelegate
init(_ promise: PromiseDelegate) {
self.promise = promise
}
func onProcessingComplete(isSuccess: Bool, sessionResult: FaceTecSessionResult?, sessionMessage: String?) {
if isSuccess {
promise.resolve(sessionMessage)
return
}
let status = sessionResult?.status
if status == nil {
onSessionTokenError()
return
}
promise.reject(status!, sessionMessage)
}
func onSessionTokenError() {
let message = FaceVerificationError.unexpectedResponse.message
promise.reject(FaceTecSessionStatus.unknownInternalError, message)
}
func onCameraAccessError() {
promise.reject(FaceTecSessionStatus.cameraPermissionDenied)
}
}
| 25.809524 | 111 | 0.635609 |
4650184b700ad76b4d455e7c4c8ec9c26961abf4 | 1,260 | //
// DetailViewController.swift
// iOS_Practical_Naman
//
// Created by naman on 05/02/19.
// Copyright © 2019 naman. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet var imgFact: UIImageView!
@IBOutlet var lblDescription: UILabel!
var strTitle = ""
var imgUrl = ""
var txtDescription = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = strTitle == "" ? constantText.noTitle : strTitle
self.lblDescription.text = txtDescription == "" ? constantText.noDescription : txtDescription
self.imgFact.sd_setImage(with: URL(string: imgUrl)) { (image, error, SDImageCacheType, URL) in
if error != nil {
self.imgFact.image = UIImage(named: "default-thumb")
}
}
// Do any additional setup after loading the view.
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 29.302326 | 106 | 0.640476 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.