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
|
---|---|---|---|---|---|
1afcb3cff809fc5bac16918c06a1c721be665ddb | 2,173 | //
// AppDelegate.swift
// WZRoute
//
// Created by xiaobin liu on 08/15/2019.
// Copyright (c) 2019 xiaobin liu. 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.234043 | 285 | 0.753797 |
397c08b7c44881f6589319bc4ad7877cb9b8da34 | 1,291 | //
// PlayerConfigurationExample.swift
// ModernAVPlayer_Example
//
// Created by ankierman on 18/12/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import AVFoundation
import ModernAVPlayer2
///
/// Documentation provided in PlayerConfiguration.swift
///
public struct PlayerConfigurationExample: PlayerConfiguration {
// Buffering State
public let rateObservingTimeout: TimeInterval = 3
public let rateObservingTickTime: TimeInterval = 0.3
// General Audio preferences
public let preferedTimeScale: CMTimeScale = 1
public let periodicPlayingTime: CMTime
public let audioSessionCategory = AVAudioSession.Category.playback
// Reachability Service
public let reachabilityURLSessionTimeout: TimeInterval = 3
//swiftlint:disable:next force_unwrapping
public let reachabilityNetworkTestingURL = URL(string: "https://www.google.com")!
public let reachabilityNetworkTestingTickTime: TimeInterval = 3
public let reachabilityNetworkTestingIteration: UInt = 10
// RemoteCommandExample is used for example
public var useDefaultRemoteCommand = false
public let allowsExternalPlayback = false
public init() {
periodicPlayingTime = CMTime(seconds: 1, preferredTimescale: preferedTimeScale)
}
}
| 30.023256 | 87 | 0.759101 |
e23e38b3f4792da9e54cced0fb912721837089ee | 6,248 | //
// FirstViewController.swift
// Petty
//
// Created by CAMILO ANDRES ANZOLA GONZALEZ on 2/21/19.
// Copyright © 2019 CAMILO ANDRES ANZOLA GONZALEZ. All rights reserved.
//
import UIKit
import Firebase
import FirebaseFirestore
class FirstViewController: UIViewController {
let alertService = AlertService()
let network: NetworkManager = NetworkManager.sharedInstance
// maneja la alerta de en progreso
@IBOutlet weak var alertButton: UIButton!
@IBAction func didTapAlert() {
let alertVC = alertService.alert(title: "Petty esta en proceso de desarrollo", body: "Seguimos trabajando para brindarte todos nuestros servicios, próximamente podrás acceder a este servicio", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
// servico baño
@IBOutlet weak var servicioBañoButton: UIButton!
@IBAction func didTapServicioBaño() {
let alertVC = alertService.alert(title: "Petty esta en proceso de desarrollo", body: "Seguimos trabajando para brindarte todos nuestros servicios, próximamente podrás acceder a este servicio", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
// servicio paseador
@IBOutlet weak var servicioPaseadorButton: UIButton!
@IBAction func didTapServicioPaseador() {
let alertVC = alertService.alert(title: "Petty esta en proceso de desarrollo", body: "Seguimos trabajando para brindarte todos nuestros servicios, próximamente podrás acceder a este servicio", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
// servicio funeraria
@IBOutlet weak var servicioFunerariaButton: UIButton!
@IBAction func didTapServicioFuneraria() {
let alertVC = alertService.alert(title: "Petty esta en proceso de desarrollo", body: "Seguimos trabajando para brindarte todos nuestros servicios, próximamente podrás acceder a este servicio", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
// partos y esterilizacion
@IBOutlet weak var servicioPartosButton: UIButton!
@IBAction func didTapServicioPartos() {
let alertVC = alertService.alert(title: "Petty esta en proceso de desarrollo", body: "Seguimos trabajando para brindarte todos nuestros servicios, próximamente podrás acceder a este servicio", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
// desparasitacion
@IBOutlet weak var servicioDesparasitacionButton: UIButton!
@IBAction func didTapServicioDesparasitacion() {
let alertVC = alertService.alert(title: "Petty esta en proceso de desarrollo", body: "Seguimos trabajando para brindarte todos nuestros servicios, próximamente podrás acceder a este servicio", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
// aqui termina todo lo del manejo de la alerta
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NetworkManager.isUnreachable { _ in
showOfflinePage()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let mascotasReference = Firestore.firestore().collection("mascotas")
//let parameters: [String: Any] = ["nombre":"Canela", "edad":"5 meses","peso":"4 kg", "raza":"Coker spaniel"]
//mascotasReference.addDocument(data: parameters)
mascotasReference.addSnapshotListener { (snapshot,_) in
guard let snapshot = snapshot else { return }
//print(snapshot.documents.isEmpty)
//for document in snapshot.documents
//{
// print(document.data())
//}
if snapshot.documents.isEmpty
{
let alert = UIAlertController(title: "Bienvenido", message: "Aún no tienes ninguna mascota registrada. Por favor agrega tus mascotas para poder acceder a todos nuestros servicios.", preferredStyle: .alert)
let subButton = UIAlertAction(title: "Ok", style: .default, handler: registrarMascota)
alert.addAction(subButton)
self.present(alert, animated: true, completion: nil)
}
}
/*else
{
let alert = UIAlertController(title: "Atencion", message: "Ahora si ya tienes mascotas", preferredStyle: .alert)
let subButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(subButton)
self.present(alert, animated: true, completion: nil)
}*/
}
/*
func showOfflinePage() -> Void {
DispatchQueue.main.async {
self.performSegue(
withIdentifier: "NetworkUnavailable",
sender: self
)
}
}
*/
func showOfflinePage() {
let alertVC = alertService.alert(title: "No hay conexion a internet ", body: "Revisa tu conexión de internet para tener acceso a todos nuestros servicios ", buttonTitle: "Entendido") {
}
present(alertVC, animated: true)
}
func registrarMascota(alert: UIAlertAction)
{
print(" ")
print(" -------------------- ")
print(" ")
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let x = storyBoard.instantiateViewController(withIdentifier: "create") as! CreatePetViewController
//self.present(x, animated: true, completion: nil)
self.navigationController?.pushViewController(x, animated: true)
}
}
}
| 34.711111 | 228 | 0.59475 |
293266a5fe2603a937dea13c4508dd9039ab786d | 1,548 | // Copyright © 2018 - 2021 Maksim Khrapov. 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.
final class PossibleCellValues {
var values: Set<Int>
init() {
values = Set<Int>()
for i in 1...9 {
values.insert(i)
}
}
func setValue(_ v: Int) {
values.removeAll()
values.insert(v)
}
func remove(_ v: Int) {
if values.contains(v) {
values.remove(v)
}
}
func hasOnlyOneValue() -> Bool {
return values.count == 1
}
func getUniqueValue() -> Int {
if values.count == 1 {
for i in values {
return i
}
}
else {
fatalError("There are more than one possible value.")
}
return 0 // to please XCode
}
func copy() -> PossibleCellValues {
let copy = PossibleCellValues()
copy.values = self.values
return copy
}
}
| 23.104478 | 75 | 0.565245 |
9039eb60ea961b78da643756d2be70cdc0ec6015 | 1,731 | //
// RemoveGoogleData.swift
// CoronaContact
//
import Foundation
struct RemoveGoogleData: MaintenancePerforming {
private enum RemovableItem {
static let googleFolder = "Google"
static let googleSDKEventsFolder = "google-sdks-events"
static let firebasePLIST = "com.firebase.FIRInstallations.plist"
}
private let fileManager: FileManager
init(fileManager: FileManager = FileManager()) {
self.fileManager = fileManager
}
private var cachesDirectory: URL? {
url(for: .cachesDirectory)
}
private var applicationSupportDirectory: URL? {
url(for: .applicationSupportDirectory)
}
private var preferencesDirectory: URL? {
url(for: .libraryDirectory)?.appendingPathComponent("Preferences")
}
private func url(for directory: FileManager.SearchPathDirectory) -> URL? {
fileManager.urls(for: directory, in: .userDomainMask)
// there should be at most one URL since we limited the search to .userDomainMask
// in any case the URL for the .userDomainMask is documented to be first
.first
}
func performMaintenance(completion: (_ success: Bool) -> Void) {
[
cachesDirectory?.appendingPathComponent(RemovableItem.googleSDKEventsFolder),
applicationSupportDirectory?.appendingPathComponent(RemovableItem.googleFolder),
preferencesDirectory?.appendingPathComponent(RemovableItem.firebasePLIST),
]
.compactMap { $0 }
.forEach { url in
do {
try fileManager.removeItem(at: url)
} catch {
print(error)
}
}
completion(true)
}
}
| 30.368421 | 93 | 0.647025 |
ed2f2927835a0410a012ee7aa350b8a1fb4f6f37 | 10,279 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Main view controller for the AR experience.
*/
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
// MARK: - IBOutlets
@IBOutlet weak var sessionInfoView: UIView!
@IBOutlet weak var sessionInfoLabel: UILabel!
@IBOutlet weak var sceneView: ARSCNView!
//4. Create Our Session
let augmentedRealitySession = ARSession()
//5. Create A Single SCNNode Which We Will Clone
var sphereNode: SCNNode!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
generateNode()
}
/// - Tag: StartARSession
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Start the view's AR session with a configuration that uses the rear camera,
// device position and orientation tracking, and plane detection.
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
// Set a delegate to track the number of plane anchors for providing UI feedback.
sceneView.session.delegate = self
sceneView.session = augmentedRealitySession
augmentedRealitySession.run(configuration, options: [.resetTracking, .removeExistingAnchors])
// Prevent the screen from being dimmed after a while as users will likely
// have long periods of interaction without touching the screen or buttons.
UIApplication.shared.isIdleTimerDisabled = true
// Show debug UI to view performance metrics (e.g. frames per second).
sceneView.showsStatistics = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's AR session.
sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
/// - Tag: PlaceARContent
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
// Place content only for anchors found by plane detection.
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
// Create a custom object to visualize the plane geometry and extent.
let plane = Plane(anchor: planeAnchor, in: sceneView)
// Add the visualization to the ARKit-managed node so that it tracks
// changes in the plane anchor as plane estimation continues.
node.addChildNode(plane)
}
override var prefersStatusBarHidden: Bool { return true }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }
/// - Tag: UpdateARContent
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
drawFeaturePoints()
// Update only anchors and nodes set up by `renderer(_:didAdd:for:)`.
if let planeAnchor = anchor as? ARPlaneAnchor {
if let plane = node.childNodes.first as? Plane {
// Update ARSCNPlaneGeometry to the anchor's new estimated shape.
if let planeGeometry = plane.meshNode.geometry as? ARSCNPlaneGeometry {
planeGeometry.update(from: planeAnchor.geometry)
}
// Update extent visualization to the anchor's new bounding rectangle.
if let extentGeometry = plane.extentNode.geometry as? SCNPlane {
extentGeometry.width = CGFloat(planeAnchor.extent.x)
extentGeometry.height = CGFloat(planeAnchor.extent.z)
plane.extentNode.simdPosition = planeAnchor.center
}
// Update the plane's classification and the text position
if #available(iOS 12.0, *),
let classificationNode = plane.classificationNode,
let classificationGeometry = classificationNode.geometry as? SCNText {
let currentClassification = planeAnchor.classification.description
if let oldClassification = classificationGeometry.string as? String, oldClassification != currentClassification {
classificationGeometry.string = currentClassification
classificationNode.centerAlign()
}
}
}
}
}
// MARK: - ARSessionDelegate
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
guard let frame = session.currentFrame else { return }
updateSessionInfoLabel(for: frame, trackingState: frame.camera.trackingState)
}
func session(_ session: ARSession, didUpdate frame: ARFrame) {
//print(frame.rawFeaturePoints)
}
func session(_ session: ARSession, didRemove anchors: [ARAnchor]) {
guard let frame = session.currentFrame else { return }
updateSessionInfoLabel(for: frame, trackingState: frame.camera.trackingState)
}
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
updateSessionInfoLabel(for: session.currentFrame!, trackingState: camera.trackingState)
}
// MARK: - ARSessionObserver
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay.
sessionInfoLabel.text = "Session was interrupted"
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required.
sessionInfoLabel.text = "Session interruption ended"
resetTracking()
}
func session(_ session: ARSession, didFailWithError error: Error) {
sessionInfoLabel.text = "Session failed: \(error.localizedDescription)"
guard error is ARError else { return }
let errorWithInfo = error as NSError
let messages = [
errorWithInfo.localizedDescription,
errorWithInfo.localizedFailureReason,
errorWithInfo.localizedRecoverySuggestion
]
// Remove optional error messages.
let errorMessage = messages.compactMap({ $0 }).joined(separator: "\n")
DispatchQueue.main.async {
// Present an alert informing about the error that has occurred.
let alertController = UIAlertController(title: "The AR session failed.", message: errorMessage, preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in
alertController.dismiss(animated: true, completion: nil)
self.resetTracking()
}
alertController.addAction(restartAction)
self.present(alertController, animated: true, completion: nil)
}
}
// MARK: - Private methods
private func updateSessionInfoLabel(for frame: ARFrame, trackingState: ARCamera.TrackingState) {
// Update the UI to provide feedback on the state of the AR experience.
let message: String
switch trackingState {
case .normal where frame.anchors.isEmpty:
// No planes detected; provide instructions for this app's AR interactions.
message = "Move the device around to detect horizontal and vertical surfaces."
case .notAvailable:
message = "Tracking unavailable."
case .limited(.excessiveMotion):
message = "Tracking limited - Move the device more slowly."
case .limited(.insufficientFeatures):
message = "Tracking limited - Point the device at an area with visible surface detail, or improve lighting conditions."
case .limited(.initializing):
message = "Initializing AR session."
default:
// No feedback needed when tracking is normal and planes are visible.
// (Nor when in unreachable limited-tracking states.)
message = ""
}
sessionInfoLabel.text = message
sessionInfoView.isHidden = message.isEmpty
}
private func resetTracking() {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors ])
}
//----------------------
//MARK: SCNNode Creation
//----------------------
/// Generates A Spherical SCNNode
func generateNode(){
sphereNode = SCNNode()
let sphereGeometry = SCNSphere(radius: 0.001)
sphereGeometry.firstMaterial?.diffuse.contents = UIColor.white
sphereNode.geometry = sphereGeometry
}
func drawFeaturePoints(){
//1. Check Our Frame Is Valid & That We Have Received Our Raw Feature Points
guard let currentFrame = self.augmentedRealitySession.currentFrame,
let featurePointsArray = currentFrame.rawFeaturePoints?.points else { return }
//2. Visualize The Feature Points
showFeaturePoints(featurePointsArray)
}
func showFeaturePoints(_ featurePointsArray: [vector_float3]){
self.sceneView.scene.rootNode.enumerateChildNodes { (featurePoint, _) in
if(featurePoint.name == "featurepoint"){
featurePoint.geometry = nil
featurePoint.removeFromParentNode()
}
}
featurePointsArray.forEach { (pointLocation) in
//Clone The SphereNode To Reduce CPU
let clone = sphereNode.clone()
clone.position = SCNVector3(pointLocation.x, pointLocation.y, pointLocation.z)
clone.name = "featurepoint"
self.sceneView.scene.rootNode.addChildNode(clone)
}
}
}
| 39.08365 | 133 | 0.628174 |
ef738d80a5d146c18c24070a1e9758ec69f4743b | 748 | import XCTest
import weatherTime
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.793103 | 111 | 0.601604 |
ab56057583ab1a0c518c1f158b87d7ad30632737 | 2,646 | import Foundation
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
import Down
public class Storage: NSTextStorage {
var name: String?
var backingStore = NSMutableAttributedString()
var currentStyles: [AttributeRange] = []
var myEditedRange: NSRange?
var myChangeInLength: Int = 0
var us: Bool = true
var parser: Parser?
public override var string: String {
get {
backingStore.string
}
}
public override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] {
backingStore.attributes(at: location, effectiveRange: range)
}
public override func replaceCharacters(in range: NSRange, with string: String) {
backingStore.replaceCharacters(in: range, with: string)
myEditedRange = range
myChangeInLength = string.utf16.count - range.length
edited(.editedCharacters, range: range, changeInLength: myChangeInLength)
}
public func syntaxHighlight() {
if let name = name {
if name.hasSuffix(".txt") || name.hasSuffix(".text") {
return
}
}
us = true
print()
var startingPoint = Date()
let parser = Parser(backingStore.string)
self.parser = parser
let newStyles = parser.processedDocument
adjustCurrentStyles()
print("parser perf: \(startingPoint.timeIntervalSinceNow * -1)")
startingPoint = Date()
let sameSize = currentStyles.count == newStyles.count
var dirty = !sameSize
if sameSize {
for (index, currentStyle) in currentStyles.enumerated() {
if !currentStyle.isEqual(to: newStyles[index]) {
dirty = true
break
}
}
}
if dirty {
print("DIRT")
currentStyles = newStyles
beginEditing()
for modification in newStyles {
setAttributes(modification.finalizeAttributes(), range: modification.range)
}
endEditing()
}
print("doc update perf: \(startingPoint.timeIntervalSinceNow * -1)")
print()
us = false
}
func adjustCurrentStyles() {
}
public override func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange) {
if us {
backingStore.setAttributes(attrs, range: range)
}
edited(.editedAttributes, range: range, changeInLength: 0)
}
}
| 28.451613 | 128 | 0.582389 |
1eb61a5905b8a56fbcab61b94f5720ab37134730 | 828 | //
// FollowsItem.swift
// InRoZe
//
// Created by Erick Olibo on 07/01/2018.
// Copyright © 2018 Erick Olibo. All rights reserved.
//
import Foundation
public class FollowsItem
{
let event: Event?
let mixtape: Mixtape?
var createdTime: Date?
var isEvent: Bool
init(event: Event?, mixtape: Mixtape?) {
self.event = event
self.mixtape = mixtape
self.createdTime = Date()
self.isEvent = false
if (event != nil) {
guard let createdTime = event?.createdTime else { return }
self.createdTime = createdTime
self.isEvent = true
} else {
guard let createdTime = mixtape?.createdTime else { return }
self.createdTime = createdTime
self.isEvent = false
}
}
}
| 21.789474 | 72 | 0.573671 |
7173135ca87ac98fb13302dfb7bd0d1c12c24294 | 273 | // RUN: not --crash %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
{struct Q<T{init{}class B:a
class a{
func a<f:f.s
| 27.3 | 87 | 0.732601 |
1d25ba1afa530f678b67ce877191b99c2c8ee95d | 908 | import Foundation
import Splash
public typealias SwiftDelegate = InjectorDelegate<SwiftCategory>
#if !os(Linux)
extension SwiftDelegate {
var theme: Theme { Theme(
font: .init(size: 12),
plainTextColor: color(for: .plainText),
tokenColors: [
.keyword: color(for: .keyword),
.string: color(for: .string),
.type: color(for: .type),
.call: color(for: .call),
.number: color(for: .number),
.comment: color(for: .comment),
.property: color(for: .property),
.dotAccess: color(for: .dotAccess),
.preprocessing: color(for: .preprocessing)
]
)}
}
#endif
extension SwiftDelegate {
public static func theme(_ theme: ColorTheme) -> SwiftDelegate {
switch theme {
case .dracula: return .dracula
case .xcodeLight: return .xcodeLight
case .xcodeDark: return .xcodeDark
}
}
}
| 25.222222 | 68 | 0.61674 |
f4a4423b7428c93d60d27f6bf4efdee94ad831fe | 2,752 | //
// SceneDelegate.swift
// SwiftUI
//
// Created by Personal Test on 3/26/20.
// Copyright © 2020 Zijia. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
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 neccessarily 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.
}
}
| 42.338462 | 147 | 0.705305 |
46e8a9661b72df1210e1c556ba99cbdd75b58a50 | 2,337 | //
// SceneDelegate.swift
// tippy
//
// Created by Wanyu Guan on 8/2/20.
// Copyright © 2020 codepath. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.277778 | 147 | 0.712452 |
e939d90f445a4ee2ce1209a5985e179c347db449 | 4,382 | //
// ShopPolicy.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
extension Storefront {
/// Policy that a merchant has configured for their store, such as their refund
/// or privacy policy.
open class ShopPolicyQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = ShopPolicy
/// Policy text, maximum size of 64kb.
@discardableResult
open func body(alias: String? = nil) -> ShopPolicyQuery {
addField(field: "body", aliasSuffix: alias)
return self
}
/// Globally unique identifier.
@discardableResult
open func id(alias: String? = nil) -> ShopPolicyQuery {
addField(field: "id", aliasSuffix: alias)
return self
}
/// Policy’s title.
@discardableResult
open func title(alias: String? = nil) -> ShopPolicyQuery {
addField(field: "title", aliasSuffix: alias)
return self
}
/// Public URL to the policy.
@discardableResult
open func url(alias: String? = nil) -> ShopPolicyQuery {
addField(field: "url", aliasSuffix: alias)
return self
}
}
/// Policy that a merchant has configured for their store, such as their refund
/// or privacy policy.
open class ShopPolicy: GraphQL.AbstractResponse, GraphQLObject, Node {
public typealias Query = ShopPolicyQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "body":
guard let value = value as? String else {
throw SchemaViolationError(type: ShopPolicy.self, field: fieldName, value: fieldValue)
}
return value
case "id":
guard let value = value as? String else {
throw SchemaViolationError(type: ShopPolicy.self, field: fieldName, value: fieldValue)
}
return GraphQL.ID(rawValue: value)
case "title":
guard let value = value as? String else {
throw SchemaViolationError(type: ShopPolicy.self, field: fieldName, value: fieldValue)
}
return value
case "url":
guard let value = value as? String else {
throw SchemaViolationError(type: ShopPolicy.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
default:
throw SchemaViolationError(type: ShopPolicy.self, field: fieldName, value: fieldValue)
}
}
/// Policy text, maximum size of 64kb.
open var body: String {
return internalGetBody()
}
func internalGetBody(alias: String? = nil) -> String {
return field(field: "body", aliasSuffix: alias) as! String
}
/// Globally unique identifier.
open var id: GraphQL.ID {
return internalGetId()
}
func internalGetId(alias: String? = nil) -> GraphQL.ID {
return field(field: "id", aliasSuffix: alias) as! GraphQL.ID
}
/// Policy’s title.
open var title: String {
return internalGetTitle()
}
func internalGetTitle(alias: String? = nil) -> String {
return field(field: "title", aliasSuffix: alias) as! String
}
/// Public URL to the policy.
open var url: URL {
return internalGetUrl()
}
func internalGetUrl(alias: String? = nil) -> URL {
return field(field: "url", aliasSuffix: alias) as! URL
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| 30.859155 | 91 | 0.701506 |
f9103f238631502f9486141d6c9f246716febfac | 2,030 | ////
// 🦠 Corona-Warn-App
//
import Foundation
import UIKit
class CheckinsInfoScreenViewController: DynamicTableViewController, FooterViewHandling, DismissHandling {
// MARK: - Init
init(
viewModel: CheckInsInfoScreenViewModel,
store: Store,
onDemand: Bool,
onDismiss: @escaping (_ animated: Bool) -> Void
) {
self.viewModel = viewModel
self.store = store
self.onDemand = onDemand
self.onDismiss = onDismiss
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
setupView()
if !viewModel.hidesCloseButton {
navigationItem.rightBarButtonItem = dismissHandlingCloseBarButton
}
navigationItem.title = AppStrings.Checkins.Information.title
navigationController?.navigationBar.prefersLargeTitles = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if store.checkinInfoScreenShown && !onDemand {
onDismiss(false)
}
}
// MARK: - Protocol DismissHandling
func wasAttemptedToBeDismissed() {
onDismiss(true)
}
// MARK: - Protocol FooterViewHandling
func didTapFooterViewButton(_ type: FooterViewModel.ButtonType) {
if type == .primary {
onDismiss(true)
}
}
// MARK: - Internal
private enum ReuseIdentifiers: String, TableViewCellReuseIdentifiers {
case legalExtended = "DynamicLegalExtendedCell"
}
// MARK: - Private
private let viewModel: CheckInsInfoScreenViewModel
private let store: Store
private let onDemand: Bool
private let onDismiss: (_ animated: Bool) -> Void
private func setupView() {
view.backgroundColor = .enaColor(for: .background)
tableView.register(
UINib(nibName: String(describing: DynamicLegalExtendedCell.self), bundle: nil),
forCellReuseIdentifier: ReuseIdentifiers.legalExtended.rawValue
)
dynamicTableViewModel = viewModel.dynamicTableViewModel
tableView.separatorStyle = .none
}
}
| 22.065217 | 105 | 0.745813 |
eb6e8d780d4bc3d6b4f12c00a080cf7ef51992d2 | 31,473 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import XCTest
import TestingProcedureKit
@testable import ProcedureKit
class QueueDelegateTests: ProcedureKitTestCase {
class WeakExpectation {
private(set) weak var expectation: XCTestExpectation?
init(_ expectation: XCTestExpectation) {
self.expectation = expectation
}
}
var expectOperations: Protector<[Operation: WeakExpectation]>!
var expectProcedures: Protector<[Procedure: WeakExpectation]>!
open override func setUp() {
super.setUp()
let expectOperations = Protector<[Operation: WeakExpectation]>([:])
let expectProcedures = Protector<[Procedure: WeakExpectation]>([:])
self.expectOperations = expectOperations
self.expectProcedures = expectProcedures
set(queueDelegate: QueueTestDelegate() { callback in
switch callback {
case .didFinishOperation(_, let operation):
if let expForOperation = expectOperations.read({ (ward) -> WeakExpectation? in
return ward[operation]
}) {
DispatchQueue.main.async {
expForOperation.expectation?.fulfill()
}
}
case .didFinishProcedure(_, let procedure, _):
if let expForProcedure = expectProcedures.read({ (ward) -> WeakExpectation? in
return ward[procedure]
}) {
DispatchQueue.main.async {
expForProcedure.expectation?.fulfill()
}
}
break
default: break
}
})
}
open override func tearDown() {
expectOperations = nil
expectProcedures = nil
super.tearDown()
}
func expectQueueDelegateDidFinishFor(operations: [Operation] = [], procedures: [Procedure] = []) {
var operationExpectations = [Operation: WeakExpectation]()
operations.forEach {
assert(!($0 is Procedure), "Passed a Procedure (\($0)) to `operations:` - use `procedures:`. Different delegate callbacks are provided for Operations vs Procedures.")
operationExpectations[$0] = WeakExpectation(expectation(description: "Expecting \($0.operationName) to generate didFinishOperation delegate callback."))
}
var procedureExpectations = [Procedure: WeakExpectation]()
procedures.forEach {
procedureExpectations[$0] = WeakExpectation(expectation(description: "Expecting \($0.operationName) to generate didFinishProcedure delegate callback."))
}
expectOperations.overwrite(with: operationExpectations)
expectProcedures.overwrite(with: procedureExpectations)
}
func test__delegate__operation_notifications() {
weak var expAddFinished = expectation(description: "Test: \(#function), queue.add did finish")
weak var expOperationFinished = expectation(description: "Test: \(#function), Operation did finish")
let operation = BlockOperation { }
let finishedProcedure = BlockProcedure { }
finishedProcedure.addDependency(operation)
finishedProcedure.addDidFinishBlockObserver { _, _ in
DispatchQueue.main.async {
expOperationFinished?.fulfill()
}
}
expectQueueDelegateDidFinishFor(operations: [operation], procedures: [finishedProcedure])
queue.addOperations([operation, finishedProcedure]).then(on: DispatchQueue.main) {
expAddFinished?.fulfill()
}
waitForExpectations(timeout: 3)
XCTAssertFalse(delegate.procedureQueueWillAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidFinishOperation.isEmpty)
}
func test___delegate__procedure_notifications() {
weak var expAddFinished = expectation(description: "Test: \(#function), queue.add did finish")
addCompletionBlockTo(procedure: procedure)
expectQueueDelegateDidFinishFor(procedures: [procedure])
queue.addOperation(procedure).then(on: DispatchQueue.main) {
expAddFinished?.fulfill()
}
waitForExpectations(timeout: 3)
XCTAssertFalse(delegate.procedureQueueWillAddProcedure.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidAddProcedure.isEmpty)
XCTAssertFalse(delegate.procedureQueueWillFinishProcedure.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidFinishProcedure.isEmpty)
}
func test__delegate__operationqueue_addoperation() {
// Testing OperationQueue's
// `open func addOperation(_ op: Operation)`
// on a ProcedureQueue to ensure that it goes through the
// overriden ProcedureQueue add path.
weak var didExecuteOperation = expectation(description: "Test: \(#function), did execute block")
let operation = BlockOperation{
DispatchQueue.main.async {
didExecuteOperation?.fulfill()
}
}
expectQueueDelegateDidFinishFor(operations: [operation])
queue.addOperation(operation)
waitForExpectations(timeout: 3)
XCTAssertFalse(delegate.procedureQueueWillAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidFinishOperation.isEmpty)
}
func test__delegate__operationqueue_addoperation_waituntilfinished() {
// Testing OperationQueue's
// `open func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool)`
// on a ProcedureQueue to ensure that it goes through the
// overriden ProcedureQueue add path and that it *doesn't* wait.
weak var didExecuteOperation = expectation(description: "Test: \(#function), Operation did finish without being waited on by addOperations(_:waitUntilFinished:)")
let operationCanProceed = DispatchSemaphore(value: 0)
let operation = BlockOperation{
guard operationCanProceed.wait(timeout: .now() + 1.0) == .success else {
// do not fulfill expectation, because main never signaled that this
// operation can proceed
return
}
DispatchQueue.main.async {
didExecuteOperation?.fulfill()
}
}
expectQueueDelegateDidFinishFor(operations: [operation])
queue.addOperations([operation], waitUntilFinished: true)
operationCanProceed.signal()
waitForExpectations(timeout: 2)
XCTAssertFalse(delegate.procedureQueueWillAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidFinishOperation.isEmpty)
}
func test__delegate__operationqueue_addoperation_block() {
// Testing OperationQueue's
// `open func addOperation(_ block: @escaping () -> Swift.Void)`
// on a ProcedureQueue to ensure that it goes through the
// overriden ProcedureQueue add path.
weak var didExecuteBlock = expectation(description: "Test: \(#function), did execute block")
queue.isSuspended = true
queue.addOperation({
DispatchQueue.main.async {
didExecuteBlock?.fulfill()
}
})
// check the queue to see if a new BlockOperation has been created
XCTAssertEqual(queue.operations.count, 1)
XCTAssertTrue(queue.operations[0] is BlockOperation, "First item in Queue is not the expected BlockOperation")
expectQueueDelegateDidFinishFor(operations: [queue.operations[0]])
// resume the queue and wait for the BlockOperation to finish
queue.isSuspended = false
waitForExpectations(timeout: 3)
XCTAssertFalse(delegate.procedureQueueWillAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidAddOperation.isEmpty)
XCTAssertFalse(delegate.procedureQueueDidFinishOperation.isEmpty)
}
}
class ExecutionTests: ProcedureKitTestCase {
func test__procedure_executes() {
wait(for: procedure)
XCTAssertTrue(procedure.didExecute)
}
func test__procedure_add_multiple_completion_blocks() {
weak var expect = expectation(description: "Test: \(#function), \(UUID())")
var completionBlockOneDidRun = 0
procedure.addCompletionBlock {
completionBlockOneDidRun += 1
}
var completionBlockTwoDidRun = 0
procedure.addCompletionBlock {
completionBlockTwoDidRun += 1
}
var finalCompletionBlockDidRun = 0
procedure.addCompletionBlock {
finalCompletionBlockDidRun += 1
DispatchQueue.main.async {
guard let expect = expect else { print("Test: \(#function): Finished expectation after timeout"); return }
expect.fulfill()
}
}
wait(for: procedure)
XCTAssertEqual(completionBlockOneDidRun, 1)
XCTAssertEqual(completionBlockTwoDidRun, 1)
XCTAssertEqual(finalCompletionBlockDidRun, 1)
}
func test__enqueue_a_sequence_of_operations() {
addCompletionBlockTo(procedure: procedure, withExpectationDescription: "\(#function)")
[procedure].enqueue()
waitForExpectations(timeout: 3, handler: nil)
PKAssertProcedureFinished(procedure)
}
func test__enqueue_a_sequence_of_operations_deallocates_queue() {
addCompletionBlockTo(procedure: procedure, withExpectationDescription: "\(#function)")
var nilQueue: ProcedureQueue! = ProcedureQueue()
weak var weakQueue = nilQueue
[procedure].enqueue(on: weakQueue!)
nilQueue = nil
waitForExpectations(timeout: 3, handler: nil)
XCTAssertNil(nilQueue)
XCTAssertNil(weakQueue)
}
// func test__procedure_executes_on_underlying_queue_of_procedurequeue() {
// // If a Procedure is added to a ProcedureQueue with an `underlyingQueue` configured,
// // the Procedure's `execute()` function should run on the underlyingQueue.
//
// class TestExecuteOnUnderlyingQueueProcedure: Procedure {
//
// public typealias Block = () -> Void
// private let block: Block
//
// public init(block: @escaping Block) {
// self.block = block
// super.init()
// }
//
// open override func execute() {
// block()
// finish()
// }
// }
//
// let customDispatchQueueLabel = "run.kit.procedure.ProcedureKit.Tests.TestUnderlyingQueue"
// let customDispatchQueue = DispatchQueue(label: customDispatchQueueLabel, attributes: [.concurrent])
// let customScheduler = ProcedureKit.Scheduler(queue: customDispatchQueue)
//
// let procedureQueue = ProcedureQueue()
// procedureQueue.underlyingQueue = customDispatchQueue
//
// let didExecuteOnDesiredQueue = Protector(false)
// let procedure = TestExecuteOnUnderlyingQueueProcedure {
// // inside execute()
// if customScheduler.isOnScheduledQueue {
// didExecuteOnDesiredQueue.overwrite(with: true)
// }
// }
//
// addCompletionBlockTo(procedure: procedure)
// procedureQueue.addOperation(procedure)
// waitForExpectations(timeout: 3)
//
// XCTAssertTrue(didExecuteOnDesiredQueue.access, "execute() did not execute on the desired underlyingQueue")
// }
}
import Dispatch
class QualityOfServiceTests: ProcedureKitTestCase {
private func testQoSClassLevels(_ block: (QualityOfService) -> Void) {
#if os(macOS)
block(.userInteractive)
block(.userInitiated)
#else
block(.userInteractive)
block(.userInitiated)
block(.`default`)
#endif
}
func test__procedure__set_quality_of_service__procedure_execute() {
testQoSClassLevels { desiredQoS in
let recordedQoSClass = Protector<DispatchQoS.QoSClass>(.unspecified)
let procedure = BlockProcedure {
recordedQoSClass.overwrite(with: DispatchQueue.currentQoSClass)
}
procedure.qualityOfService = desiredQoS
wait(for: procedure, withExpectationDescription: "Procedure Did Finish (QoSClassLevel: \(desiredQoS.qosClass))")
XCTAssertEqual(recordedQoSClass.access, desiredQoS.qosClass)
}
}
func test__procedure__set_quality_of_service__will_execute_observer() {
testQoSClassLevels { desiredQoS in
let recordedQoSClass = Protector<DispatchQoS.QoSClass>(.unspecified)
let procedure = TestProcedure()
procedure.addWillExecuteBlockObserver { procedure, _ in
recordedQoSClass.overwrite(with: DispatchQueue.currentQoSClass)
}
procedure.qualityOfService = desiredQoS
wait(for: procedure, withExpectationDescription: "Procedure Did Finish (QoSClassLevel: \(desiredQoS.qosClass))")
XCTAssertEqual(recordedQoSClass.access, desiredQoS.qosClass)
}
}
func test__procedure__set_quality_of_service__execute_after_will_execute_on_custom_queue() {
testQoSClassLevels { desiredQoS in
let recordedQoSClass_willExecute_otherQueue = Protector<DispatchQoS.QoSClass>(.unspecified)
let recordedQoSClass_willExecute = Protector<DispatchQoS.QoSClass>(.unspecified)
let recordedQoSClass_execute = Protector<DispatchQoS.QoSClass>(.unspecified)
let procedure = BlockProcedure {
recordedQoSClass_execute.overwrite(with: DispatchQueue.currentQoSClass)
}
// 1st WillExecute observer has a custom queue with no specified QoS level
// the submitted observer block should run with a QoS at least that of the desiredQoS level
let otherQueue = DispatchQueue(label: "run.kit.procedure.ProcedureKit.Testing.OtherQueue")
procedure.addWillExecuteBlockObserver(synchronizedWith: otherQueue) { procedure, _ in
recordedQoSClass_willExecute_otherQueue.overwrite(with: DispatchQueue.currentQoSClass)
}
// 2nd WillExecute observer has no custom queue (runs on the Procedure's EventQueue)
// the observer block should run with a QoS level equal to the desiredQoS level
procedure.addWillExecuteBlockObserver { procedure, _ in
recordedQoSClass_willExecute.overwrite(with: DispatchQueue.currentQoSClass)
}
procedure.qualityOfService = desiredQoS
wait(for: procedure, withExpectationDescription: "Procedure Did Finish (QoSClassLevel: \(desiredQoS.qosClass))")
XCTAssertGreaterThanOrEqual(recordedQoSClass_willExecute_otherQueue.access, desiredQoS.qosClass)
XCTAssertEqual(recordedQoSClass_willExecute.access, desiredQoS.qosClass)
XCTAssertEqual(recordedQoSClass_execute.access, desiredQoS.qosClass)
}
}
func test__procedure__set_quality_of_service__did_cancel_observer() {
testQoSClassLevels { desiredQoS in
weak var expDidCancel = expectation(description: "did cancel Procedure with qualityOfService: \(desiredQoS.qosClass)")
let recordedQoSClass = Protector<DispatchQoS.QoSClass>(.unspecified)
let procedure = TestProcedure()
procedure.addDidCancelBlockObserver { procedure, _ in
recordedQoSClass.overwrite(with: DispatchQueue.currentQoSClass)
DispatchQueue.main.async { expDidCancel?.fulfill() }
}
procedure.qualityOfService = desiredQoS
procedure.cancel()
waitForExpectations(timeout: 3)
// DidCancel observers should be executed with the qualityOfService of the Procedure
XCTAssertEqual(recordedQoSClass.access, desiredQoS.qosClass)
}
}
}
class ProcedureTests: ProcedureKitTestCase {
func test__procedure_name() {
let block = BlockProcedure { }
XCTAssertEqual(block.name, "BlockProcedure")
let group = GroupProcedure(operations: [])
XCTAssertEqual(group.name, "GroupProcedure")
wait(for: group)
}
func test__identity_is_equatable() {
let identity1 = procedure.identity
let identity2 = procedure.identity
XCTAssertEqual(identity1, identity2)
}
func test__identity_description() {
XCTAssertTrue(procedure.identity.description.hasPrefix("TestProcedure #"))
procedure.name = nil
XCTAssertTrue(procedure.identity.description.hasPrefix("Unnamed Procedure #"))
}
}
class DependencyTests: ProcedureKitTestCase {
func test__operation_added_using_then_follows_receiver() {
let another = TestProcedure()
let operations = procedure.then(do: another)
XCTAssertEqual(operations, [procedure, another])
wait(for: procedure, another)
XCTAssertLessThan(procedure.executedAt, another.executedAt)
}
func test__operation_added_using_then_via_closure_follows_receiver() {
let another = TestProcedure()
let operations = procedure.then { another }
XCTAssertEqual(operations, [procedure, another])
wait(for: procedure, another)
XCTAssertLessThan(procedure.executedAt, another.executedAt)
}
func test__operation_added_using_then_via_closure_returning_nil() {
XCTAssertEqual(procedure.then { nil }, [procedure])
}
func test__operation_added_using_then_via_closure_throwing_error() {
do {
let _ = try procedure.then { throw TestError() }
}
catch is TestError { }
catch { XCTFail("Caught unexpected error.") }
}
func test__operation_added_to_array_using_then() {
let one = TestProcedure()
let two = TestProcedure(delay: 1)
let didFinishAnother = DispatchGroup()
didFinishAnother.enter()
let another = TestProcedure()
another.addDidFinishBlockObserver { _, _ in
didFinishAnother.leave()
}
let all = [one, two, procedure].then(do: another)
XCTAssertEqual(all.count, 4)
run(operation: another)
wait(for: procedure)
// wait should time out because all of `one`, `two`, `procedure` should be waited on to start `another`
XCTAssertEqual(didFinishAnother.wait(timeout: .now() + 0.1), .timedOut)
weak var expDidFinishAnother = expectation(description: "DidFinish: another")
didFinishAnother.notify(queue: DispatchQueue.main) {
expDidFinishAnother?.fulfill()
}
wait(for: one, two) // wait for `one`, `two` and `another` (after `one` and `two`) to finish
PKAssertProcedureFinished(another)
XCTAssertLessThan(one.executedAt, another.executedAt)
XCTAssertLessThan(two.executedAt, another.executedAt)
XCTAssertLessThan(procedure.executedAt, another.executedAt)
}
func test__operation_added_to_array_using_then_via_closure() {
let one = TestProcedure()
let two = TestProcedure(delay: 1)
let another = TestProcedure()
let all = [one, two, procedure].then { another }
XCTAssertEqual(all.count, 4)
wait(for: one, two, procedure, another)
PKAssertProcedureFinished(another)
XCTAssertLessThan(one.executedAt, another.executedAt)
XCTAssertLessThan(two.executedAt, another.executedAt)
XCTAssertLessThan(procedure.executedAt, another.executedAt)
}
func test__operation_added_to_array_using_then_via_closure_throwing_error() {
let one = TestProcedure()
let two = TestProcedure(delay: 1)
do {
let _ = try [one, two, procedure].then { throw TestError() }
}
catch is TestError { }
catch { XCTFail("Caught unexpected error.") }
}
func test__operation_added_to_array_using_then_via_closure_returning_nil() {
let one = TestProcedure()
let two = TestProcedure(delay: 1)
let all = [one, two, procedure].then { nil }
XCTAssertEqual(all.count, 3)
}
}
class ProduceTests: ProcedureKitTestCase {
func test__procedure_produce_operation() {
let producedOperation = BlockProcedure { usleep(5000) }
producedOperation.name = "ProducedOperation"
let procedure = EventConcurrencyTrackingProcedure() { procedure in
try! procedure.produce(operation: producedOperation) // swiftlint:disable:this force_try
procedure.finish()
}
addCompletionBlockTo(procedure: producedOperation) // also wait for the producedOperation to finish
wait(for: procedure)
PKAssertProcedureFinished(producedOperation)
PKAssertProcedureFinished(procedure)
PKAssertProcedureNoConcurrentEvents(procedure)
}
func test__procedure_produce_operation_before_execute() {
let producedOperation = BlockProcedure { usleep(5000) }
producedOperation.name = "ProducedOperation"
let procedure = EventConcurrencyTrackingProcedure() { procedure in
procedure.finish()
}
procedure.addWillExecuteBlockObserver { procedure, pendingExecute in
try! procedure.produce(operation: producedOperation, before: pendingExecute) // swiftlint:disable:this force_try
}
addCompletionBlockTo(procedure: producedOperation) // also wait for the producedOperation to finish
wait(for: procedure)
PKAssertProcedureFinished(producedOperation)
PKAssertProcedureFinished(procedure)
PKAssertProcedureNoConcurrentEvents(procedure)
}
func test__procedure_produce_operation_before_execute_async() {
let didExecuteWillAddObserverForProducedOperation = Protector(false)
let procedureIsExecuting_InWillAddObserver = Protector(false)
let procedureIsFinished_InWillAddObserver = Protector(false)
let producedOperation = BlockProcedure { usleep(5000) }
producedOperation.name = "ProducedOperation"
let procedure = EventConcurrencyTrackingProcedure() { procedure in
procedure.finish()
}
procedure.addWillExecuteBlockObserver { procedure, pendingExecute in
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
// despite this being executed long after the willExecute observer has returned
// (and a delay), by passing the pendingExecute event to the produce function
// it should ensure that `procedure` does not execute until producing the
// operation succeeds (i.e. until all WillAdd observers have been fired and it's
// added to the queue)
try! procedure.produce(operation: producedOperation, before: pendingExecute) // swiftlint:disable:this force_try
}
}
procedure.addWillAddOperationBlockObserver { procedure, operation in
guard operation === producedOperation else { return }
didExecuteWillAddObserverForProducedOperation.overwrite(with: true)
procedureIsExecuting_InWillAddObserver.overwrite(with: procedure.isExecuting)
procedureIsFinished_InWillAddObserver.overwrite(with: procedure.isFinished)
}
addCompletionBlockTo(procedure: producedOperation) // also wait for the producedOperation to finish
wait(for: procedure)
PKAssertProcedureFinished(producedOperation)
PKAssertProcedureFinished(procedure)
XCTAssertTrue(didExecuteWillAddObserverForProducedOperation.access, "procedure never executed its WillAddOperation observer for the produced operation")
XCTAssertFalse(procedureIsExecuting_InWillAddObserver.access, "procedure was executing when its WillAddOperation observer was fired for the produced operation")
XCTAssertFalse(procedureIsFinished_InWillAddObserver.access, "procedure was finished when its WillAddOperation observer was fired for the produced operation")
}
func test__procedure_produce_operation_before_finish() {
let producedOperation = BlockProcedure { usleep(5000) }
producedOperation.name = "ProducedOperation"
let procedure = EventConcurrencyTrackingProcedure() { procedure in
procedure.finish()
}
procedure.addWillFinishBlockObserver { procedure, errors, pendingFinish in
try! procedure.produce(operation: producedOperation, before: pendingFinish) // swiftlint:disable:this force_try
}
addCompletionBlockTo(procedure: producedOperation) // also wait for the producedOperation to finish
wait(for: procedure)
PKAssertProcedureFinished(producedOperation)
PKAssertProcedureFinished(procedure)
}
func test__procedure_produce_operation_before_finish_async() {
let didExecuteWillAddObserverForProducedOperation = Protector(false)
let procedureIsExecuting_InWillAddObserver = Protector(false)
let procedureIsFinished_InWillAddObserver = Protector(false)
let producedOperation = BlockProcedure { usleep(5000) }
producedOperation.name = "ProducedOperation"
let procedure = EventConcurrencyTrackingProcedure() { procedure in
procedure.finish()
}
procedure.addWillFinishBlockObserver { procedure, errors, pendingFinish in
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
// despite this being executed long after the willFinish observer has returned
// (and a delay), by passing the pendingFinish event to the produce function
// it should ensure that `procedure` does not finish until producing the
// operation succeeds (i.e. until all WillAdd observers have been fired and it's
// added to the queue)
try! procedure.produce(operation: producedOperation, before: pendingFinish) // swiftlint:disable:this force_try
}
}
procedure.addWillAddOperationBlockObserver { procedure, operation in
guard operation === producedOperation else { return }
didExecuteWillAddObserverForProducedOperation.overwrite(with: true)
procedureIsExecuting_InWillAddObserver.overwrite(with: procedure.isExecuting)
procedureIsFinished_InWillAddObserver.overwrite(with: procedure.isFinished)
}
addCompletionBlockTo(procedure: producedOperation) // also wait for the producedOperation to finish
wait(for: procedure)
PKAssertProcedureFinished(producedOperation)
PKAssertProcedureFinished(procedure)
XCTAssertTrue(didExecuteWillAddObserverForProducedOperation.access, "procedure never executed its WillAddOperation observer for the produced operation")
XCTAssertFalse(procedureIsExecuting_InWillAddObserver.access, "procedure was executing when its WillAddOperation observer was fired for the produced operation")
XCTAssertFalse(procedureIsFinished_InWillAddObserver.access, "procedure was finished when its WillAddOperation observer was fired for the produced operation")
}
}
class ObserverEventQueueTests: ProcedureKitTestCase {
func test__custom_observer_with_event_queue() {
let didFinishGroup = DispatchGroup()
didFinishGroup.enter()
let eventsNotOnSpecifiedQueue = Protector<[EventConcurrencyTrackingRegistrar.ProcedureEvent]>([])
let eventsOnSpecifiedQueue = Protector<[EventConcurrencyTrackingRegistrar.ProcedureEvent]>([])
let registrar = EventConcurrencyTrackingRegistrar()
let customEventQueue = EventQueue(label: "run.kit.procedure.ProcedureKit.Testing.ObserverCustomEventQueue")
let observer = ConcurrencyTrackingObserver(registrar: registrar, eventQueue: customEventQueue, callbackBlock: { procedure, event in
guard customEventQueue.isOnQueue else {
eventsNotOnSpecifiedQueue.append(event)//((procedure.operationName, event))
return
}
eventsOnSpecifiedQueue.append(event)//((procedure.operationName, event))
})
let procedure = EventConcurrencyTrackingProcedure(name: "TestingProcedure") { procedure in
procedure.finish()
}
procedure.addObserver(observer)
procedure.addDidFinishBlockObserver { _, _ in
didFinishGroup.leave()
}
let finishing = BlockProcedure { }
finishing.addDependency(procedure)
run(operation: procedure)
wait(for: finishing)
// Because Procedure signals isFinished KVO *prior* to calling DidFinish observers,
// the above wait() may return before the ConcurrencyTrackingObserver is called to
// record the DidFinish event.
// Thus, wait on a second observer added *after* the ConcurrencyTrackingObserver
// to ensure the event is captured by this test.
weak var expDidFinishObserverFired = expectation(description: "DidFinishObserver was fired")
didFinishGroup.notify(queue: DispatchQueue.main) {
expDidFinishObserverFired?.fulfill()
}
waitForExpectations(timeout: 2)
XCTAssertTrue(eventsNotOnSpecifiedQueue.access.isEmpty, "Found events not on expected queue: \(eventsNotOnSpecifiedQueue.access)")
let expectedEventsOnQueue: [EventConcurrencyTrackingRegistrar.ProcedureEvent] = [.observer_didAttach, .observer_willExecute, .observer_didExecute, .observer_willFinish, .observer_didFinish]
XCTAssertEqual(eventsOnSpecifiedQueue.access, expectedEventsOnQueue)
}
func test__custom_observer_with_event_queue_same_as_self() {
let procedure = EventConcurrencyTrackingProcedure(name: "TestingProcedure") { procedure in
procedure.finish()
}
let registrar = EventConcurrencyTrackingRegistrar()
// NOTE: Don't do this. This is just for testing.
let observer = ConcurrencyTrackingObserver(registrar: registrar, eventQueue: procedure.eventQueue)
procedure.addObserver(observer)
let finishing = BlockProcedure { }
finishing.addDependency(procedure)
run(operation: procedure)
wait(for: finishing) // This test should not timeout.
}
}
class MainQueueTests: XCTestCase {
func test__operation_queue_main_has_underlyingqueue_main() {
guard let underlyingQueue = OperationQueue.main.underlyingQueue else {
XCTFail("OperationQueue.main is missing any set underlyingQueue.")
return
}
XCTAssertTrue(underlyingQueue.isMainDispatchQueue, "OperationQueue.main.underlyingQueue does not seem to be the same as DispatchQueue.main")
}
func test__procedure_queue_main_has_underlyingqueue_main() {
guard let underlyingQueue = ProcedureQueue.main.underlyingQueue else {
XCTFail("ProcedureQueue.main is missing any set underlyingQueue.")
return
}
XCTAssertTrue(underlyingQueue.isMainDispatchQueue, "ProcedureQueue.main.underlyingQueue does not seem to be the same as DispatchQueue.main")
}
}
| 45.025751 | 197 | 0.686811 |
f5b72006e4fe41d21a3e9baf7b7b3524c2ff12ef | 635 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "TILApp",
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0-rc.2"),
// 🔵 Swift ORM (queries, models, relations, etc) built on PostgreSQL.
.package(url: "https://github.com/vapor/fluent-postgresql.git", from: "1.0.0-rc.2")
],
targets: [
.target(name: "App", dependencies: ["FluentPostgreSQL", "Vapor"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"])
]
)
| 31.75 | 89 | 0.60315 |
e27e2b239c066af90f1d0fd979009eca46e23bc3 | 2,179 | //
// AppDelegate.swift
// LoadingView
//
// Created by Gleb Radchenko on 4/9/17.
// Copyright © 2017 Gleb Radchenko. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.361702 | 285 | 0.755851 |
5dfc5fca358ac102e7b4a9366cb1c3c2da82b3bf | 547 | // swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Crossroad",
platforms: [.iOS(.v9),.tvOS(.v9)],
products: [
.library(
name: "Crossroad",
targets: ["Crossroad"]),
],
targets: [
.target(
name: "Crossroad",
dependencies: []),
.testTarget(
name: "CrossroadTests",
dependencies: ["Crossroad"]),
]
)
| 23.782609 | 96 | 0.552102 |
f48e95e7d1aee7852438c84b6c909e9c37e38697 | 1,850 | //
// ProfileViewController.swift
// Twitter
//
// Created by David Kuchar on 5/31/15.
// Copyright (c) 2015 David Kuchar. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
var user: User?
@IBOutlet weak var userBackgroundImage: UIImageView!
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userTwitterHandleLabel: UILabel!
@IBOutlet weak var tweetCountLabel: UILabel!
@IBOutlet weak var followingCountLabel: UILabel!
@IBOutlet weak var followerCountLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if user!.headerImageUrl != nil {
userBackgroundImage.setImageWithURL(NSURL(string: user!.headerImageUrl!))
}
userImage.setImageWithURL(NSURL(string: user!.profileImageUrl!))
userImage.layer.cornerRadius = 3
userImage.clipsToBounds = true
userNameLabel.text = user!.name
userTwitterHandleLabel.text = "@\(user!.screenname!)"
tweetCountLabel.text = String(user!.tweetCount!)
followingCountLabel.text = String(user!.followingCount!)
followerCountLabel.text = String(user!.followerCount!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.45614 | 106 | 0.688649 |
e259b90841ca255a3c119d6e37e93d57e42b208c | 3,001 | //
// TabBarDivider.swift
// CodeEdit
//
// Created by Lingxi Li on 4/22/22.
//
import SwiftUI
import AppPreferences
import CodeEditUI
/// The vertical divider between tab bar items.
struct TabDivider: View {
@Environment(\.colorScheme)
var colorScheme
@StateObject
private var prefs: AppPreferencesModel = .shared
let width: CGFloat = 1
var body: some View {
Rectangle()
.frame(width: width)
.padding(.vertical, prefs.preferences.general.tabBarStyle == .xcode ? 8 : 0)
.foregroundColor(
prefs.preferences.general.tabBarStyle == .xcode
? Color(nsColor: colorScheme == .dark ? .white : .black)
.opacity(0.12)
: Color(nsColor: colorScheme == .dark ? .controlColor : .black)
.opacity(colorScheme == .dark ? 0.40 : 0.13)
)
}
}
/// The top border for tab bar (between tab bar and titlebar).
struct TabBarTopDivider: View {
@Environment(\.colorScheme)
var colorScheme
@StateObject
private var prefs: AppPreferencesModel = .shared
var body: some View {
ZStack(alignment: .top) {
if prefs.preferences.general.tabBarStyle == .native {
// Color background overlay in native style.
Color(nsColor: .black)
.opacity(colorScheme == .dark ? 0.80 : 0.02)
.frame(height: prefs.preferences.general.tabBarStyle == .xcode ? 1.0 : 0.8)
// Shadow of top divider in native style.
TabBarNativeShadow()
}
}
}
}
/// The bottom border for tab bar (between tab bar and breadcrumbs).
struct TabBarBottomDivider: View {
@Environment(\.colorScheme)
var colorScheme
@StateObject
private var prefs: AppPreferencesModel = .shared
var body: some View {
Rectangle()
.foregroundColor(
prefs.preferences.general.tabBarStyle == .xcode
? Color(nsColor: .separatorColor)
.opacity(colorScheme == .dark ? 0.80 : 0.40)
: Color(nsColor: .black)
.opacity(colorScheme == .dark ? 0.65 : 0.13)
)
.frame(height: prefs.preferences.general.tabBarStyle == .xcode ? 1.0 : 0.8)
}
}
/// The divider shadow for native tab bar style.
///
/// This is generally used in the top divider of tab bar when tab bar style is set to `native`.
struct TabBarNativeShadow: View {
let shadowColor = Color(nsColor: .shadowColor)
var body: some View {
LinearGradient(
colors: [
shadowColor.opacity(0.18),
shadowColor.opacity(0.06),
shadowColor.opacity(0.03),
shadowColor.opacity(0.01),
shadowColor.opacity(0)
],
startPoint: .top,
endPoint: .bottom
)
.frame(height: 3.8)
.opacity(0.70)
}
}
| 29.421569 | 95 | 0.566145 |
567893e93fdfde5d7ed8eee95f6643fcec1c6987 | 6,199 | // export
import Path
import TensorFlow
let path = downloadImagette()
let il = ItemList(fromFolder: path, extensions: ["jpeg", "jpg"])
let sd = SplitData(il, fromFunc: {grandParentSplitter(fName: $0, valid: "val")})
var (procItem,procLabel) = (NoopProcessor<Path>(),CategoryProcessor())
let sld = SplitLabeledData(sd, fromFunc: parentLabeler, procItem: &procItem, procLabel: &procLabel)
let rawData = sld.toDataBunch(itemToTensor: pathsToTensor, labelToTensor: intsToTensor, bs: 32)
let data = transformData(rawData, tfmItem: { openAndResize(fname: $0, size: 128) })
let batch = data.train.oneBatch()!
print(batch.xb.shape)
print(batch.yb.shape)
let labels = batch.yb.scalars.map { procLabel.vocab![Int($0)] }
// showImages(batch.xb, labels: labels)
public struct ConvLayer: Layer {
public var bn: FABatchNorm<Float>
public var conv: FANoBiasConv2D<Float>
public init(_ cIn: Int, _ cOut: Int, ks: Int = 3, stride: Int = 1, zeroBn: Bool = false, act: Bool = true){
bn = FABatchNorm(featureCount: cOut)
if act {
conv = FANoBiasConv2D(cIn, cOut, ks: ks, stride: stride, activation: relu)
} else {
conv = FANoBiasConv2D(cIn, cOut, ks: ks, stride: stride, activation: identity)
}
if zeroBn { bn.scale = Tensor(zeros: [cOut]) }
}
@differentiable
public func call(_ input: TF) -> TF {
return bn(conv(input))
}
}
//A layer that you can switch off to do the identity instead
public protocol SwitchableLayer: Layer {
associatedtype Input
var isOn: Bool {get set}
@differentiable func forward(_ input: Input) -> Input
}
public extension SwitchableLayer {
func call(_ input: Input) -> Input {
return isOn ? forward(input) : input
}
@differentiating(call)
func gradForward(_ input: Input) ->
(value: Input, pullback: (Self.Input.CotangentVector) ->
(Self.CotangentVector, Self.Input.CotangentVector)) {
if isOn { return valueWithPullback(at: input) { $0.forward($1) } }
else { return (input, {v in return (Self.CotangentVector.zero, v)}) }
}
}
public struct MaybeAvgPool2D: SwitchableLayer {
var pool: FAAvgPool2D<Float>
@noDerivative public var isOn = false
@differentiable public func forward(_ input: TF) -> TF { return pool(input) }
public init(_ sz: Int) {
isOn = (sz > 1)
pool = FAAvgPool2D<Float>(sz)
}
}
public struct MaybeConv: SwitchableLayer {
var conv: ConvLayer
@noDerivative public var isOn = false
@differentiable public func forward(_ input: TF) -> TF { return conv(input) }
public init(_ cIn: Int, _ cOut: Int) {
isOn = (cIn > 1) || (cOut > 1)
conv = ConvLayer(cIn, cOut, ks: 1, act: false)
}
}
public struct ResBlock: Layer {
public var convs: [ConvLayer]
public var idConv: MaybeConv
public var pool: MaybeAvgPool2D
public init(_ expansion: Int, _ ni: Int, _ nh: Int, stride: Int = 1){
let (nf, nin) = (nh*expansion,ni*expansion)
convs = [ConvLayer(nin, nh, ks: 1)]
convs += (expansion==1) ? [
ConvLayer(nh, nf, ks: 3, stride: stride, zeroBn: true, act: false)
] : [
ConvLayer(nh, nh, ks: 3, stride: stride),
ConvLayer(nh, nf, ks: 1, zeroBn: true, act: false)
]
idConv = nin==nf ? MaybeConv(1,1) : MaybeConv(nin, nf)
pool = MaybeAvgPool2D(stride)
}
@differentiable
public func call(_ inp: TF) -> TF {
return relu(convs(inp) + idConv(pool(inp)))
}
}
func makeLayer(_ expansion: Int, _ ni: Int, _ nf: Int, _ nBlocks: Int, stride: Int) -> [ResBlock] {
return Array(0..<nBlocks).map { ResBlock(expansion, $0==0 ? ni : nf, nf, stride: $0==0 ? stride : 1) }
}
public struct XResNet: Layer {
public var stem: [ConvLayer]
public var maxPool = MaxPool2D<Float>(poolSize: (3,3), strides: (2,2), padding: .same)
public var blocks: [ResBlock]
public var pool = GlobalAvgPool2D<Float>()
public var linear: Dense<Float>
public init(_ expansion: Int, _ layers: [Int], cIn: Int = 3, cOut: Int = 1000){
var nfs = [cIn, (cIn+1)*8, 64, 64]
stem = Array(0..<3).map{ ConvLayer(nfs[$0], nfs[$0+1], stride: $0==0 ? 2 : 1)}
nfs = [64/expansion,64,128,256,512]
blocks = Array(layers.enumerated()).map { (i,l) in
return makeLayer(expansion, nfs[i], nfs[i+1], l, stride: i==0 ? 1 : 2)
}.reduce([], +)
linear = Dense(inputSize: nfs.last!*expansion, outputSize: cOut)
}
@differentiable
public func call(_ inp: TF) -> TF {
return linear(pool(blocks(maxPool(stem(inp)))))
}
}
func xresnet18 (cIn: Int = 3, cOut: Int = 1000) -> XResNet { return XResNet(1, [2, 2, 2, 2], cIn: cIn, cOut: cOut) }
func xresnet34 (cIn: Int = 3, cOut: Int = 1000) -> XResNet { return XResNet(1, [3, 4, 6, 3], cIn: cIn, cOut: cOut) }
func xresnet50 (cIn: Int = 3, cOut: Int = 1000) -> XResNet { return XResNet(4, [3, 4, 6, 3], cIn: cIn, cOut: cOut) }
func xresnet101(cIn: Int = 3, cOut: Int = 1000) -> XResNet { return XResNet(4, [3, 4, 23, 3], cIn: cIn, cOut: cOut) }
func xresnet152(cIn: Int = 3, cOut: Int = 1000) -> XResNet { return XResNet(4, [3, 8, 36, 3], cIn: cIn, cOut: cOut) }
func modelInit() -> XResNet { return xresnet50(cOut: 10) }
let optFunc: (XResNet) -> StatefulOptimizer<XResNet> = AdamOpt(lr: 1e-2, mom: 0.9, beta: 0.99, wd: 1e-2, eps: 1e-6)
let learner = Learner(data: data, lossFunc: softmaxCrossEntropy, optFunc: optFunc, modelInit: modelInit)
let recorder = learner.makeDefaultDelegates(metrics: [accuracy])
learner.addDelegate(learner.makeNormalize(mean: imagenetStats.mean, std: imagenetStats.std))
try! learner.fit(1)
// Experiment: Iterate through the whole dataset. This seems to go really fast.
// var xOpt: Tensor<Float>? = nil
// var n: Int = 0
// for batch in data.train.ds {
// print(n)
// n += 1
// guard let x = xOpt else {
// xOpt = batch.xb
// continue
// }
// guard batch.xb.shape[0] == x.shape[0] else {
// print("Smaller batch, skipping")
// continue
// }
// xOpt = x + batch.xb
// }
// print(xOpt!)
| 35.022599 | 117 | 0.621713 |
165aa2abf4ba6a28329c21c247fd4beecf6f46c8 | 1,484 | //
// AddLangTableViewCell.swift
// MiniChallenge
//
// Created by Aluno Mack on 22/10/19.
// Copyright © 2019 Leo Mosca. All rights reserved.
//
import UIKit
class AddLangTableViewCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var desc: UILabel!
@IBOutlet weak var topics: UILabel!
@IBOutlet weak var materials: UILabel!
@IBOutlet weak var language: UIView!
@IBOutlet weak var languageIcon: UIImageView!
@IBOutlet weak var topicsView: UIView!
@IBOutlet weak var materialsView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.language.layer.cornerRadius = 5
self.topicsView.layer.cornerRadius = self.topicsView.frame.height / 2
self.materialsView.layer.cornerRadius = self.materialsView.frame.height / 2
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
public func setCell(_ title: String?, _ desc: String?, _ topics: Int, _ materials: Int, _ color: String?){
self.title.text = title;
self.desc.text = desc;
self.topics.text = String(topics) + " TÓPICO" + (topics == 1 ? "" : "S");
self.materials.text = String(materials) + " MATERIA" + (materials == 1 ? "L" : "IS");
self.language.backgroundColor = UIColor(hex: color ?? "#777777")
self.languageIcon.image = UIImage(named: title! + "Icon")
}
}
| 33.727273 | 110 | 0.651617 |
71387cb52513b560f86e6dca0e7c55a26caed8c0 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{
struct S{
var f=c
struct c<T
func a{struct a{struct c<f:f.c
var f=c
| 22.181818 | 87 | 0.745902 |
bf5e4941a60df2a662586e018b8eff9c709c6d3e | 1,885 | //
// Measure.swift
// CoreMLAndVisonRealTimeObjectDetction
//
// Created by Ilija Mihajlovic on 2/7/19.
// Copyright © 2019 Ilija Mihajlovic. All rights reserved.
//
import UIKit
protocol MeasureDelegate {
func updateMeasure(inferenceTime: Double, executionTime: Double, fps: Int)
}
// Performance Measurement
class Measure {
var delegate: MeasureDelegate?
var index: Int = -1
var measurements: [Dictionary<String, Double>]
init() {
let measurement = ["start": CACurrentMediaTime(),"end": CACurrentMediaTime()]
measurements = Array<Dictionary<String, Double>>(repeating: measurement, count: 30)
}
func recordStart() {
index += 1
index %= 30
measurements[index] = [:]
labeling(for: index, with: "start")
}
func recordStop() {
labeling(for: index, with: "end")
let beforeMeasurement = getBeforeMeasurment(for: index)
let currentMeasurement = measurements[index]
if let startTime = currentMeasurement["start"],
let endInferenceTime = currentMeasurement["endInference"],
let endTime = currentMeasurement["end"],
let beforeStartTime = beforeMeasurement["start"] {
delegate?.updateMeasure(inferenceTime: endInferenceTime - startTime,executionTime: endTime - startTime, fps: Int(1/(startTime - beforeStartTime)))
}
}
func labelingWith(with msg: String? = "") {
labeling(for: index, with: msg)
}
private func labeling(for index: Int, with msg: String? = "") {
if let message = msg {
measurements[index][message] = CACurrentMediaTime()
}
}
private func getBeforeMeasurment(for index: Int) -> Dictionary<String, Double> {
return measurements[(index + 30 - 1) % 30]
}
}
| 28.134328 | 158 | 0.618568 |
de851e6bdd7915e8a9b0e7c80f83f8dad23136f2 | 17,781 | //
// AODialogView.swift
// DialogAlert
//
// Created by Alexander Orlov on 30/01/2020.
// Copyright © 2020 Alexander Orlov. All rights reserved.
//
import UIKit
private extension Selector {
// static let deviceOrientationDidChange = #selector(AODialogView.deviceOrientationDidChange)
}
private extension UIView {
func clearConstraints() {
for subview in self.subviews {
subview.clearConstraints()
}
self.removeConstraints(self.constraints)
}
}
enum AODialogStyle {
case date
case dateTime
case time
}
enum AODialogAlertStyle {
case alert
case actionSheet
}
protocol AODialogViewDelegate {
/// Dismiss by background tap
func dialogDidDisappear()
/// Done click handler
func doneClicked(selectedDate: Date)
/// Cancel click handler
func cancelClicked()
}
class AODialogView: UIView {
var style: AODialogStyle!
var alertStyle: AODialogAlertStyle!
var delegate: AODialogViewDelegate?
var datePicker: UIDatePicker!
var dialogView: UIView!
var contentView: UIView!
var defaultDate: Date!
var defaultDateFormat: String = "dd.MM.yyyy, HH:mm"
var leftHandConfirm: Bool = false
var minDate: Date!
var maxDate: Date!
var dateLabel: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
lbl.numberOfLines = 1
return lbl
}()
let borderBottomView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.0, *) {
view.backgroundColor = UIColor.systemGray2
} else {
view.backgroundColor = UIColor.lightGray
}
return view
}()
let buttonBorder: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.0, *) {
view.backgroundColor = UIColor.systemGray2
} else {
view.backgroundColor = UIColor.lightGray
}
return view
}()
let doneButton: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Done", for: .normal)
btn.setTitleColor(UIColor.systemRed, for: .normal)
btn.setTitleColor(UIColor.systemGray, for: .highlighted)
if #available(iOS 13.0, *) {
btn.backgroundColor = .secondarySystemBackground
} else {
btn.backgroundColor = .white
}
btn.clipsToBounds = true
btn.layer.cornerRadius = 10
return btn
}()
let cancelButton: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Cancel", for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
btn.setTitleColor(UIColor.systemBlue, for: .normal)
btn.setTitleColor(UIColor.systemGray, for: .highlighted)
if #available(iOS 13.0, *) {
btn.backgroundColor = .secondarySystemBackground
} else {
btn.backgroundColor = .white
}
btn.clipsToBounds = true
btn.layer.cornerRadius = 10
return btn
}()
var backgroundTapToDismiss: Bool = false
private var buttonsHeight: CGFloat {
return 50
}
static let shared = AODialogView(style: .date, frame: .zero)
override init(frame: CGRect) {
super.init(frame: frame)
}
init(style: AODialogStyle, frame: CGRect) {
let size = UIScreen.main.bounds.size
super.init(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
backgroundColor = UIColor.systemGray.withAlphaComponent(0.3)
alpha = 0
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(delegate: AODialogViewDelegate, doneTitle: String = "Done", cancelTitle: String = "Cancel", style: AODialogStyle = .dateTime, leftHandConfirm: Bool = false, enableBackgroundDismiss: Bool = true, defaultDate: Date = Date(), minimumDate: Date? = nil, maximumDate: Date? = nil, dateFormat: String = "dd.MM.yyyy, HH:mm", alertStyle: AODialogAlertStyle = .alert) {
self.delegate = delegate
self.alertStyle = alertStyle
self.style = style
self.backgroundTapToDismiss = enableBackgroundDismiss
self.doneButton.setTitle(doneTitle, for: .normal)
self.cancelButton.setTitle(cancelTitle, for: .normal)
self.defaultDate = defaultDate
self.defaultDateFormat = dateFormat
self.minDate = minimumDate
self.maxDate = maximumDate
self.leftHandConfirm = leftHandConfirm
setupBackground()
}
fileprivate func setupBackground() {
if backgroundTapToDismiss {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closeByBackgroundTap)))
}
/* Add dialog to main window */
guard let appDelegate = UIApplication.shared.delegate else { fatalError() }
guard let window = appDelegate.window else { fatalError() }
setupDialogView()
window?.addSubview(self)
window?.bringSubviewToFront(self)
window?.endEditing(true)
}
fileprivate func setupDialogView() {
contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentView)
dialogView = UIView()
if #available(iOS 13.0, *) {
dialogView.backgroundColor = .secondarySystemBackground
} else {
dialogView.backgroundColor = .white
}
dialogView.translatesAutoresizingMaskIntoConstraints = false
dialogView.clipsToBounds = true
dialogView.layer.cornerRadius = 7
dialogView.alpha = 0
dialogView.layer.opacity = 0.5
dialogView.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
cancelButton.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
doneButton.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
dialogView.addSubview(dateLabel)
dialogView.addSubview(borderBottomView)
dialogView.addSubview(buttonBorder)
contentView.addSubview(doneButton)
contentView.addSubview(cancelButton)
doneButton.addTarget(self, action: #selector(doneHandler), for: .touchUpInside)
cancelButton.addTarget(self, action: #selector(closeHandler), for: .touchUpInside)
contentView.addSubview(dialogView)
// NotificationCenter.default.addObserver(
// self,
// selector: .deviceOrientationDidChange,
// name: UIDevice.orientationDidChangeNotification, object: nil
// )
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
self.dialogView.alpha = 1
self.dialogView.layer.transform = CATransform3DMakeScale(1, 1, 1)
self.cancelButton.alpha = 1
self.doneButton.alpha = 1
self.doneButton.layer.transform = CATransform3DMakeScale(1, 1, 1)
self.cancelButton.layer.transform = CATransform3DMakeScale(1, 1, 1)
self.alpha = 1
}) { (success) in
}
setupDatePicker()
}
fileprivate func setupDatePicker() {
datePicker = UIDatePicker()
datePicker.minimumDate = minDate
datePicker.maximumDate = maxDate
datePicker.translatesAutoresizingMaskIntoConstraints = false
datePicker.setDate(defaultDate, animated: true)
datePicker.addTarget(self, action: #selector(dateHasChanged(picker:)), for: .valueChanged)
let dateF = DateFormatter()
switch style {
case .date:
datePicker.datePickerMode = .date
dateF.dateFormat = defaultDateFormat
dateLabel.text = dateF.string(from: defaultDate)
case .dateTime:
datePicker.datePickerMode = .dateAndTime
dateF.dateFormat = defaultDateFormat
dateLabel.text = dateF.string(from: defaultDate)
case .time:
datePicker.datePickerMode = .time
dateF.dateFormat = defaultDateFormat
dateLabel.text = dateF.string(from: defaultDate)
case .none:
print("")
}
dialogView.addSubview(datePicker)
setupDialogContraints()
}
fileprivate func setupDialogContraints() {
// contentView.heightAnchor.constraint(equalToConstant: 300).isActive = true
contentView.topAnchor.constraint(equalTo: dialogView.topAnchor, constant: -20).isActive = true
contentView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0).isActive = true
contentView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0).isActive = true
if alertStyle == .alert {
contentView.bottomAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: buttonsHeight + 40).isActive = true
contentView.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
contentView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
dialogView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 0).isActive = true
dialogView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
} else {
setupActionSheet()
}
dialogView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
dialogView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
dialogView.heightAnchor.constraint(equalToConstant: 250).isActive = true
dateLabel.centerXAnchor.constraint(equalTo: dialogView.centerXAnchor, constant: 0).isActive = true
dateLabel.topAnchor.constraint(equalTo: dialogView.topAnchor, constant: 10).isActive = true
dateLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
datePicker.centerXAnchor.constraint(equalTo: dialogView.centerXAnchor, constant: 0).isActive = true
datePicker.leadingAnchor.constraint(equalTo: dialogView.leadingAnchor, constant: 0).isActive = true
datePicker.trailingAnchor.constraint(equalTo: dialogView.trailingAnchor, constant: 0).isActive = true
datePicker.bottomAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: 0).isActive = true
datePicker.topAnchor.constraint(equalTo: dateLabel.bottomAnchor, constant: 0).isActive = true
// borderBottomView.leadingAnchor.constraint(equalTo: dialogView.leadingAnchor, constant: 0).isActive = true
// borderBottomView.trailingAnchor.constraint(equalTo: dialogView.trailingAnchor, constant: 0).isActive = true
// borderBottomView.topAnchor.constraint(equalTo: datePicker.bottomAnchor, constant: 0).isActive = true
// borderBottomView.heightAnchor.constraint(equalToConstant: 1).isActive = true
setupButtonConstraints()
}
fileprivate func setupButtonConstraints() {
if alertStyle == .alert {
if leftHandConfirm {
doneButton.leadingAnchor.constraint(equalTo: dialogView.leadingAnchor, constant: 0).isActive = true
doneButton.topAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: 20).isActive = true
doneButton.trailingAnchor.constraint(equalTo: dialogView.centerXAnchor, constant: -5).isActive = true
doneButton.heightAnchor.constraint(equalToConstant: buttonsHeight).isActive = true
cancelButton.trailingAnchor.constraint(equalTo: dialogView.trailingAnchor, constant: 0).isActive = true
cancelButton.topAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: 20).isActive = true
cancelButton.heightAnchor.constraint(equalToConstant: buttonsHeight).isActive = true
cancelButton.leadingAnchor.constraint(equalTo: dialogView.centerXAnchor, constant: 5).isActive = true
} else {
cancelButton.leadingAnchor.constraint(equalTo: dialogView.leadingAnchor, constant: 0).isActive = true
cancelButton.topAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: 20).isActive = true
cancelButton.trailingAnchor.constraint(equalTo: dialogView.centerXAnchor, constant: -5).isActive = true
cancelButton.heightAnchor.constraint(equalToConstant: buttonsHeight).isActive = true
doneButton.trailingAnchor.constraint(equalTo: dialogView.trailingAnchor, constant: 0).isActive = true
doneButton.topAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: 20).isActive = true
doneButton.heightAnchor.constraint(equalToConstant: buttonsHeight).isActive = true
doneButton.leadingAnchor.constraint(equalTo: dialogView.centerXAnchor, constant: 5).isActive = true
}
// buttonBorder.topAnchor.constraint(equalTo: borderBottomView.bottomAnchor, constant: 0).isActive = true
// buttonBorder.leadingAnchor.constraint(equalTo: cancelButton.trailingAnchor, constant: 0).isActive = true
// buttonBorder.trailingAnchor.constraint(equalTo: doneButton.leadingAnchor, constant: 0).isActive = true
// buttonBorder.bottomAnchor.constraint(equalTo: dialogView.bottomAnchor, constant: 0).isActive = true
}
}
fileprivate func setupActionSheet() {
if #available(iOS 11.0, *) {
contentView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor).isActive = true
} else {
contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
cancelButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
cancelButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
cancelButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20).isActive = true
cancelButton.heightAnchor.constraint(equalToConstant: buttonsHeight).isActive = true
doneButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
doneButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
doneButton.bottomAnchor.constraint(equalTo: cancelButton.topAnchor, constant: -20).isActive = true
doneButton.heightAnchor.constraint(equalToConstant: buttonsHeight).isActive = true
dialogView.bottomAnchor.constraint(equalTo: doneButton.topAnchor, constant: -10).isActive = true
dialogView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 0).isActive = true
}
@objc fileprivate func dateHasChanged(picker: UIDatePicker) {
let dateF = DateFormatter()
switch style {
case .date:
datePicker.datePickerMode = .date
dateF.dateFormat = defaultDateFormat
dateLabel.text = dateF.string(from: picker.date)
case .dateTime:
datePicker.datePickerMode = .dateAndTime
dateF.dateFormat = defaultDateFormat
dateLabel.text = dateF.string(from: picker.date)
case .time:
datePicker.datePickerMode = .time
dateF.dateFormat = defaultDateFormat
dateLabel.text = dateF.string(from: picker.date)
case .none:
print("")
}
}
@objc fileprivate func doneHandler() {
self.delegate?.doneClicked(selectedDate: datePicker.date)
dismissView()
}
@objc fileprivate func closeHandler() {
self.delegate?.cancelClicked()
dismissView()
}
@objc fileprivate func closeByBackgroundTap() {
self.delegate?.dialogDidDisappear()
dismissView()
}
fileprivate func dismissView() {
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
self.dialogView.alpha = 0
self.dialogView.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.3)
self.cancelButton.alpha = 0
self.doneButton.alpha = 0
self.doneButton.layer.transform = CATransform3DMakeScale(0.1, 0.1, 0.1)
self.cancelButton.layer.transform = CATransform3DMakeScale(0.1, 0.1, 0.1)
self.alpha = 0
}) { (success) in
if success {
self.dialogView.removeFromSuperview()
self.cancelButton.removeFromSuperview()
self.doneButton.removeFromSuperview()
self.contentView.removeFromSuperview()
self.removeFromSuperview()
self.dialogView = nil
self.contentView = nil
}
}
}
}
extension AODialogView {
/// Handle device orientation changes
// @objc func deviceOrientationDidChange(_ notification: Notification) {
// self.frame = UIScreen.main.bounds
// dialogView.clearConstraints()
//
// setupDialogContraints()
// }
}
| 41.544393 | 373 | 0.655981 |
f481a43868602e185be006aad8442a5ebf55bdec | 368 | //
// CategoryView.swift
// TriviaApp
//
// Created by Ari on 09/03/22.
//
import SwiftUI
//struct CategoryView: View {
// var body: some View {
// Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
// }
//}
//
//struct CategoryView_Previews: PreviewProvider {
// static var previews: some View {
// CategoryView()
// }
//}
| 17.52381 | 73 | 0.595109 |
dd671944a92d0f9a8e8e33062e08a7c10b46f203 | 4,939 | //
// TernBridge.swift
// BridgeJSCodeForSwift
//
// Created by anthann on 2019/3/22.
// Copyright © 2019 anthann. All rights reserved.
//
import Foundation
import JavaScriptCore
@objc protocol TernExportProtocol: JSExport {
func getFile(_ filename: String) -> String
func callback(_ error: Any?, _ response: Any?)
}
@objc class TernBridge: NSObject {
public var fileContents: [String: String] = [String: String]()
public weak var delegate: TernJSProtocol?
@discardableResult
static func registerInto(jsContext: JSContext, forKeyedSubscript: String = "TernBridge") -> TernBridge {
// Load source files
let bundle = Bundle.main
let sources = ["polyfill", "acorn", "acorn-loose", "walk", "signal", "tern", "def", "comment", "infer", "modules", "es_modules", "requirejs", "doc_comment", "complete_strings", "commonjs"]
for source in sources {
if let url = bundle.url(forResource: source, withExtension: "js", subdirectory: "tern") {
jsContext.evaluateScript(try! String(contentsOf: url), withSourceURL: url)
} else {
fatalError()
}
}
// Initialize Tern.Server
let instance = TernBridge()
jsContext.setObject(instance,
forKeyedSubscript: forKeyedSubscript as NSString)
jsContext.evaluateScript(
"function __callback__(err, response) { return TernBridge.callback(err, response) }" +
"let ternServer = new tern.Server({" +
" getFile: TernBridge.getFile," +
" async: true," +
" plugins: {commonjs: true}," +
"});" +
"ternServer.requestFileUpdate = function(filename, content) {" +
" this.request({files: [{type: 'full', name: filename, text: content}]}, __callback__)" +
"};"
)
return instance
}
public func onTextChange(context: JSContext, _ text: String, filename: String) {
self.fileContents[filename] = text
context.evaluateScript("ternServer.requestFileUpdate('\(filename)', `\(text)`);")
}
public func requestForHint(context: JSContext, filename: String, offset: Int) {
context.evaluateScript("""
ternServer.request({query: {type: "completions", file: '\(filename)', end: \(offset), includeKeywords: true, caseInsensitive: true, types: true, origins: true}}, __callback__)
""")
}
public func addFile(context: JSContext, name: String, content: String) {
context.evaluateScript("""
ternServer.addFile(`\(name)`, `\(content)`);
""")
}
public func deleteFile(context: JSContext, name: String) {
context.evaluateScript("""
ternServer.delFile(`\(name)`);
""")
}
public func acornParse(context: JSContext, code: String, loose: Bool) -> String? {
let script: String
if loose {
script = "JSON.stringify(acorn.loose.parse(`\(code)`))"
} else {
script = "JSON.stringify(acorn.parse(`\(code)`))"
}
let result = context.evaluateScript(script)
if let jsonStr = result?.toString() {
return jsonStr
} else {
return nil
}
}
}
extension TernBridge: TernExportProtocol {
func getFile(_ filename: String) -> String {
print("getfile: \(filename)")
if let content = fileContents[filename] {
return content
} else {
return ""
}
}
func callback(_ error: Any?, _ response: Any?) {
if let err = error {
guard err is NSNull else {
print("err: \(err)")
return
}
}
if let dict = response as? NSDictionary, let array = dict["completions"] as? NSArray, let start = dict["start"] as? Int, let end = dict["end"] as? Int {
var candidates = [TernCompletionObject]()
for item in array {
guard let dict = item as? NSDictionary else {
continue
}
guard let name = dict["name"] as? String else {
continue
}
let isKeyword = dict["isKeyword"] as? Bool
let type = dict["type"] as? String
let origin = dict["origin"] as? String
let object = TernCompletionObject(name: name, origin: origin, isKeyword: isKeyword, type: type)
candidates.append(object)
}
let range = NSMakeRange(start, end - start)
delegate?.completions(sender: self, candidates: candidates, range: range)
print(dict)
}
}
}
| 38.286822 | 196 | 0.546264 |
11918b5496cea394d4fbebde188bc2646d6f1749 | 1,489 | //
// Outputs.swift
// eqMac
//
// Created by Romans Kisils on 04/11/2019.
// Copyright © 2019 Romans Kisils. All rights reserved.
//
import Foundation
import AVFoundation
import AMCoreAudio
class Outputs {
static var current: AudioDeviceID? {
get {
return Application.enabled ? Application.selectedDevice?.id : AudioDevice.currentOutputDevice.id
}
}
static func isDeviceAllowed(_ device: AudioDevice) -> Bool {
return device.transportType != nil
&& SUPPORTED_TRANSPORT_TYPES.contains(device.transportType!)
&& !device.isInputOnlyDevice()
&& !device.name.contains("CADefaultDeviceAggregate")
&& device.uid != Constants.DRIVER_DEVICE_UID
&& !Constants.LEGACY_DRIVER_UIDS.contains(device.uid ?? "")
}
static func shouldAutoSelect (_ device: AudioDevice) -> Bool {
let types: [TransportType] = [.bluetooth, .bluetoothLE, .builtIn]
return isDeviceAllowed(device) && types.contains(device.transportType!)
}
static var allowedDevices: [AudioDevice] {
return AudioDevice.allOutputDevices().filter({ isDeviceAllowed($0) })
}
static let SUPPORTED_TRANSPORT_TYPES = [
TransportType.airPlay,
TransportType.bluetooth,
TransportType.bluetoothLE,
TransportType.builtIn,
TransportType.displayPort,
TransportType.fireWire,
TransportType.hdmi,
TransportType.pci,
TransportType.thunderbolt,
TransportType.usb,
TransportType.aggregate,
TransportType.virtual
]
}
| 28.09434 | 102 | 0.713902 |
382afbddca21733bffc19a49ebe6faf50c2d8364 | 1,395 | import SwiftUI
public protocol CardFaceChangeAnimatable {
associatedtype CardFaceChangeViewModifier: ViewModifier
var modifier: CardFaceChangeViewModifier { get }
var transition: AnyTransition { get }
}
struct Card3DRotationViewModifier: ViewModifier {
let isFacedUp: Bool
func body(content: Content) -> some View {
content
.rotation3DEffect(.radians(.pi), axis: (x: 0.0, y: 1.0, z: 0.0))
.rotation3DEffect(
isFacedUp ? .radians(.pi) : .zero,
axis: (x: 0.0, y: 1.0, z: 0.0),
perspective: 1/3
)
}
}
public struct CardFaceChange3DRotate: CardFaceChangeAnimatable {
let isFacedUp: Bool
public var modifier: some ViewModifier { Card3DRotationViewModifier(isFacedUp: isFacedUp) }
public let transition: AnyTransition = .opacity.animation(.linear(duration: 0.01).delay(2/10))
}
public extension CardFaceChangeAnimatable where Self == CardFaceChange3DRotate {
static func rotateTransition(isFacedUp: Bool) -> Self {
CardFaceChange3DRotate(isFacedUp: isFacedUp)
}
}
public struct CardNoneAnimation: CardFaceChangeAnimatable {
public let modifier = EmptyModifier()
public let transition: AnyTransition = .identity
}
public extension CardFaceChangeAnimatable where Self == CardNoneAnimation {
static var none: Self { CardNoneAnimation() }
}
| 31.704545 | 98 | 0.695341 |
1a41ae00e53a35a072af540e7ff16003b89ff581 | 2,899 | //
// LoginViewPresenterProtocol.swift
// Login-VIPER
//
// Created by Aashish Adhikari on 3/3/19.
// Copyright © 2019 Aashish Adhikari. All rights reserved.
//
import Foundation
class LoginViewInteractor: LoginViewInteractorInputProtocol{
var presenter: LoginViewInteractorOutputProtocol?
var remoteDataManager: LoginViewRemoteDataManagerInputProtocol?
var localDataManager: LoginViewLocalDataManagerInputProtocol?
private func validUserCredentials(username: String, password: String) -> (status:Bool, message: String) {
let isUserNameValid = isValidUserName(username: username)
let isPasswordValid = isValidPassword(password: password)
if !isUserNameValid.status{
return (isUserNameValid.status, isUserNameValid.message)
}
if !isPasswordValid.status{
return(isPasswordValid.status, isPasswordValid.message)
}
return (true,"")
}
private func isValidUserName(username: String) -> (status:Bool, message: String) {
if username.isEmpty{
return (false, "Username cannot be empty.")
}
return (true, "")
}
private func isValidPassword(password: String) -> (status:Bool, message: String){
if password.isEmpty{
return (false,"Password cannot be empty")
}
if password.count < 6 {
return (false,"Password should be 6 characters long.")
}
return (true, "" )
}
func postLoginRequest(username: String, password: String) {
let validator = validUserCredentials(username: username, password: password)
if validator.status{
let loginRequestModel = LoginRequestModel(username: username, password: password)
remoteDataManager?.postLoginRequest(loginModel: loginRequestModel)
}else{
onError(message: validator.message)
}
}
static func isUserAlreadyLoggedIn() -> Bool {
do{
let user = try LoginViewLocalDataManager.reteriveUser()
if let _ = user {
return true
}
}catch(let data){
print("error \(data)")
}
return false
}
}
extension LoginViewInteractor: LoginViewRemoteDataManagerOutputProtocol{
func onSucessfulLogin(token: String, user: UserData) {
// Save the User in Core Data
do{
try localDataManager?.saveUser(token: token, userData: user)
presenter?.didLoginCompleted()
}catch(let data){
#warning(" Need to catch error here! ")
print("Error: \(data)")
presenter?.onError(message: "Something went wrong. Please try again.")
}
}
func onError(message: String) {
presenter?.onError(message: message)
}
}
| 31.172043 | 110 | 0.617109 |
622766e9b840b1c5e1d9d574bd4ab1f36713c888 | 1,648 | //
// StopDetailPresentationAnimator.swift
// Fuel
//
// Created by Brad Leege on 1/22/18.
// Copyright © 2018 Brad Leege. All rights reserved.
//
import UIKit
class StopDetailPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var isPresenting: Bool
init(isPresenting: Bool) {
self.isPresenting = isPresenting
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let key = isPresenting ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from
let controller = transitionContext.viewController(forKey: key)!
if isPresenting {
transitionContext.containerView.addSubview(controller.view)
}
let presentedFrame = transitionContext.finalFrame(for: controller)
var dismissedFrame = presentedFrame
dismissedFrame.origin.y = transitionContext.containerView.frame.size.height
let initialFrame = isPresenting ? dismissedFrame : presentedFrame
let finalFrame = isPresenting ? presentedFrame : dismissedFrame
let animationDuration = transitionDuration(using: transitionContext)
controller.view.frame = initialFrame
UIView.animate(withDuration: animationDuration, animations: {
controller.view.frame = finalFrame
}) { finished in
transitionContext.completeTransition(finished)
}
}
}
| 32.96 | 116 | 0.699636 |
8f9e5c8df8bbf01fa0a3e07d9cf306a99324252d | 594 | //
// ViewController.swift
// HabitTracker
//
// Created by Yike Li on 11/20/20.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements() {
// Style the text forms
Utilities.styleFilledButton(signUpButton)
Utilities.styleHollowButton(loginButton)
}
}
| 18.5625 | 58 | 0.621212 |
ff612d56fc0d4a40cd45b464f768cc7295836378 | 3,006 | //
// ViewController.swift
// RACAlamofire
//
// Created by 郑林琴 on 16/7/23.
// Copyright © 2016年 Ice Butterfly. All rights reserved.
//
import UIKit
import Alamofire
import ReactiveCocoa
struct Server {
static var URL = ""
}
class ViewController: UIViewController {
let producer = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.rac_responseJSON().replayLazily(1)
@IBOutlet weak var button: UIButton!
// var action: Action<UIButton, AnyObject, NSError>!
var cocoaAction: CocoaAction!
override func viewDidLoad() {
super.viewDidLoad()
let signal = RACSignal.createSignal { (_) -> RACDisposable! in
return nil
}
signal.replay()
// self.button.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (_) in
// self.signalProducer()
// }
let action = Action<UIButton, AnyObject, NSError> { value -> SignalProducer<AnyObject, NSError> in
print("btn actioned")
let ss = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.rac_responseJSON().replayLazily(1).logEvents()
return ss
}
cocoaAction = CocoaAction(action, input: self.button)
self.button.addTarget(cocoaAction, action: CocoaAction.selector, forControlEvents: .TouchUpInside)
action.events.logEvents().observe { (ob) in
switch ob{
case .Next(let value):
print("event next \("event")")
case .Completed:
print("event complete")
case .Interrupted:
print("event interrupted")
case .Failed(_):
print("event failed")
}
}
}
func signalProducer(){
var _signal: Signal<AnyObject, NSError>!
producer.startWithSignal({ (signal, dispose) in
_signal = signal
})
_signal.observeNext({ (next) in
print("next: ")
})
_signal.observeFailed({ (err) in
print("error:")
})
_signal.observeCompleted({
print("completed")
})
producer.startWithNext { (ob) in
print("producer next1")
}
producer.startWithNext { (ob) in
print("producer next2")
}
}
func signal(){
let signal = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.rac_responseJSON()
signal.startWithSignal { (signal, dispose) in
signal.observeNext({ (_) in
})
}
}
}
| 24.048 | 106 | 0.503992 |
72d0ce291b1560fc0b696365772b3616e2999158 | 1,217 | //
// BaseViewModel.swift
// DouYuZB
//
// Created by RandyWei on 2019/9/15.
// Copyright © 2019 RandyWei. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroups:[AnchorGroup] = [AnchorGroup]()
func requestAnchorData(url:String,params:[String:String]? = nil,isGroup:Bool? = true,callback:@escaping ()->()) {
Network.request(url: url, methodType: MethodType.GET,params: params) { (result) in
//将json转成字典
guard result is [String: AnyObject] else {return}
//根据获取data数组
guard let dataArray = result["data"] as? [[String:AnyObject]] else {return}
if isGroup == true {
for dict in dataArray {
let group = AnchorGroup(dict: dict)
self.anchorGroups.append(group)
}
} else {
let group = AnchorGroup()
for dict in dataArray {
let anchorModel = AnchorModel(dict: dict)
group.anchors.append(anchorModel)
}
self.anchorGroups.append(group)
}
callback()
}
}
}
| 31.205128 | 118 | 0.52424 |
fc9762e1c1c108771eeb4495adc67c241a9a90db | 461 | public struct StaticClientRetriever: ClientRetriever {
let clients: [String: OAuthClient]
public init(clients: [OAuthClient]) {
self.clients = clients.reduce([String: OAuthClient]()) { (dict, client) -> [String: OAuthClient] in
var dict = dict
dict[client.clientID] = client
return dict
}
}
public func getClient(clientID: String) -> OAuthClient? {
return clients[clientID]
}
}
| 27.117647 | 107 | 0.613883 |
e6540542093b43086fccbda5a246281521f77150 | 1,594 |
import UIKit
private let kRankWeekCellID = "kRankWeekCellID"
class RankWeekDetailViewController: RankDateDetailViewController {
fileprivate lazy var rankVM: RankViewModel = RankViewModel()
override init(rankType: RankType) {
super.init(rankType: rankType)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets.zero
tableView.register(UINib(nibName: "RankWeekCell", bundle: nil), forCellReuseIdentifier: kRankWeekCellID)
}
override func loadRankData() {
rankVM.loadRankWeekData(rankType) {
self.tableView.reloadData()
}
}
}
extension RankWeekDetailViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return rankVM.weekModels.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rankVM.weekModels[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kRankWeekCellID, for: indexPath) as! RankWeekCell
cell.weekModel = rankVM.weekModels[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "主播周星榜" : "富豪周星榜"
}
}
| 30.653846 | 114 | 0.681932 |
e93a5b57e02eec18211ebedc80460a5b2aa5e2fd | 840 | //
// NotificationView.swift
// WatchLandmarks Extension
//
// Created by Adam Becevello on 2021-01-21.
//
import SwiftUI
struct NotificationView: View {
var title: String?
var message: String?
var landmark: Landmark?
var body: some View {
VStack {
if landmark != nil {
CircleImage(image: landmark!.image.resizable())
.scaledToFit()
}
Text(title ?? "Unknown Landmark")
.font(.headline)
Divider()
Text(message ?? "You are within 5 miles of one of your favorite landmarks.")
.font(.caption)
}
.lineLimit(0)
}
}
struct NotificationView_Previews: PreviewProvider {
static var previews: some View {
Group {
NotificationView()
NotificationView(title: "Turtle Rock",
message: "You are within 5 miles of Turtle Rock.",
landmark: ModelData().landmarks[0])
}
}
}
| 19.090909 | 79 | 0.660714 |
79f5ee026eee064bea2476aeb3157555479bac2f | 4,157 | import ARKit
import ARKit_CoreLocation
import Combine
import CoreLocation
import SceneKit
import SwiftUI
// MARK: - ARView
struct ARView: UIViewRepresentable {
// MARK: property
@Binding var isOn: Bool
@Binding var bathymetryTiles: [BathymetryTile]
@Binding var bathymetries: [Bathymetry]
@Binding var waterSurface: Double
let dispatchGroup = DispatchGroup()
// MARK: UIViewRepresentable
func makeUIView(context: UIViewRepresentableContext<ARView>) -> UIARView {
let uiArView = UIARView(trackingType: .orientationTracking)
uiArView.locationEstimateDelegate = context.coordinator
uiArView.arViewDelegate = context.coordinator
uiArView.run()
return uiArView
}
func updateUIView(_ uiView: UIARView, context: UIViewRepresentableContext<ARView>) {
dispatchGroup.notify(queue: .main) {
uiView.locationNodes.forEach {
uiView.removeLocationNode(locationNode: $0)
}
if !isOn {
return
}
let altitude = uiView.sceneLocationManager.currentLocation?.altitude ?? 0
bathymetryTiles.forEach {
uiView.addLocationNodeWithConfirmedLocation(
locationNode: ARBathymetryNode(
bathymetryTile: $0,
altitude: altitude,
waterSurface: waterSurface
)
)
}
}
}
static func dismantleUIView(_ uiView: ARView.UIViewType, coordinator: ARView.Coordinator) {
uiView.pause()
}
func makeCoordinator() -> ARView.Coordinator {
Coordinator(self)
}
// MARK: Coordinator
final class Coordinator: NSObject, SceneLocationViewEstimateDelegate, ARSCNViewDelegate, ARSessionDelegate {
var control: ARView
init(_ control: ARView) {
self.control = control
}
// MARK: SceneLocationViewEstimateDelegate
func didAddSceneLocationEstimate(sceneLocationView: SceneLocationView, position: SCNVector3, location: CLLocation) {
let altitude = sceneLocationView.sceneLocationManager.currentLocation?.altitude ?? 0
sceneLocationView.locationNodes.forEach {
$0.location = CLLocation(coordinate: $0.location.coordinate, altitude: altitude)
}
}
func didRemoveSceneLocationEstimate(sceneLocationView: SceneLocationView, position: SCNVector3, location: CLLocation) {
}
// MARK: ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
control.dispatchGroup.enter()
}
func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
control.dispatchGroup.leave()
}
}
}
// MARK: - UIARView
final class UIARView: SceneLocationView {
// MARK: property
var cancellables = Set<AnyCancellable>()
// MARK: initializer
// swiftlint:disable discouraged_optional_collection
override private init(frame: CGRect, options: [String: Any]? = nil) {
super.init(frame: frame, options: options)
allowsCameraControl = false
NotificationCenter
.default
.publisher(for: UIApplication.didBecomeActiveNotification)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.run()
}
.store(in: &cancellables)
NotificationCenter
.default
.publisher(for: UIApplication.willResignActiveNotification)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.pause()
}
.store(in: &cancellables)
}
// swiftlint:enable discouraged_optional_collection
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - ARView_Previews
struct ARView_Previews: PreviewProvider {
static var previews: some View {
ARView(
isOn: Binding<Bool>(
get: { true },
set: { _ in }
),
bathymetryTiles: Binding<[BathymetryTile]>(
get: { [] },
set: { _ in }
),
bathymetries: Binding<[Bathymetry]>(
get: { .default },
set: { _ in }
),
waterSurface: Binding<Double>(
get: { -1.0 },
set: { _ in }
)
)
}
}
| 26.993506 | 123 | 0.670676 |
4a418ee4b070533bd4bb2859328bd95dd50e9e41 | 420 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
import XCTest
class ___FILEBASENAME___WireframeTests: XCTestCase {
var wireframe : ___FILEBASENAME___Wireframe!
override func setUp() {
super.setUp()
wireframe = ___FILEBASENAME___Wireframe()
}
func testInstantiation() {
XCTAssertNotNil(wireframe)
}
}
| 16.8 | 52 | 0.692857 |
ed869052f7d72b181c252ba76ce2003b12961ff9 | 4,762 | // File created from simpleScreenTemplate
// $ createSimpleScreen.sh DeviceVerification/Verified DeviceVerificationVerified
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
protocol KeyVerificationVerifiedViewControllerDelegate: class {
func keyVerificationVerifiedViewControllerDidTapSetupAction(_ viewController: KeyVerificationVerifiedViewController)
func keyVerificationVerifiedViewControllerDidCancel(_ viewController: KeyVerificationVerifiedViewController)
}
final class KeyVerificationVerifiedViewController: UIViewController {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private weak var doneButton: RoundedButton!
// MARK: Private
private var theme: Theme!
private var verificationKind: KeyVerificationKind = .user
// MARK: Public
weak var delegate: KeyVerificationVerifiedViewControllerDelegate?
// MARK: - Setup
class func instantiate(with verificationKind: KeyVerificationKind) -> KeyVerificationVerifiedViewController {
let viewController = StoryboardScene.KeyVerificationVerifiedViewController.initialScene.instantiate()
viewController.theme = ThemeService.shared().theme
viewController.verificationKind = verificationKind
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.vc_removeBackTitle()
self.setupViews()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Hide back button
self.navigationItem.setHidesBackButton(true, animated: animated)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func setupViews() {
let bodyTitle: String
let informationText: String
switch self.verificationKind {
case .otherSession:
bodyTitle = VectorL10n.deviceVerificationVerifiedTitle
informationText = VectorL10n.keyVerificationVerifiedOtherSessionInformation
case .newSession:
bodyTitle = VectorL10n.keyVerificationVerifiedNewSessionTitle
informationText = VectorL10n.keyVerificationVerifiedNewSessionInformation
case .thisSession:
bodyTitle = VectorL10n.deviceVerificationVerifiedTitle
informationText = VectorL10n.keyVerificationVerifiedThisSessionInformation
case .user:
bodyTitle = VectorL10n.deviceVerificationVerifiedTitle
informationText = VectorL10n.keyVerificationVerifiedUserInformation
}
self.title = self.verificationKind.verificationTitle
self.titleLabel.text = bodyTitle
self.informationLabel.text = informationText
self.doneButton.setTitle(VectorL10n.deviceVerificationVerifiedGotItButton, for: .normal)
}
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.titleLabel.textColor = theme.textPrimaryColor
self.informationLabel.textColor = theme.textPrimaryColor
self.doneButton.update(theme: theme)
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
// MARK: - Actions
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
@IBAction private func doneButtonAction(_ sender: Any) {
self.delegate?.keyVerificationVerifiedViewControllerDidTapSetupAction(self)
}
}
| 35.274074 | 137 | 0.716296 |
e27f25f548e52455bdfddc2b2f7d1a3dd0fbe844 | 2,145 | //
// AppDelegate.swift
// SwiftDP
//
// Created by YoonTaesup on 2016. 4. 27..
// Copyright © 2016년 YoonTaesup. 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:.
}
}
| 45.638298 | 285 | 0.75338 |
db9ca93b6ca469b73b18a4f291b4561a82a0c495 | 2,841 | //
// ButtonViewController.swift
// Animatify
//
// Created by Shubham Singh on 29/06/20.
// Copyright © 2020 Shubham Singh. All rights reserved.
//
import UIKit
class ButtonViewController: UIViewController {
override class func description() -> String {
return "ButtonViewController"
}
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var instructionLabel: UILabel!
var instructions: [String] = [
"Create a UIViewControllerAnimatedTransitioning class.",
"It has an animateTransition method where the animation between the viewController should be defined.",
"After defining the class, UIViewControllerTransitioningDelegate has to be inherited by the viewController. ",
"The delegate has 2 methods each for presenting and dissmissed viewController.",
]
// MARK:- lifecycle methods for the viewController
override func viewDidLoad() {
super.viewDidLoad()
self.setInstructions()
}
// MARK:- action outlets for the viewController
@IBAction func backButtonPressed(_ sender: Any) {
self.dismiss(animated: true)
}
// MARK:- functions for the viewController
func setInstructions(){
/// getting the initial value for the y axis
var dy: CGFloat = self.instructionLabel.frame.origin.y + self.instructionLabel.frame.height + 24
let stepLabelSize: CGFloat = 42
for (ix,instruction) in instructions.enumerated() {
let stepLabel = UILabel()
stepLabel.font = UIFont(name: "MuseoModerno-Medium", size: 21)
stepLabel.text = "\(ix + 1)"
stepLabel.textAlignment = .center
stepLabel.textColor = UIColor.white
stepLabel.setBorderAndCorner(borderColor: UIColor.white, borderWidth: 2, cornerRadius: 21)
stepLabel.frame = CGRect(x: 24, y: dy + stepLabel.intrinsicContentSize.height / 2, width: stepLabelSize, height: stepLabelSize)
let descriptionLabel = UILabel()
descriptionLabel.font = UIFont(name: "Montserrat-Regular", size: 18)
descriptionLabel.textColor = UIColor.white
descriptionLabel.text = instruction
descriptionLabel.numberOfLines = 5
descriptionLabel.frame = CGRect(x: stepLabelSize * 2, y: dy + (descriptionLabel.intrinsicContentSize.height / 1.75), width: (self.view.frame.width - (24 * 3) - stepLabelSize), height: descriptionLabel.intrinsicContentSize.height)
descriptionLabel.sizeToFit()
dy += descriptionLabel.frame.size.height + 24
// adding the labels to the scrollview
self.view.addSubview(stepLabel)
self.view.addSubview(descriptionLabel)
}
}
}
| 39.458333 | 241 | 0.649771 |
accc68229fa507dc5e32310fe812ff4282eaacf4 | 3,717 | //
// String+Additions.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-05-27.
//
// ---------------------------------------------------------------------------
//
// © 2016-2019 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
private let kMaxEscapesCheckLength = 8
extension String {
/// return copied string to make sure the string is not a kind of NSMutableString.
var immutable: String {
return NSString(string: self) as String
}
/// unescape backslashes
var unescaped: String {
// -> According to the following sentence in the Swift 3 documentation, these are the all combinations with backslash.
// > The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
let entities = ["\0": "0",
"\t": "t",
"\n": "n",
"\r": "r",
"\"": "\"",
"\'": "'",
]
return entities
.mapValues { try! NSRegularExpression(pattern: "(?<!\\\\)(?:\\\\\\\\)*(\\\\" + $0 + ")") }
.reduce(self) { (string, entity) in
entity.value.matches(in: string, range: string.nsRange)
.map { $0.range(at: 1) }
.compactMap { Range($0, in: string) }
.reversed()
.reduce(string) { $0.replacingCharacters(in: $1, with: entity.key) }
}
}
}
extension StringProtocol where Self.Index == String.Index {
/// range of the line containing a given index
func lineRange(at index: Index, excludingLastLineEnding: Bool = false) -> Range<Index> {
return self.lineRange(for: index..<index, excludingLastLineEnding: excludingLastLineEnding)
}
/// line range adding ability to exclude last line ending character if exists
func lineRange(for range: Range<Index>, excludingLastLineEnding: Bool) -> Range<Index> {
let lineRange = self.lineRange(for: range)
guard excludingLastLineEnding,
let index = self.index(lineRange.upperBound, offsetBy: -1, limitedBy: lineRange.lowerBound),
self[index] == "\n" else { return lineRange }
return lineRange.lowerBound..<self.index(before: lineRange.upperBound)
}
/// check if character at the index is escaped with backslash
func isCharacterEscaped(at index: Index) -> Bool {
let escapes = self[..<index].suffix(kMaxEscapesCheckLength).reversed().prefix { $0 == "\\" }
return !escapes.count.isMultiple(of: 2)
}
}
// MARK: NSRange based
extension String {
/// check if character at the location in UTF16 is escaped with backslash
func isCharacterEscaped(at location: Int) -> Bool {
let locationIndex = String.Index(utf16Offset: location, in: self)
return self.isCharacterEscaped(at: locationIndex)
}
}
| 32.605263 | 182 | 0.575195 |
617ab57943d19632e920dd310a61a97106822ae0 | 164 | import PackageDescription
let package = Package(
dependencies: [
.Package(url: "https://github.com/CaramelForSwift/CUv.git", majorVersion: 1)
]
)
| 18.222222 | 84 | 0.676829 |
dba953fae9a9a7a60231e4b012e6a955e16d0493 | 472 | //
// AppDelegate.swift
// FoodApp
//
// Created by Admin on 17/12/2020.
// Copyright © 2020 Adnan Ali. 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
}
}
| 23.6 | 145 | 0.720339 |
b99c18a0bdab1ddff938c628571c07696bae0262 | 533 | //
// Hours.swift
// What's Poppin?
//
// Created by David Hodge on 2/11/15.
// Copyright (c) 2015 Genesis Apps, LLC. All rights reserved.
//
import UIKit
class Hours: NSObject {
let openingTime: String
let closingTime: String
override init() {
openingTime = "-1"
closingTime = "-1"
}
init(openingTime theOpeningTime: String, closingTime theClosingTime: String)
{
openingTime = theOpeningTime
closingTime = theClosingTime
}
}
| 18.37931 | 80 | 0.587242 |
5b578b70c84fe24d4333b600fdf5311a342ad3df | 6,837 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import CoreGraphics
/**
The frame of a layout and the frames of its sublayouts.
*/
public struct LayoutArrangement {
public let layout: Layout
public let frame: CGRect
public let sublayouts: [LayoutArrangement]
public init(layout: Layout, frame: CGRect, sublayouts: [LayoutArrangement]) {
self.layout = layout
self.frame = frame
self.sublayouts = sublayouts
}
/**
Creates the views for the layout and adds them as subviews to the provided view.
Existing subviews of the provided view will be removed.
If no view is provided, then a new one is created and returned.
MUST be run on the main thread.
- parameter view: The layout's views will be added as subviews to this view, if provided.
- parameter direction: The natural direction of the layout (default: .LeftToRight).
If it does not match the user's language direction, then the layout's views will be flipped horizontally.
Only provide this parameter if you want to test the flipped version of your layout,
or if your layouts are declared for right-to-left languages and you want them to get flipped for left-to-right languages.
- returns: The root view. If a view was provided, then the same view will be returned, otherwise, a new one will be created.
*/
@discardableResult
public func makeViews(in view: View? = nil, direction: UserInterfaceLayoutDirection = .leftToRight) -> View {
return makeViews(in: view, direction: direction, prepareAnimation: false)
}
/**
Prepares the view to be animated to this arrangement.
Call `prepareAnimation(for:direction)` before the animation block.
Call the returned animation's `apply()` method inside the animation block.
```
let animation = nextLayout.arrangement().prepareAnimation(for: rootView, direction: .RightToLeft)
View.animateWithDuration(5.0, animations: {
animation.apply()
})
```
Subviews are reparented for the new arrangement, if necessary, but frames are adjusted so locations don't change.
No frames or configurations of the new arrangement are applied until `apply()` is called on the returned animation object.
MUST be run on the main thread.
*/
public func prepareAnimation(for view: View, direction: UserInterfaceLayoutDirection = .leftToRight) -> Animation {
makeViews(in: view, direction: direction, prepareAnimation: true)
return Animation(arrangement: self, rootView: view, direction: direction)
}
/**
Helper function for `makeViews(in:direction:)` and `prepareAnimation(for:direction:)`.
See the documentation for those two functions.
*/
@discardableResult
private func makeViews(in view: View? = nil, direction: UserInterfaceLayoutDirection, prepareAnimation: Bool) -> View {
let recycler = ViewRecycler(rootView: view)
let views = makeSubviews(from: recycler, prepareAnimation: prepareAnimation)
let rootView: View
if let view = view {
for subview in views {
view.addSubview(subview, maintainCoordinates: prepareAnimation)
}
rootView = view
} else if let view = views.first, views.count == 1 {
// We have a single view so it is our root view.
rootView = view
} else {
// We have multiple views so create a root view.
rootView = View(frame: frame)
for subview in views {
if !prepareAnimation {
// Unapply the offset that was applied in makeSubviews()
subview.frame = subview.frame.offsetBy(dx: -frame.origin.x, dy: -frame.origin.y)
}
rootView.addSubview(subview)
}
}
recycler.purgeViews()
if !prepareAnimation {
// Horizontally flip the view frames if direction does not match the root view's language direction.
if rootView.userInterfaceLayoutDirection != direction {
flipSubviewsHorizontally(rootView)
}
}
return rootView
}
/// Flips the right and left edges of the view's subviews.
private func flipSubviewsHorizontally(_ view: View) {
for subview in view.subviews {
subview.frame.origin.x = view.frame.width - subview.frame.maxX
flipSubviewsHorizontally(subview)
}
}
/// Returns the views for the layout and all of its sublayouts.
private func makeSubviews(from recycler: ViewRecycler, prepareAnimation: Bool) -> [View] {
let subviews = sublayouts.flatMap({ (sublayout: LayoutArrangement) -> [View] in
return sublayout.makeSubviews(from: recycler, prepareAnimation: prepareAnimation)
})
// If we are preparing an animation, then we don't want to update frames or configure views.
if layout.needsView, let view = recycler.makeOrRecycleView(havingViewReuseId: layout.viewReuseId, viewProvider: layout.makeView) {
if !prepareAnimation {
view.frame = frame
layout.configure(baseTypeView: view)
}
for subview in subviews {
// If a view gets reparented and we are preparing an animation, then
// make sure that its absolute position on the screen does not change.
view.addSubview(subview, maintainCoordinates: prepareAnimation)
}
return [view]
} else {
if !prepareAnimation {
for subview in subviews {
subview.frame = subview.frame.offsetBy(dx: frame.origin.x, dy: frame.origin.y)
}
}
return subviews
}
}
}
extension View {
/**
Similar to `addSubview()` except if `maintainCoordinates` is true, then the view's frame
will be adjusted so that its absolute position on the screen does not change.
*/
fileprivate func addSubview(_ view: View, maintainCoordinates: Bool) {
if maintainCoordinates {
let frame = view.convertToAbsoluteCoordinates(view.frame)
addSubview(view)
view.frame = view.convertFromAbsoluteCoordinates(frame)
} else {
addSubview(view)
}
}
}
| 42.465839 | 138 | 0.65321 |
11c0e3660f5b7cb597e25766e2c9c1d1c3e1250c | 745 | //
// AppDelegate.swift
// DecomposedAR
//
// Created by Adam Bell on 5/23/20.
// Copyright © 2020 Adam Bell. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var rootViewController: ViewController!
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.rootViewController = ViewController(nibName: nil, bundle: nil)
self.window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = rootViewController
window!.makeKeyAndVisible()
return true
}
}
| 24.032258 | 143 | 0.748993 |
0173cbe026adbb4ac78fc0f7f07baac9246f16c7 | 13,194 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience %s | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience -O %s
// CHECK: %swift.type = type { [[INT:i32|i64]] }
// CHECK: @_TWvdvC16class_resilience26ClassWithResilientProperty1sV16resilient_struct4Size = {{(protected )?}}global [[INT]] 0
// CHECK: @_TWvdvC16class_resilience26ClassWithResilientProperty5colorVs5Int32 = {{(protected )?}}global [[INT]] 0
// CHECK: @_TWvdvC16class_resilience33ClassWithResilientlySizedProperty1rV16resilient_struct9Rectangle = {{(protected )?}}global [[INT]] 0
// CHECK: @_TWvdvC16class_resilience33ClassWithResilientlySizedProperty5colorVs5Int32 = {{(protected )?}}global [[INT]] 0
// CHECK: @_TWvdvC16class_resilience14ResilientChild5fieldVs5Int32 = {{(protected )?}}global [[INT]] {{12|16}}
// CHECK: @_TWvivC16class_resilience21ResilientGenericChild5fieldVs5Int32 = {{(protected )?}}global [[INT]] {{56|88}}
// CHECK: @_TWvdvC16class_resilience28ClassWithMyResilientProperty1rVS_17MyResilientStruct = {{(protected )?}}constant [[INT]] {{12|16}}
// CHECK: @_TWvdvC16class_resilience28ClassWithMyResilientProperty5colorVs5Int32 = {{(protected )?}}constant [[INT]] {{16|20}}
// CHECK: @_TWvdvC16class_resilience30ClassWithIndirectResilientEnum1sO14resilient_enum10FunnyShape = {{(protected )?}}constant [[INT]] {{12|16}}
// CHECK: @_TWvdvC16class_resilience30ClassWithIndirectResilientEnum5colorVs5Int32 = {{(protected )?}}constant [[INT]] {{16|24}}
import resilient_class
import resilient_struct
import resilient_enum
// Concrete class with resilient stored property
public class ClassWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
// Concrete class with resilient stored property that
// is fixed-layout inside this resilience domain
public struct MyResilientStruct {
public let x: Int32
}
public class ClassWithMyResilientProperty {
public let r: MyResilientStruct
public let color: Int32
public init(r: MyResilientStruct, color: Int32) {
self.r = r
self.color = color
}
}
// Enums with indirect payloads are fixed-size
public class ClassWithIndirectResilientEnum {
public let s: FunnyShape
public let color: Int32
public init(s: FunnyShape, color: Int32) {
self.s = s
self.color = color
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientChild : ResilientOutsideParent {
public let field: Int32 = 0
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> {
public let field: Int32 = 0
}
// Superclass is resilient and has a resilient value type payload,
// but everything is in one module
public class MyResilientParent {
public let s: MyResilientStruct = MyResilientStruct(x: 0)
}
public class MyResilientChild : MyResilientParent {
public let field: Int32 = 0
}
// ClassWithResilientProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaC16class_resilience26ClassWithResilientProperty()
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_TMLC16class_resilience26ClassWithResilientProperty
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[METADATA:%.*]] = call %swift.type* @swift_getResilientMetadata(
// CHECK-NEXT: store %swift.type* [[METADATA]], %swift.type** @_TMLC16class_resilience26ClassWithResilientProperty
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// ClassWithResilientProperty.color getter
// CHECK-LABEL: define{{( protected)?}} i32 @_TFC16class_resilience26ClassWithResilientPropertyg5colorVs5Int32(%C16class_resilience26ClassWithResilientProperty*)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_TWvdvC16class_resilience26ClassWithResilientProperty5colorVs5Int32
// CHECK-NEXT: [[PTR:%.*]] = bitcast %C16class_resilience26ClassWithResilientProperty* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Vs5Int32*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Vs5Int32, %Vs5Int32* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ClassWithResilientlySizedProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaC16class_resilience33ClassWithResilientlySizedProperty()
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_TMLC16class_resilience33ClassWithResilientlySizedProperty
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[METADATA:%.*]] = call %swift.type* @swift_getResilientMetadata(
// CHECK-NEXT: store %swift.type* [[METADATA]], %swift.type** @_TMLC16class_resilience33ClassWithResilientlySizedProperty
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// ClassWithResilientlySizedProperty.color getter
// CHECK-LABEL: define{{( protected)?}} i32 @_TFC16class_resilience33ClassWithResilientlySizedPropertyg5colorVs5Int32(%C16class_resilience33ClassWithResilientlySizedProperty*)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_TWvdvC16class_resilience33ClassWithResilientlySizedProperty5colorVs5Int32
// CHECK-NEXT: [[PTR:%.*]] = bitcast %C16class_resilience33ClassWithResilientlySizedProperty* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Vs5Int32*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Vs5Int32, %Vs5Int32* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ClassWithIndirectResilientEnum.color getter
// CHECK-LABEL: define{{( protected)?}} i32 @_TFC16class_resilience30ClassWithIndirectResilientEnumg5colorVs5Int32(%C16class_resilience30ClassWithIndirectResilientEnum*)
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %C16class_resilience30ClassWithIndirectResilientEnum, %C16class_resilience30ClassWithIndirectResilientEnum* %0, i32 0, i32 2
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Vs5Int32, %Vs5Int32* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} i32 @_TFC16class_resilience14ResilientChildg5fieldVs5Int32(%C16class_resilience14ResilientChild*)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_TWvdvC16class_resilience14ResilientChild5fieldVs5Int32
// CHECK-NEXT: [[PTR:%.*]] = bitcast %C16class_resilience14ResilientChild* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Vs5Int32*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Vs5Int32, %Vs5Int32* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: ret i32 [[FIELD_VALUE]]
// ResilientGenericChild.field getter
// CHECK-LABEL: define{{( protected)?}} i32 @_TFC16class_resilience21ResilientGenericChildg5fieldVs5Int32(%C16class_resilience21ResilientGenericChild*)
// FIXME: we could eliminate the unnecessary isa load by lazily emitting
// metadata sources in EmitPolymorphicParameters
// CHECK: load %swift.type*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds %C16class_resilience21ResilientGenericChild, %C16class_resilience21ResilientGenericChild* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]]
// CHECK-NEXT: [[INDIRECT_OFFSET:%.*]] = load [[INT]], [[INT]]* @_TWvivC16class_resilience21ResilientGenericChild5fieldVs5Int32
// CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[INDIRECT_OFFSET]]
// CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]]
// CHECK-NEXT: [[OBJECT:%.*]] = bitcast %C16class_resilience21ResilientGenericChild* %0 to i8*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Vs5Int32*
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Vs5Int32, %Vs5Int32* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: ret i32 [[RESULT]]
// MyResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} i32 @_TFC16class_resilience16MyResilientChildg5fieldVs5Int32(%C16class_resilience16MyResilientChild*)
// CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %C16class_resilience16MyResilientChild, %C16class_resilience16MyResilientChild* %0, i32 0, i32 2
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Vs5Int32, %Vs5Int32* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: ret i32 [[RESULT]]
// ClassWithResilientProperty metadata instantiation function
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_ClassWithResilientProperty(%swift.type_pattern*, i8**)
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(
// CHECK: [[SIZE_METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size()
// CHECK: call void @swift_initClassMetadata_UniversalStrategy(
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_TWvdvC16class_resilience26ClassWithResilientProperty1sV16resilient_struct4Size
// CHECK-native-NEXT: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{13|16}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_TWvdvC16class_resilience26ClassWithResilientProperty5colorVs5Int32
// CHECK: ret %swift.type* [[METADATA]]
// ClassWithResilientlySizedProperty metadata instantiation function
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_ClassWithResilientlySizedProperty(%swift.type_pattern*, i8**)
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(
// CHECK: [[RECTANGLE_METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct9Rectangle()
// CHECK: call void @swift_initClassMetadata_UniversalStrategy(
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{11|14}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_TWvdvC16class_resilience33ClassWithResilientlySizedProperty1rV16resilient_struct9Rectangle
// CHECK-native-NEXT: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_TWvdvC16class_resilience33ClassWithResilientlySizedProperty5colorVs5Int32
// CHECK: ret %swift.type* [[METADATA]]
| 50.746154 | 182 | 0.711536 |
46b46dcf37636e2fa7aff07fc45bdae393c447df | 536 | //
// BaseUIProtocol.swift
// BaseUtils
//
// Created by Etienne Goulet-Lang on 12/3/16.
// Copyright © 2016 Etienne Goulet-Lang. All rights reserved.
//
import Foundation
import UIKit
public protocol BaseUIProtocol {
func initialize()
func createAndAddSubviews()
func addGestureRecognition()
func removeGestureRecognition()
func frameUpdate()
func addTap(_ view: UIView, selector: Selector)
func addLongPress(_ view: UIView, selector: String)
func animate(_ block: @escaping ()->Void)
}
| 22.333333 | 62 | 0.701493 |
e8b61fd1704955ba8e33be7ecfbfbf3d955b37e2 | 3,383 | //
// SettingsViewController.swift
// coronasurveys-ios
//
// Created by Josep Bordes Jové on 18/05/2020.
// Copyright (c) 2020 Inqbarna. 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
protocol SettingsDisplayLogic: AnyObject {
func displayView(viewModel: Settings.PrepareView.ViewModel)
func displayToggleNotification(viewModel: Settings.ToggleNotification.ViewModel)
}
class SettingsViewController: UIViewController, SettingsDisplayLogic {
var interactor: SettingsBusinessLogic?
var router: (NSObjectProtocol & SettingsRoutingLogic & SettingsDataPassing)?
// MARK: View
private lazy var settingsView: SettingsView = {
let view = SettingsView()
view.delegate = self
return view
}()
// MARK: Object lifecycle
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Setup
private func setup() {
let viewController = self
let interactor = SettingsInteractor()
let presenter = SettingsPresenter()
let router = SettingsRouter()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
presenter.viewController = viewController
router.viewController = viewController
router.dataStore = interactor
}
// MARK: View lifecycle
override func loadView() {
super.loadView()
view = settingsView
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
prepareView()
}
// MARK: Setup methods
func setupNavigationBar() {
navigationController?.navigationBar.tintColor = Color.black
let leftBarButtonItem = UIBarButtonItem(image: Icon.xmark, style: .plain, target: self, action: #selector(dismissViewController))
navigationItem.leftBarButtonItem = leftBarButtonItem
}
// MARK: Prepare view
func prepareView() {
let request = Settings.PrepareView.Request()
interactor?.prepareView(request: request)
}
func displayView(viewModel: Settings.PrepareView.ViewModel) {
title = viewModel.title
let settingsViewVM = SettingsViewVM(sections: viewModel.sections)
settingsView.display(viewModel: settingsViewVM)
}
private func toggleNotification(newValue: Bool) {
let request = Settings.ToggleNotification.Request(newValue: newValue)
interactor?.toggleNotification(request: request)
}
func displayToggleNotification(viewModel: Settings.ToggleNotification.ViewModel) {
let settingsViewVM = SettingsViewVM(sections: viewModel.sections)
settingsView.display(viewModel: settingsViewVM)
}
// MARK: Helpers
@objc private func dismissViewController() {
dismiss(animated: true, completion: nil)
}
}
extension SettingsViewController: SettingsViewDelegate {
func didUpdateNotifications(_ uiSwitch: UISwitch) {
toggleNotification(newValue: uiSwitch.isOn)
}
}
| 28.91453 | 137 | 0.691694 |
0addc16be012d8b54bb3fbba0797fbce49ac0c6e | 928 | //
// SquareCashStyleViewController.swift
// FlexibleHeightBarDemo
//
// Created by Vicente Suarez on 1/8/17.
// Copyright © 2017 Vicente Suarez. All rights reserved.
//
import UIKit
import FlexibleHeightBar
class SquareCashStyleViewController: UIViewController {
let delegateHandler = TableViewDelegateHandler()
let dataSourceHandler = TableViewDataSourceHandler()
@IBOutlet var heightConstraint: NSLayoutConstraint!
@IBOutlet var customBar: SquareCashFlexibleHeightBar!
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = dataSourceHandler
tableView.delegate = delegateHandler
delegateHandler.otherDelegate = customBar.behaviorDefiner
customBar.heightConstraint = heightConstraint
tableView.contentInset = UIEdgeInsetsMake(customBar.maximumBarHeight, 0.0, 0.0, 0.0)
}
}
| 30.933333 | 92 | 0.742457 |
08465375b264efef2e28fb50eab35297543ebee3 | 3,045 | import UIKit
public class StyleKitMarker: NSObject {
//// Drawing Methods
@objc dynamic public class func drawMarker(frame: CGRect = CGRect(x: 57, y: 27, width: 50, height: 50), innerColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000), shadowColor: UIColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000), pinColor: UIColor = UIColor(red: 0.290, green: 0.565, blue: 0.886, alpha: 1.000), strokeColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Group
//// Oval 2 Drawing
context.saveGState()
context.setAlpha(0.1)
let oval2Path = UIBezierPath(ovalIn: CGRect(x: 10, y: 40.61, width: 19, height: 8))
shadowColor.setFill()
oval2Path.fill()
context.restoreGState()
//// Group 2
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 18.04, y: 43.43))
bezier2Path.addCurve(to: CGPoint(x: 20.96, y: 43.43), controlPoint1: CGPoint(x: 18.85, y: 44.18), controlPoint2: CGPoint(x: 20.16, y: 44.17))
bezier2Path.addCurve(to: CGPoint(x: 37, y: 19.55), controlPoint1: CGPoint(x: 20.96, y: 43.43), controlPoint2: CGPoint(x: 37, y: 29.24))
bezier2Path.addCurve(to: CGPoint(x: 19.5, y: 2), controlPoint1: CGPoint(x: 37, y: 9.86), controlPoint2: CGPoint(x: 29.16, y: 2))
bezier2Path.addCurve(to: CGPoint(x: 2, y: 19.55), controlPoint1: CGPoint(x: 9.84, y: 2), controlPoint2: CGPoint(x: 2, y: 9.86))
bezier2Path.addCurve(to: CGPoint(x: 18.04, y: 43.43), controlPoint1: CGPoint(x: 2, y: 29.24), controlPoint2: CGPoint(x: 18.04, y: 43.43))
bezier2Path.close()
bezier2Path.usesEvenOddFillRule = true
pinColor.setFill()
bezier2Path.fill()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 18.04, y: 43.43))
bezier3Path.addCurve(to: CGPoint(x: 20.96, y: 43.43), controlPoint1: CGPoint(x: 18.85, y: 44.18), controlPoint2: CGPoint(x: 20.16, y: 44.17))
bezier3Path.addCurve(to: CGPoint(x: 37, y: 19.55), controlPoint1: CGPoint(x: 20.96, y: 43.43), controlPoint2: CGPoint(x: 37, y: 29.24))
bezier3Path.addCurve(to: CGPoint(x: 19.5, y: 2), controlPoint1: CGPoint(x: 37, y: 9.86), controlPoint2: CGPoint(x: 29.16, y: 2))
bezier3Path.addCurve(to: CGPoint(x: 2, y: 19.55), controlPoint1: CGPoint(x: 9.84, y: 2), controlPoint2: CGPoint(x: 2, y: 9.86))
bezier3Path.addCurve(to: CGPoint(x: 18.04, y: 43.43), controlPoint1: CGPoint(x: 2, y: 29.24), controlPoint2: CGPoint(x: 18.04, y: 43.43))
bezier3Path.close()
strokeColor.setStroke()
bezier3Path.lineWidth = 3
bezier3Path.stroke()
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 12.5, y: 12.16, width: 14, height: 14))
innerColor.setFill()
ovalPath.fill()
}
}
| 53.421053 | 445 | 0.626273 |
9b446f24ccbc6053354f0f3b9b30e1c3caf40136 | 2,711 | /// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
extension UIColor {
class func RGB(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return RGBA(red: red, green: green, blue: blue, alpha: 255.0)
}
class func RGBA(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha / 255.0)
}
class func RGBAColorFromString(string: String?) -> UIColor? {
guard let string = string else {
return nil
}
var components = string.split(separator: ",").map(String.init)
if components.count == 3 {
components.append("255.0")
}
guard components.count == 4 else {
return nil
}
let red = CGFloat((Float(components[0]) ?? 0) / 255.0)
let green = CGFloat((Float(components[1]) ?? 0) / 255.0)
let blue = CGFloat((Float(components[2]) ?? 0) / 255.0)
let alpha = CGFloat((Float(components[3]) ?? 0) / 255.0)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
| 42.359375 | 100 | 0.699373 |
761ada0997e1e74893aa207045a8192f6b0be424 | 766 | import UIKit
import XCTest
import NMCollectionView
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.533333 | 111 | 0.608355 |
463df3ad6563fd7c2bdb5690b23ab8a6b81e6d37 | 517 | //
// ViewController.swift
// PayloadCardReader
//
// Created by Ian Halpern on 06/03/2021.
// Copyright (c) 2021 Ian Halpern. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.68 | 80 | 0.675048 |
1c3ca9da364b8bd214a584525e29e1c306ae4a26 | 4,433 | //
// NSLayoutConstraintExtension.swift
// ClingConstraintsDemo
//
// Created by Christopher Perkins on 6/24/18.
// Copyright © 2018 Christopher Perkins. All rights reserved.
//
import UIKit
public extension NSLayoutConstraint {
/// Creates a new constraint with the given multiplier and the original constraint's other properties, deactivates
/// and removes the old constraint, activates the created constraint if the original constraint was active, and
/// returns the created constraint.
///
/// - Parameter newMultiplier: The multiplier that should be set for the new constraint
/// - Returns: The new activated constraint with the provided `newMultiplier` value
@discardableResult func withMultiplier(_ newMultiplier: CGFloat) -> NSLayoutConstraint {
let newConstraint = NSLayoutConstraint(item: firstItem!,
attribute: firstAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondAttribute,
multiplier: newMultiplier,
constant: constant)
let originallyActive = isActive
isActive = false
firstItem?.removeConstraint(self)
newConstraint.isActive = originallyActive
return newConstraint
}
/// Sets the offset of this constraint and returns it again.
///
/// - Parameter offset: The offset that the constraint should have
/// - Returns: This constraint with the offset of the provided offset value
@discardableResult func withOffset(_ offset: CGFloat) -> NSLayoutConstraint {
let originallyActive = isActive
isActive = false
constant = offset
isActive = originallyActive
return self
}
/// Creates a new constraint with the given priority and the original constraint's other properties, deactivates and
/// removes the old constraint, activates the created constraint if the original constraint was active, and returns
/// the created constraint.
///
/// - Parameter priority: The priority that should be set for the new constraint
/// - Returns: The new constraint with the provided `priority` value
@discardableResult func withPriority( _ priority: UILayoutPriority) -> NSLayoutConstraint {
let newConstraint = NSLayoutConstraint(item: firstItem!,
attribute: firstAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondAttribute,
multiplier: multiplier,
constant: constant)
newConstraint.priority = priority
let originallyActive = isActive
isActive = false
firstItem?.removeConstraint(self)
newConstraint.isActive = originallyActive
return self
}
/// Creates a new constraint with the given relation and the original constraint's other properties, deactivates and
/// removes the old constraint, activates the created constraint if the original constraint was active, and returns
/// the created constraint.
///
/// - Parameter newRelation: The relation that should be set for the new constraint
/// - Returns: The new constraint with the provided `newRelation` value
@discardableResult func withRelation(_ newRelation: NSLayoutConstraint.Relation) -> NSLayoutConstraint {
let newConstraint = NSLayoutConstraint(item: firstItem!,
attribute: firstAttribute,
relatedBy: newRelation,
toItem: secondItem,
attribute: secondAttribute,
multiplier: multiplier,
constant: constant)
let originallyActive = isActive
isActive = false
firstItem?.removeConstraint(self)
newConstraint.isActive = originallyActive
return newConstraint
}
}
| 47.666667 | 120 | 0.588315 |
d6284cf57e9c4e0e652a425254d72bcbf2891dfd | 1,960 | //
// NetworkManager.swift
// Employees
//
// Created by Anton Stremovskiy on 07.05.2020.
// Copyright © 2020 Anton Stremovskiy. All rights reserved.
//
import Foundation
import UIKit
enum NetworkResponse: String {
case success
case authError = "Login or password are incorrect"
case badRequest = "Bad Request"
case failed = "Request failed"
case noData = "Response returned with no data to decode"
case unableToDecode = "We could not decode the response"
case serverError = "Internal server error"
case nothingFound = "The server can not find the requested resource"
case forbidden = "The client does not have access rights to the content"
case methodNotAllowed = "Metthod not allowed"
case conflict = "The request could not be processed because of conflict in the request"
}
enum Result<String> {
case success
case failure(String)
}
class NetworkManager {
public func handleNetworkResponse(_ response: HTTPURLResponse) -> Result<String> {
switch response.statusCode {
case 200...299: return .success
case 400: return .failure(NetworkResponse.badRequest.rawValue)
case 401: return .failure(NetworkResponse.authError.rawValue)
case 403: return .failure(NetworkResponse.forbidden.rawValue)
case 404: return .failure(NetworkResponse.nothingFound.rawValue)
case 405: return .failure(NetworkResponse.methodNotAllowed.rawValue)
case 409: return .failure(NetworkResponse.conflict.rawValue)
case 406...499: return .failure(NetworkResponse.authError.rawValue)
case 411: return .failure(NetworkResponse.authError.rawValue)
case 500: return .failure(NetworkResponse.serverError.rawValue)
case 501...599: return .failure(NetworkResponse.badRequest.rawValue)
default: return .failure(NetworkResponse.badRequest.rawValue)
}
}
}
| 35.636364 | 91 | 0.69898 |
efb1cabbd2ad3cc92c110aed7c4f8baa56d06d9b | 1,073 | //
// USDAFoodCompositionDatabasesAPITests.swift
// USDAFoodCompositionDatabasesAPITests
//
// Created by Jacob Christie on 2017-12-30.
// Copyright © 2017 Jacob Christie. All rights reserved.
//
import XCTest
@testable import USDAFoodCompositionDatabasesAPI
class USDAFoodCompositionDatabasesAPITests: 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.
}
}
}
| 29 | 111 | 0.667288 |
38cbccaefcac8943135818c21b0e76de1f57bd3c | 610 | //
// HideEmptyAlbumsController.swift
// AssetsPickerViewController
//
// Created by DragonCherry on 5/31/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import MediaPickerViewController
class HideEmptyAlbumsController: CommonExampleController {
override func pressedPick(_ sender: Any) {
let pickerConfig = AssetsPickerConfig()
pickerConfig.albumIsShowEmptyAlbum = false
let picker = AssetsPickerViewController(pickerConfig: pickerConfig)
picker.pickerDelegate = self
present(picker, animated: true, completion: nil)
}
}
| 26.521739 | 75 | 0.708197 |
1cfa1882e4bcf35f3706d42ce33506a1afdebaaf | 4,980 | //
// PullToRefreshView.swift
// Yep
//
// Created by NIX on 15/4/14.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
protocol PullToRefreshViewDelegate: class {
func pulllToRefreshViewDidRefresh(pulllToRefreshView: PullToRefreshView)
func scrollView() -> UIScrollView
}
private let sceneHeight: CGFloat = 80
final class PullToRefreshView: UIView {
var refreshView: YepRefreshView!
var progressPercentage: CGFloat = 0
weak var delegate: PullToRefreshViewDelegate?
var refreshItems = [RefreshItem]()
var isRefreshing = false {
didSet {
if !isRefreshing {
refreshTimeoutTimer?.invalidate()
}
}
}
var refreshTimeoutTimer: NSTimer?
var refreshTimeoutAction: (() -> Void)? {
didSet {
refreshTimeoutTimer?.invalidate()
refreshTimeoutTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(PullToRefreshView.refreshTimeout(_:)), userInfo: nil, repeats: false)
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.clipsToBounds = true
setupRefreshItems()
updateColors()
}
func setupRefreshItems() {
refreshView = YepRefreshView(frame: CGRectMake(0, 0, 50, 50))
refreshItems = [
RefreshItem(
view: refreshView,
centerEnd: CGPoint(
x: CGRectGetMidX(UIScreen.mainScreen().bounds),
y: 200 - sceneHeight * 0.5
),
parallaxRatio: 0,
sceneHeight: sceneHeight
),
]
for refreshItem in refreshItems {
addSubview(refreshItem.view)
}
}
func updateColors() {
refreshView.updateShapePositionWithProgressPercentage(progressPercentage)
}
func updateRefreshItemPositions() {
for refreshItem in refreshItems {
refreshItem.updateViewPositionForPercentage(progressPercentage)
}
}
// MARK: Actions
func beginRefreshing() {
isRefreshing = true
UIView.animateWithDuration(0.25, delay: 0, options: .CurveEaseInOut, animations: { [weak self] in
self?.delegate?.scrollView().contentInset.top += sceneHeight
}, completion: { (_) -> Void in
})
}
func endRefreshingAndDoFurtherAction(furtherAction: () -> Void) {
guard isRefreshing else {
return
}
isRefreshing = false
UIView.animateWithDuration(0.25, delay: 0, options: .CurveEaseInOut, animations: { [weak self] in
self?.delegate?.scrollView().contentInset.top -= sceneHeight
}, completion: { (_) -> Void in
furtherAction()
self.refreshView.stopFlashing()
self.refreshView.updateRamdonShapePositions()
})
}
func refreshTimeout(timer: NSTimer) {
println("PullToRefreshView refreshTimeout")
refreshTimeoutAction?()
}
}
extension PullToRefreshView: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
if isRefreshing {
return
}
let refreshViewVisibleHeight = max(0, -(scrollView.contentOffset.y + scrollView.contentInset.top))
progressPercentage = min(1, refreshViewVisibleHeight / sceneHeight)
updateRefreshItemPositions()
updateColors()
}
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if !isRefreshing && progressPercentage == 1 {
beginRefreshing()
targetContentOffset.memory.y = -scrollView.contentInset.top
delegate?.pulllToRefreshViewDidRefresh(self)
}
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
if !isRefreshing && progressPercentage == 1 {
beginRefreshing()
scrollView.contentOffset.y = -scrollView.contentInset.top
delegate?.pulllToRefreshViewDidRefresh(self)
}
}
}
final class RefreshItem {
unowned var view: UIView
private var centerStart: CGPoint
private var centerEnd: CGPoint
init(view: UIView, centerEnd: CGPoint, parallaxRatio: CGFloat, sceneHeight: CGFloat) {
self.view = view
self.centerEnd = centerEnd
centerStart = CGPoint(x: centerEnd.x, y: centerEnd.y + (parallaxRatio * sceneHeight))
self.view.center = centerStart
}
func updateViewPositionForPercentage(percentage: CGFloat) {
view.center = CGPoint(
x: centerStart.x + (centerEnd.x - centerStart.x) * percentage,
y: centerStart.y + (centerEnd.y - centerStart.y) * percentage
)
}
func updateViewTintColor(tintColor: UIColor) {
view.tintColor = tintColor
}
} | 26.210526 | 181 | 0.627711 |
18a4db00a9e1e2e3cf67d2a7b19915dff40cf9b2 | 17,096 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// Source file description.proto
import Foundation
public struct Services { public struct Common { public struct Containers { public struct Description { }}}}
public func == (lhs: Services.Common.Containers.Description.DescriptionV1, rhs: Services.Common.Containers.Description.DescriptionV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value)
fieldCheck = fieldCheck && (lhs.hasByProfileId == rhs.hasByProfileId) && (!lhs.hasByProfileId || lhs.byProfileId == rhs.byProfileId)
fieldCheck = fieldCheck && (lhs.hasChanged == rhs.hasChanged) && (!lhs.hasChanged || lhs.changed == rhs.changed)
fieldCheck = fieldCheck && (lhs.hasByProfile == rhs.hasByProfile) && (!lhs.hasByProfile || lhs.byProfile == rhs.byProfile)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public extension Services.Common.Containers.Description {
public struct DescriptionRoot {
public static var sharedInstance : DescriptionRoot {
struct Static {
static let instance : DescriptionRoot = DescriptionRoot()
}
return Static.instance
}
public var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
Services.Profile.Containers.ContainersRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
public func registerAllExtensions(registry:ExtensionRegistry) {
}
}
final public class DescriptionV1 : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasValue:Bool = false
public private(set) var value:String = ""
public private(set) var hasByProfileId:Bool = false
public private(set) var byProfileId:String = ""
public private(set) var hasChanged:Bool = false
public private(set) var changed:String = ""
public private(set) var hasByProfile:Bool = false
public private(set) var byProfile:Services.Profile.Containers.ProfileV1!
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasValue {
try output.writeString(1, value:value)
}
if hasByProfileId {
try output.writeString(2, value:byProfileId)
}
if hasChanged {
try output.writeString(3, value:changed)
}
if hasByProfile {
try output.writeMessage(4, value:byProfile)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasValue {
serialize_size += value.computeStringSize(1)
}
if hasByProfileId {
serialize_size += byProfileId.computeStringSize(2)
}
if hasChanged {
serialize_size += changed.computeStringSize(3)
}
if hasByProfile {
if let varSizebyProfile = byProfile?.computeMessageSize(4) {
serialize_size += varSizebyProfile
}
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Common.Containers.Description.DescriptionV1> {
var mergedArray = Array<Services.Common.Containers.Description.DescriptionV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Common.Containers.Description.DescriptionV1? {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.Common.Containers.Description.DescriptionV1 {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFromData(data, extensionRegistry:Services.Common.Containers.Description.DescriptionRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Common.Containers.Description.DescriptionV1 {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.Common.Containers.Description.DescriptionV1 {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Common.Containers.Description.DescriptionV1 {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Common.Containers.Description.DescriptionV1 {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Common.Containers.Description.DescriptionV1 {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.Common.Containers.Description.DescriptionV1.Builder {
return Services.Common.Containers.Description.DescriptionV1.classBuilder() as! Services.Common.Containers.Description.DescriptionV1.Builder
}
public func getBuilder() -> Services.Common.Containers.Description.DescriptionV1.Builder {
return classBuilder() as! Services.Common.Containers.Description.DescriptionV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.Common.Containers.Description.DescriptionV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.Common.Containers.Description.DescriptionV1.Builder()
}
public func toBuilder() throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
return try Services.Common.Containers.Description.DescriptionV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.Common.Containers.Description.DescriptionV1) throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
return try Services.Common.Containers.Description.DescriptionV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
if hasValue {
output += "\(indent) value: \(value) \n"
}
if hasByProfileId {
output += "\(indent) byProfileId: \(byProfileId) \n"
}
if hasChanged {
output += "\(indent) changed: \(changed) \n"
}
if hasByProfile {
output += "\(indent) byProfile {\n"
try byProfile?.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent) }\n"
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasValue {
hashCode = (hashCode &* 31) &+ value.hashValue
}
if hasByProfileId {
hashCode = (hashCode &* 31) &+ byProfileId.hashValue
}
if hasChanged {
hashCode = (hashCode &* 31) &+ changed.hashValue
}
if hasByProfile {
if let hashValuebyProfile = byProfile?.hashValue {
hashCode = (hashCode &* 31) &+ hashValuebyProfile
}
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.Common.Containers.Description.DescriptionV1"
}
override public func className() -> String {
return "Services.Common.Containers.Description.DescriptionV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.Common.Containers.Description.DescriptionV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.Common.Containers.Description.DescriptionV1 = Services.Common.Containers.Description.DescriptionV1()
public func getMessage() -> Services.Common.Containers.Description.DescriptionV1 {
return builderResult
}
required override public init () {
super.init()
}
public var hasValue:Bool {
get {
return builderResult.hasValue
}
}
public var value:String {
get {
return builderResult.value
}
set (value) {
builderResult.hasValue = true
builderResult.value = value
}
}
public func setValue(value:String) -> Services.Common.Containers.Description.DescriptionV1.Builder {
self.value = value
return self
}
public func clearValue() -> Services.Common.Containers.Description.DescriptionV1.Builder{
builderResult.hasValue = false
builderResult.value = ""
return self
}
public var hasByProfileId:Bool {
get {
return builderResult.hasByProfileId
}
}
public var byProfileId:String {
get {
return builderResult.byProfileId
}
set (value) {
builderResult.hasByProfileId = true
builderResult.byProfileId = value
}
}
public func setByProfileId(value:String) -> Services.Common.Containers.Description.DescriptionV1.Builder {
self.byProfileId = value
return self
}
public func clearByProfileId() -> Services.Common.Containers.Description.DescriptionV1.Builder{
builderResult.hasByProfileId = false
builderResult.byProfileId = ""
return self
}
public var hasChanged:Bool {
get {
return builderResult.hasChanged
}
}
public var changed:String {
get {
return builderResult.changed
}
set (value) {
builderResult.hasChanged = true
builderResult.changed = value
}
}
public func setChanged(value:String) -> Services.Common.Containers.Description.DescriptionV1.Builder {
self.changed = value
return self
}
public func clearChanged() -> Services.Common.Containers.Description.DescriptionV1.Builder{
builderResult.hasChanged = false
builderResult.changed = ""
return self
}
public var hasByProfile:Bool {
get {
return builderResult.hasByProfile
}
}
public var byProfile:Services.Profile.Containers.ProfileV1! {
get {
if byProfileBuilder_ != nil {
builderResult.byProfile = byProfileBuilder_.getMessage()
}
return builderResult.byProfile
}
set (value) {
builderResult.hasByProfile = true
builderResult.byProfile = value
}
}
private var byProfileBuilder_:Services.Profile.Containers.ProfileV1.Builder! {
didSet {
builderResult.hasByProfile = true
}
}
public func getByProfileBuilder() -> Services.Profile.Containers.ProfileV1.Builder {
if byProfileBuilder_ == nil {
byProfileBuilder_ = Services.Profile.Containers.ProfileV1.Builder()
builderResult.byProfile = byProfileBuilder_.getMessage()
if byProfile != nil {
try! byProfileBuilder_.mergeFrom(byProfile)
}
}
return byProfileBuilder_
}
public func setByProfile(value:Services.Profile.Containers.ProfileV1!) -> Services.Common.Containers.Description.DescriptionV1.Builder {
self.byProfile = value
return self
}
public func mergeByProfile(value:Services.Profile.Containers.ProfileV1) throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
if builderResult.hasByProfile {
builderResult.byProfile = try Services.Profile.Containers.ProfileV1.builderWithPrototype(builderResult.byProfile).mergeFrom(value).buildPartial()
} else {
builderResult.byProfile = value
}
builderResult.hasByProfile = true
return self
}
public func clearByProfile() -> Services.Common.Containers.Description.DescriptionV1.Builder {
byProfileBuilder_ = nil
builderResult.hasByProfile = false
builderResult.byProfile = nil
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.Common.Containers.Description.DescriptionV1.Builder {
builderResult = Services.Common.Containers.Description.DescriptionV1()
return self
}
public override func clone() throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
return try Services.Common.Containers.Description.DescriptionV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.Common.Containers.Description.DescriptionV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.Common.Containers.Description.DescriptionV1 {
let returnMe:Services.Common.Containers.Description.DescriptionV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.Common.Containers.Description.DescriptionV1) throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
if other == Services.Common.Containers.Description.DescriptionV1() {
return self
}
if other.hasValue {
value = other.value
}
if other.hasByProfileId {
byProfileId = other.byProfileId
}
if other.hasChanged {
changed = other.changed
}
if (other.hasByProfile) {
try mergeByProfile(other.byProfile)
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Common.Containers.Description.DescriptionV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10 :
value = try input.readString()
case 18 :
byProfileId = try input.readString()
case 26 :
changed = try input.readString()
case 34 :
let subBuilder:Services.Profile.Containers.ProfileV1.Builder = Services.Profile.Containers.ProfileV1.Builder()
if hasByProfile {
try subBuilder.mergeFrom(byProfile)
}
try input.readMessage(subBuilder, extensionRegistry:extensionRegistry)
byProfile = subBuilder.buildPartial()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
}
// @@protoc_insertion_point(global_scope)
| 41.799511 | 214 | 0.670098 |
fe2a54ea5c9fd81812e30dc4514570665d14231b | 135 | import UIKit
extension UIScreen {
static func fy_1px() -> CGFloat {
return 1 / self.main.scale
}
}
| 12.272727 | 37 | 0.525926 |
6942af06c4a7f09d95ecae16d5a953689ddbe178 | 757 | import XCTest
import TransitionController
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 26.103448 | 111 | 0.606341 |
38d5695b9761910c9b0940f1ccc00ba43bee3b75 | 6,215 | // The MIT License (MIT)
//
// Copyright (c) 2015-2019 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
#if !os(macOS)
import UIKit
#endif
class ImageProcessingTests: XCTestCase {
var mockDataLoader: MockDataLoader!
var pipeline: ImagePipeline!
override func setUp() {
super.setUp()
mockDataLoader = MockDataLoader()
pipeline = ImagePipeline {
$0.dataLoader = mockDataLoader
return
}
}
override func tearDown() {
super.tearDown()
}
// MARK: - Applying Filters
func testThatImageIsProcessed() {
// Given
let request = Test.request.processed(with: MockImageProcessor(id: "processor1"))
// When
expect(pipeline).toLoadImage(with: request) { response, _ in
// Then
XCTAssertEqual(response?.image.nk_test_processorIDs ?? [], ["processor1"])
}
wait()
}
func testReplacingDefaultProcessor() {
// Given
var request = Test.request
request.processor = nil
request.process(with: MockImageProcessor(id: "processor1"))
// When
// When
expect(pipeline).toLoadImage(with: request) { response, _ in
// Then
XCTAssertEqual(response?.image.nk_test_processorIDs ?? [], ["processor1"])
}
wait()
}
// MARK: - Composing Filters
func testApplyingMultipleProcessors() {
// Given
let request = Test.request
.processed(with: MockImageProcessor(id: "processor1"))
.processed(with: MockImageProcessor(id: "processor2"))
// When
expect(pipeline).toLoadImage(with: request) { response, _ in
// Then
XCTAssertEqual(response?.image.nk_test_processorIDs ?? [], ["processor1", "processor2"])
}
wait()
}
func testPerformingRequestWithoutProcessors() {
// Given
var request = Test.request
request.processor = nil
// When
expect(pipeline).toLoadImage(with: request) { response, _ in
// Then
XCTAssertEqual(response?.image.nk_test_processorIDs ?? [], [])
}
wait()
}
// MARK: - Anonymous Processor
func testAnonymousProcessorsEquatable() {
XCTAssertEqual(
Test.request.processed(key: 1, { $0 }).processor,
Test.request.processed(key: 1, { $0 }).processor
)
XCTAssertNotEqual(
Test.request.processed(key: 1, { $0 }).processor,
Test.request.processed(key: 2, { $0 }).processor
)
}
func testAnonymousProcessorIsApplied() {
// Given
let request = Test.request.processed(key: 1) {
$0.nk_test_processorIDs = ["1"]
return $0
}
let context = ImageProcessingContext(request: request, isFinal: true, scanNumber: nil)
// When
let image = request.processor?.process(image: Image(), context: context)
// Then
XCTAssertEqual(image?.nk_test_processorIDs ?? [], ["1"])
}
func testAnonymousProcessorIsApplied2() {
// Given
var request = Test.request
request.process(key: 1) {
$0.nk_test_processorIDs = ["1"]
return $0
}
let context = ImageProcessingContext(request: request, isFinal: true, scanNumber: nil)
// When
let image = request.processor?.process(image: Image(), context: context)
// Then
XCTAssertEqual(image?.nk_test_processorIDs ?? [], ["1"])
}
// MARK: - Resizing
#if !os(macOS)
func testUsingProcessorRequestParameter() {
// Given
let processor = ImageDecompressor(targetSize: CGSize(width: 40, height: 40), contentMode: .aspectFit, upscale: false)
// When
let request = ImageRequest(url: Test.url, processor: processor)
// Then
XCTAssertEqual(AnyImageProcessor(processor), request.processor)
}
func testResizingUsingRequestParameters() {
// Given
let request = ImageRequest(url: Test.url, targetSize: CGSize(width: 40, height: 40), contentMode: .aspectFit)
let context = ImageProcessingContext(request: request, isFinal: true, scanNumber: nil)
// When
let image = request.processor!.process(image: Test.image, context: context)
// Then
XCTAssertEqual(image?.cgImage?.width, 40)
XCTAssertEqual(image?.cgImage?.height, 30)
}
func testResizingUsingRequestParametersInitWithURLRequest() {
// Given
let request = ImageRequest(urlRequest: Test.request.urlRequest, targetSize: CGSize(width: 40, height: 40), contentMode: .aspectFit)
let context = ImageProcessingContext(request: request, isFinal: true, scanNumber: nil)
// When
let image = request.processor!.process(image: Test.image, context: context)
// Then
XCTAssertEqual(image?.cgImage?.width, 40)
XCTAssertEqual(image?.cgImage?.height, 30)
}
func testResizingShouldNotUpscaleWithoutParamater() {
// Given
let targetSize = CGSize(width: 960, height: 720)
let request = ImageRequest(url: Test.url, targetSize: targetSize, contentMode: .aspectFit)
let context = ImageProcessingContext(request: request, isFinal: true, scanNumber: nil)
// When
let image = request.processor!.process(image: Test.image, context: context)
// Then
XCTAssertEqual(image?.cgImage?.width, 640)
XCTAssertEqual(image?.cgImage?.height, 480)
}
func testResizingShouldUpscaleWithParamater() {
// Given
let targetSize = CGSize(width: 960, height: 720)
let request = ImageRequest(url: Test.url, targetSize: targetSize, contentMode: .aspectFit, upscale: true)
let context = ImageProcessingContext(request: request, isFinal: true, scanNumber: nil)
// When
let image = request.processor!.process(image: Test.image, context: context)
// Then
XCTAssertEqual(image?.cgImage?.width, 960)
XCTAssertEqual(image?.cgImage?.height, 720)
}
#endif
}
| 30.920398 | 139 | 0.612872 |
cc90246dada18cf3dc7a9a3632211898c9c93c45 | 895 | //
// AlertHandler Extension.swift
//
// Created by Michael Stebel on 11/9/15.
// Copyright © 2016-2022 Michael Stebel Consulting, LLC. All rights reserved..
//
import UIKit
extension UIViewController: AlertHandler {
/// Convenience method to display a simple alert
func alert(for title: String, message messageToDisplay: String) {
let alertController = UIAlertController(title: title, message: messageToDisplay, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
/// Display alert if unable to connect to a server
func cannotConnectToInternetAlert() {
alert(for: "Can't connect to the server.", message: "Check your Internet connection\nand try again.")
}
}
| 29.833333 | 112 | 0.669274 |
11e0eed33d510b3c920812ff9f9de1ebf196eb8b | 4,575 | //
// QueueConversationSocialExpressionEventTopicEmail.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class QueueConversationSocialExpressionEventTopicEmail: Codable {
public enum State: String, Codable {
case alerting = "ALERTING"
case connected = "CONNECTED"
case disconnected = "DISCONNECTED"
case _none = "NONE"
case transmitting = "TRANSMITTING"
}
public enum DisconnectType: String, Codable {
case endpoint = "ENDPOINT"
case client = "CLIENT"
case system = "SYSTEM"
case timeout = "TIMEOUT"
case transfer = "TRANSFER"
case transferConference = "TRANSFER_CONFERENCE"
case transferConsult = "TRANSFER_CONSULT"
case transferForward = "TRANSFER_FORWARD"
case transferNoanswer = "TRANSFER_NOANSWER"
case transferNotavailable = "TRANSFER_NOTAVAILABLE"
case transportFailure = "TRANSPORT_FAILURE"
case error = "ERROR"
case peer = "PEER"
case other = "OTHER"
case spam = "SPAM"
case uncallable = "UNCALLABLE"
}
public enum Direction: String, Codable {
case outbound = "OUTBOUND"
case inbound = "INBOUND"
}
public var _id: String?
public var state: State?
public var held: Bool?
public var autoGenerated: Bool?
public var subject: String?
public var provider: String?
public var scriptId: String?
public var peerId: String?
public var messagesSent: Int?
public var errorInfo: QueueConversationSocialExpressionEventTopicErrorDetails?
public var disconnectType: DisconnectType?
public var startHoldTime: Date?
public var connectedTime: Date?
public var disconnectedTime: Date?
public var messageId: String?
public var direction: Direction?
public var draftAttachments: [QueueConversationSocialExpressionEventTopicAttachment]?
public var spam: Bool?
public var wrapup: QueueConversationSocialExpressionEventTopicWrapup?
public var afterCallWork: QueueConversationSocialExpressionEventTopicAfterCallWork?
public var afterCallWorkRequired: Bool?
public var additionalProperties: JSON?
public init(_id: String?, state: State?, held: Bool?, autoGenerated: Bool?, subject: String?, provider: String?, scriptId: String?, peerId: String?, messagesSent: Int?, errorInfo: QueueConversationSocialExpressionEventTopicErrorDetails?, disconnectType: DisconnectType?, startHoldTime: Date?, connectedTime: Date?, disconnectedTime: Date?, messageId: String?, direction: Direction?, draftAttachments: [QueueConversationSocialExpressionEventTopicAttachment]?, spam: Bool?, wrapup: QueueConversationSocialExpressionEventTopicWrapup?, afterCallWork: QueueConversationSocialExpressionEventTopicAfterCallWork?, afterCallWorkRequired: Bool?, additionalProperties: JSON?) {
self._id = _id
self.state = state
self.held = held
self.autoGenerated = autoGenerated
self.subject = subject
self.provider = provider
self.scriptId = scriptId
self.peerId = peerId
self.messagesSent = messagesSent
self.errorInfo = errorInfo
self.disconnectType = disconnectType
self.startHoldTime = startHoldTime
self.connectedTime = connectedTime
self.disconnectedTime = disconnectedTime
self.messageId = messageId
self.direction = direction
self.draftAttachments = draftAttachments
self.spam = spam
self.wrapup = wrapup
self.afterCallWork = afterCallWork
self.afterCallWorkRequired = afterCallWorkRequired
self.additionalProperties = additionalProperties
}
public enum CodingKeys: String, CodingKey {
case _id = "id"
case state
case held
case autoGenerated
case subject
case provider
case scriptId
case peerId
case messagesSent
case errorInfo
case disconnectType
case startHoldTime
case connectedTime
case disconnectedTime
case messageId
case direction
case draftAttachments
case spam
case wrapup
case afterCallWork
case afterCallWorkRequired
case additionalProperties
}
}
| 32.21831 | 670 | 0.662295 |
648de72fe76f4d49026e6ee93d7ecb9c306a3821 | 2,425 | //
// Shadow.swift
// Shadow
//
// Created by Cem Olcay on 05/06/16.
// Copyright © 2016 Prototapp. All rights reserved.
//
import UIKit
/// Defines a shadow object for `CALayer` shadows.
/// Uses UIKit objects instead of CoreGraphics ones that CALayer uses.
public struct Shadow {
/// Color of the shadow. Default is `UIColor.grayColor()`.
public var color: UIColor
/// Radius of the shadow. Default is 1.
public var radius: CGFloat
/// Opacity of the shadow. Default is 0.5
public var opacity: Float
/// Offset of the shadow. Default is `CGSize(width: 0, height: 1)`
public var offset: CGSize
/// Optional bezier path of shadow.
public var path: UIBezierPath?
/// Initilizes `Shadow` with default values or optional given values.
public init(
color: UIColor? = nil,
radius: CGFloat? = nil,
opacity: Float? = nil,
offset: CGSize? = nil,
path: UIBezierPath? = nil) {
self.color = color ?? UIColor.gray
self.radius = radius ?? 5
self.opacity = opacity ?? 1
self.offset = offset ?? CGSize(width: 0, height: 1)
self.path = path
}
}
/// Public extension of CALayer for applying or removing `Shadow`.
public extension CALayer {
/// Applys shadow if given object is not nil.
/// Removes shadow if given object is nil.
public func applyShadow(shadow: Shadow? = nil) {
shadowColor = shadow?.color.cgColor ?? UIColor.clear.cgColor
shadowOpacity = shadow?.opacity ?? 0
if let shadow = shadow {
if let path = shadow.path {
shadowRadius = shadow.radius
shadowOffset = shadow.offset
shadowPath = path.cgPath
} else {
var shadowRect = bounds
shadowRect.origin = CGPoint(
x: bounds.origin.x + shadow.offset.width,
y: bounds.origin.y + shadow.offset.height)
let path = UIBezierPath(
roundedRect: shadowRect,
cornerRadius: shadow.radius)
shadowPath = path.cgPath
shadowRadius = 0
shadowOffset = CGSize.zero
}
} else {
shadowRadius = 0
shadowOffset = CGSize.zero
shadowPath = nil
}
}
}
/// Public extension of UIView for applying or removing `Shadow`
public extension UIView {
/// Applys shadow on its layer if given object is not nil.
/// Removes shadow on its layer if given object is nil.
public func applyShadow(shadow: Shadow? = nil) {
layer.applyShadow(shadow: shadow)
}
}
| 30.3125 | 71 | 0.653196 |
4682810c4fc5d1f2c54caae6215c9ca6cdaad189 | 3,312 | //
// ItemsViewController.swift
// ConditioningAssistant
//
// Created by Q on 15/6/13.
// Copyright (c) 2015年 zwq. All rights reserved.
//
import UIKit
class ItemsViewController: UITableViewController {
var isFold = [true, true]
let sectionTitleArr = ["Section 1", "Section 2"]
let sectionListArr = [["New Zealand","Australia","Bangladesh","Sri Lanka"], ["India","South Africa","UAE","Pakistan"]]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "All Items"
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
println("numberOfSections")
return sectionTitleArr.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("numberOfRows In section")
if (isFold[section] == false) {
return sectionListArr[section].count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
if !isFold[indexPath.section] {
cell.textLabel?.text = sectionListArr[indexPath.section][indexPath.row]
cell.backgroundColor = UIColor.greenColor()
}
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitleArr[section]
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRectMake(0.0, 0.0, tableView.frame.size.width, 50.0))
headerView.backgroundColor = UIColor.blueColor()
let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width-10, height: 30)) as UILabel
headerString.text = sectionTitleArr[section]
headerView .addSubview(headerString)
return headerView
}
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tag = section
println(view.tag)
let headerTapped = UITapGestureRecognizer(target: self, action: "sectionHeaderTapped:")
view.addGestureRecognizer(headerTapped)
}
func sectionHeaderTapped(recognizer: UITapGestureRecognizer) {
println("Tapping working")
println(recognizer.view?.tag)
let tappedSection = recognizer.view?.tag as Int!
isFold[tappedSection] = !isFold[tappedSection]
var sectionToReload = NSIndexSet(index: tappedSection)
self.tableView.reloadSections(sectionToReload, withRowAnimation: UITableViewRowAnimation.Fade)
}
}
| 34.863158 | 126 | 0.676027 |
1e411da13cfdeceec0f756bb650e1c7fda5d6d27 | 10,521 | // Copyright 2019 Algorand, 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.
//
// AppDelegate.swift
import UIKit
import CoreData
import Firebase
import SwiftDate
import UserNotifications
import FirebaseCrashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private lazy var session = Session()
private lazy var api = AlgorandAPI(session: session, base: "")
private lazy var appConfiguration = AppConfiguration(api: api, session: session)
private lazy var pushNotificationController = PushNotificationController(api: api)
private(set) lazy var firebaseAnalytics = FirebaseAnalytics()
private var rootViewController: RootViewController?
private(set) lazy var accountManager: AccountManager = AccountManager(api: api)
private var timer: PollingOperation?
private var shouldInvalidateAccountFetch = false
private var shouldInvalidateUserSession: Bool = false
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
setupFirebase()
SwiftDate.setupDateRegion()
setupWindow()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
authorizeNotifications(for: deviceToken)
}
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
displayInAppPushNotification(from: userInfo)
}
func applicationWillEnterForeground(_ application: UIApplication) {
updateForegroundActions()
}
func applicationDidEnterBackground(_ application: UIApplication) {
decideToInvalidateSessionInBackground()
}
func applicationWillTerminate(_ application: UIApplication) {
saveContext()
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
return shouldHandleDeepLinkRouting(from: url)
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "algorand")
container.loadPersistentStores { storeDescription, error in
if var url = storeDescription.url {
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
do {
try url.setResourceValues(resourceValues)
} catch {
}
}
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
}
extension AppDelegate {
private func setupFirebase() {
firebaseAnalytics.initialize()
}
private func setupWindow() {
let window = UIWindow(frame: UIScreen.main.bounds)
rootViewController = RootViewController(appConfiguration: appConfiguration)
guard let rootViewController = rootViewController else {
return
}
window.backgroundColor = .clear
window.rootViewController = rootViewController
window.makeKeyAndVisible()
self.window = window
}
}
extension AppDelegate {
private func updateForegroundActions() {
timer?.invalidate()
updateUserInterfaceStyleIfNeeded()
NotificationCenter.default.post(name: .ApplicationWillEnterForeground, object: self, userInfo: nil)
validateUserSessionIfNeeded()
}
private func validateUserSessionIfNeeded() {
guard appConfiguration.session.isValid,
!appConfiguration.session.accounts.isEmpty else {
return
}
if shouldInvalidateUserSession {
shouldInvalidateUserSession = false
if appConfiguration.session.hasPassword() {
appConfiguration.session.isValid = false
openPasswordEntryScreen()
}
return
} else {
validateAccountManagerFetchPolling()
}
}
private func openPasswordEntryScreen() {
guard let rootViewController = rootViewController,
let topViewController = rootViewController.tabBarViewController.topMostController,
appConfiguration.session.hasPassword() else {
return
}
rootViewController.route(
to: .choosePassword(mode: .login, flow: nil, route: nil),
from: topViewController,
by: .customPresent(presentationStyle: .fullScreen, transitionStyle: nil, transitioningDelegate: nil)
)
}
private func decideToInvalidateSessionInBackground() {
timer = PollingOperation(interval: Constants.sessionInvalidateTime) { [weak self] in
self?.shouldInvalidateUserSession = true
}
timer?.start()
invalidateAccountManagerFetchPolling()
}
}
extension AppDelegate {
private func authorizeNotifications(for deviceToken: Data) {
let pushToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
pushNotificationController.authorizeDevice(with: pushToken)
}
private func displayInAppPushNotification(from userInfo: [AnyHashable: Any]) {
guard let algorandNotification = parseAlgorandNotification(from: userInfo),
let accountId = getNotificationAccountId(from: algorandNotification) else {
return
}
handleNotificationActions(for: accountId, with: algorandNotification.details)
}
private func parseAlgorandNotification(from userInfo: [AnyHashable: Any]) -> AlgorandNotification? {
guard let userInfo = userInfo as? [String: Any],
let userInfoDictionary = userInfo["aps"] as? [String: Any],
let remoteNotificationData = try? JSONSerialization.data(withJSONObject: userInfoDictionary, options: .prettyPrinted),
let algorandNotification = try? JSONDecoder().decode(AlgorandNotification.self, from: remoteNotificationData) else {
return nil
}
return algorandNotification
}
private func getNotificationAccountId(from algorandNotification: AlgorandNotification) -> String? {
guard let accountId = algorandNotification.getAccountId() else {
if let message = algorandNotification.alert {
NotificationBanner.showInformation(message)
}
return nil
}
return accountId
}
private func handleNotificationActions(for accountId: String, with notificationDetail: NotificationDetail?) {
if UIApplication.shared.applicationState == .active,
let notificationDetail = notificationDetail {
NotificationCenter.default.post(name: .NotificationDidReceived, object: self, userInfo: nil)
if let notificationtype = notificationDetail.notificationType {
if notificationtype == .assetSupportRequest {
rootViewController?.openAsset(from: notificationDetail, for: accountId)
return
}
}
pushNotificationController.show(with: notificationDetail) {
self.rootViewController?.openAsset(from: notificationDetail, for: accountId)
}
} else {
if let notificationDetail = notificationDetail {
rootViewController?.openAsset(from: notificationDetail, for: accountId)
}
}
}
private func shouldHandleDeepLinkRouting(from url: URL) -> Bool {
let parser = DeepLinkParser(url: url)
guard let screen = parser.expectedScreen,
let rootViewController = rootViewController else {
return false
}
return rootViewController.handleDeepLinkRouting(for: screen)
}
}
extension AppDelegate {
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
extension AppDelegate {
func validateAccountManagerFetchPolling() {
shouldInvalidateAccountFetch = false
fetchAccounts()
}
func invalidateAccountManagerFetchPolling() {
shouldInvalidateAccountFetch = true
}
private func fetchAccounts(round: Int64? = nil) {
guard !shouldInvalidateAccountFetch else {
return
}
if session.authenticatedUser != nil {
accountManager.waitForNextRoundAndFetchAccounts(round: round) { nextRound in
self.fetchAccounts(round: nextRound)
}
}
}
}
extension AppDelegate {
private func updateUserInterfaceStyleIfNeeded() {
/// <note> Will update the appearance style if it's set to system since it might be changed from device settings.
/// Since user interface style is overriden, traitCollectionDidChange is not triggered
/// when the user interface is changed from the device settings while app is open.
/// Needs a minor delay to receive correct system interface value from traitCollection to override the current one.
if appConfiguration.session.userInterfaceStyle == .system {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.rootViewController?.changeUserInterfaceStyle(to: .system)
}
}
}
}
extension AppDelegate {
private enum Constants {
static let sessionInvalidateTime: Double = 60.0
}
}
| 34.382353 | 130 | 0.660679 |
4bae0ec85affb383a80af1610d14814874dd32f1 | 1,093 | //
// AssociatedObject.swift
// Pods
//
// Created by eme on 2017/4/27.
//
//
import Foundation
class AssociatedObject {
/// 获取关联属性
///
/// - parameter base: 关联类
/// - parameter key: 属性对应key
/// - parameter initialiser: 初始化闭包
///
/// - returns: 属性
static func associatedObject<ValueType: Any>(base: Any, key: UnsafePointer<UInt8>, initialiser: () -> ValueType) -> ValueType {
if let associated = objc_getAssociatedObject(base, key) as? ValueType {
return associated
}
let associated = initialiser()
objc_setAssociatedObject(base, key, associated, .OBJC_ASSOCIATION_RETAIN)
return associated
}
/// 设置关联属性值
///
/// - parameter base: 关联类
/// - parameter key: 属性对应key
/// - parameter value: 新值
static func associatedObject<ValueType: Any>(base: Any, key: UnsafePointer<UInt8>, value: ValueType) {
objc_setAssociatedObject(base, key, value, .OBJC_ASSOCIATION_RETAIN)
}
}
| 23.76087 | 130 | 0.573651 |
d58eda7c8d9e923fc7e9c781a97bc3ff3b8f7b58 | 441 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class S{let a=.h == Int}{"
{struct S<T:T.E
| 40.090909 | 79 | 0.736961 |
16291d5652e8f1a801fc574019587eb292888738 | 568 | import Basic
import Foundation
@testable import xcbuddykit
final class MockFileHandler: FileHandling {
var existsStub: ((AbsolutePath) -> Bool)?
var currentPathStub: AbsolutePath?
var globStub: ((AbsolutePath, String) -> [AbsolutePath])?
var currentPath: AbsolutePath {
return currentPathStub ?? AbsolutePath.current
}
func exists(_ path: AbsolutePath) -> Bool {
return existsStub?(path) ?? false
}
func glob(_ path: AbsolutePath, glob: String) -> [AbsolutePath] {
return globStub?(path, glob) ?? []
}
}
| 25.818182 | 69 | 0.667254 |
11630a070510fe17c36877d17f08306376743b7f | 1,670 | //
// Number.swift
// RethinkDBSwift
//
// Created by Jeremy Jacobson on 11/17/16.
//
//
import Foundation
import WarpCore
// because NSNumber sucks
public enum Number: ReqlSerializable, CustomStringConvertible, CustomDebugStringConvertible {
case int(Int64)
case uint(UInt64)
case float(Float)
case double(Double)
public var description: String {
switch self {
case .int(let i): return i.description
case .uint(let u): return u.description
case .float(let f): return f.description
case .double(let d): return d.description
}
}
public var debugDescription: String {
switch self {
case .int(let i): return i.description
case .uint(let u): return u.description
case .float(let f): return f.debugDescription
case .double(let d): return d.debugDescription
}
}
public var json: Any {
switch self {
case .int(let i): return i
case .uint(let u): return u
case .float(let f): return f
case .double(let d): return d
}
}
}
extension Number: JSONConvertible {
public init(json: JSON) throws {
switch json {
case .integer(let i):
self = .int(i)
default:
throw JSON.Error.invalidNumber
}
}
public func encoded() -> JSON {
switch self {
case .int(let i):
return .integer(i)
case .uint(let u):
return .integer(Int64(u))
case .float(let f):
return .double(Double(f))
case .double(let d):
return .double(d)
}
}
}
| 23.857143 | 93 | 0.567066 |
db5cb353215dcc63bb1ae3b8d2bcc3468d04178b | 1,457 | final class AuthorizationiPadPresentationController: UIPopoverPresentationController {
private let chromeView = UIView()
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
(presentedViewController as? AuthorizationViewController)?.chromeView.frame = containerView!.bounds
}
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
guard let presentedViewController = presentedViewController as? AuthorizationViewController,
let coordinator = presentedViewController.transitionCoordinator,
let containerView = containerView else { return }
presentedViewController.containerView = containerView
presentedViewController.chromeView.frame = containerView.bounds
presentedViewController.chromeView.alpha = 0
coordinator.animate(alongsideTransition: { _ in
presentedViewController.chromeView.alpha = 1
}, completion: nil)
}
override func dismissalTransitionWillBegin() {
super.dismissalTransitionWillBegin()
guard let presentedViewController = presentedViewController as? AuthorizationViewController,
let coordinator = presentedViewController.transitionCoordinator,
let presentedView = presentedView else { return }
coordinator.animate(alongsideTransition: { _ in
presentedViewController.chromeView.alpha = 0
}, completion: { _ in
presentedView.removeFromSuperview()
})
}
}
| 39.378378 | 103 | 0.785175 |
d552ce658cd8ff16f11f2d6daab7846ae6ca2d05 | 3,167 | //
// ExponeaNotificationContentService.swift
// ExponeaSDK
//
// Created by Dominik Hadl on 06/12/2018.
// Copyright © 2018 Exponea. All rights reserved.
//
import Foundation
import UserNotifications
import UserNotificationsUI
public class ExponeaNotificationContentService {
private let decoder: JSONDecoder = JSONDecoder.snakeCase
private var attachmentUrl: URL?
public init() { }
deinit {
attachmentUrl?.stopAccessingSecurityScopedResource()
}
public func didReceive(_ notification: UNNotification,
context: NSExtensionContext?,
viewController: UIViewController) {
guard Exponea.isExponeaNotification(userInfo: notification.request.content.userInfo) else {
Exponea.logger.log(.verbose, message: "Skipping non-Exponea notification")
return
}
createActions(notification: notification, context: context)
// Add image if any
if let first = notification.request.content.attachments.first,
first.url.startAccessingSecurityScopedResource() {
attachmentUrl = first.url
createImageView(on: viewController.view, with: first.url.path)
}
}
private func createActions(notification: UNNotification, context: NSExtensionContext?) {
guard #available(iOS 12.0, *),
let context = context,
let actionsObject = notification.request.content.userInfo["actions"],
let data = try? JSONSerialization.data(withJSONObject: actionsObject, options: []),
let actions = try? decoder.decode([ExponeaNotificationAction].self, from: data) else {
return
}
context.notificationActions = []
for (index, action) in actions.enumerated() {
context.notificationActions.append(
ExponeaNotificationAction.createNotificationAction(
type: action.action,
title: action.title,
index: index
)
)
}
}
private func createImageView(on view: UIView, with imagePath: String) {
let url = URL(fileURLWithPath: imagePath)
guard let data = try? Data(contentsOf: url) else {
Exponea.logger.log(.warning, message: "Unable to load image contents \(imagePath)")
return
}
let imageView = UIImageView(image: UIImage.gif(data: data))
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
// Constraints
imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
imageView.heightAnchor.constraint(lessThanOrEqualToConstant: 300).isActive = true
}
}
| 38.621951 | 100 | 0.657404 |
5dee16bc28dea74133a2dbf82eae8c34cbb06a4b | 402 | //
// DefaultMutable.swift
// Swiftest
//
// Created by Brian Strobach on 1/14/19.
//
public protocol DefaultMutable: Defaultable {
static var defaultConstructor: ClosureOut<Self> { get set }
}
extension DefaultMutable {
public static var `default`: Self {
return defaultConstructor()
}
}
public typealias DefaultMutableEmptyInitializable = DefaultMutable & EmptyInitializable
| 22.333333 | 87 | 0.731343 |
e09fcb3cb1d79283b9cf5a8c7fcc9c0744893f6f | 7,877 | //
// SwiftUI_CombineTests.swift
// SwiftUI-NotesTests
//
// Created by Joseph Heck on 6/13/19.
// Copyright © 2019 SwiftUI-Notes. All rights reserved.
//
import Combine
import XCTest
class SwiftUI_CombineTests: XCTestCase {
func testVerifySignature() {
let x = PassthroughSubject<String, Never>()
.flatMap { _ in
Future<String, Error> { promise in
promise(.success(""))
}.catch { _ in
Just("No user found")
}.map { result in
"\(result) foo"
}
}.eraseToAnyPublisher()
let y = PassthroughSubject<String, Never>()
.flatMap { _ in
Future<String, Error> { promise in
promise(.success(""))
}.catch { _ in
Just("No user found")
}.map { result in
"\(result) foo"
}
}
print("composed type")
print(type(of: x.self))
print("erased type")
print(type(of: y.self))
}
func testSimplePipeline() {
_ = Just(5)
.map { value -> String in
switch value {
case _ where value < 1:
return "none"
case _ where value == 1:
return "one"
case _ where value == 2:
return "couple"
case _ where value == 3:
return "few"
case _ where value > 8:
return "many"
default:
return "some"
}
}
.sink { receivedValue in
print("The end result was \(receivedValue)")
}
}
func testSimpleSequencePublisher() {
let originalListOfString = ["foo", "bar", "baz"]
// this publishes the stream combo: <String>,<Never>
let foo = Publishers.Sequence<[String], Never>(sequence: originalListOfString)
// this may be a lot more sensible to create with a PropertyWrapper of some form...
// there's a hint (that I haven't clued into) at the bottom of Combine of a function on Sequence called
// publisher() that returns a publisher<Self, Never>
let printingSubscriber = foo.sink { data in
print(data)
}
_ = foo
.collect(3)
.sink { (listOfStrings: [String]) in
XCTAssertEqual(listOfStrings, originalListOfString)
}
XCTAssertNotNil(printingSubscriber)
}
func testAnyFuture_CreationAndUse() {
// A generic Future that always returns <Any>"A result"
let goodPlace = Future<Any, Never> { promise in
promise(.success("A result"))
}
let goodSinkHolder = goodPlace.sink(receiveValue: { receivedThing in
// receiveValue here is typed as "<Any>"
XCTAssertNotNil(receivedThing)
print(receivedThing)
})
// just to hide the Xcode "unused" warnings really...
XCTAssertNotNil(goodSinkHolder)
XCTAssertNotNil(goodPlace)
}
func testStringFuture_CreationAndUse() {
// A generic Future that always returns <Any>"A result"
let goodPlace = Future<String, Never> { promise in
promise(.success("A result"))
}
let goodSinkHolder = goodPlace.sink(receiveValue: { receivedThing in
// receivedThing here is typed as String
XCTAssertNotNil(receivedThing)
// which makes it a lot easier to assert against
XCTAssertEqual(receivedThing, "A result")
})
// just to hide the Xcode "unused" warnings really...
XCTAssertNotNil(goodSinkHolder)
XCTAssertNotNil(goodPlace)
}
/* - using this to explore - not functional or useful yet
func testPublisherFor() {
let x: String = "whassup"
// as good a place to start as any...
let publisher = PassthroughSubject<String?, Never>()
// Publishers.ValueForKey
.publisher(for: \.foo) // <- This is for getting a keypath to a property - not sure if it's passed down from the publisher, or if this is meant to send to a publisher keypath that the code scope has access to... (a variant on sink or assign)
}
*/
func testAnyFuture_FailingAFuture() {
enum SampleError: Error {
case exampleError
case aDifferentError
}
// A generic Future that always returns a Failure
let badPlace = Future<String, SampleError> { promise in
// promise is Result<Any, Error> and this is expect to return Void
// you generally call promise with .success() or .failure() enclosing relevant information (or results)
promise(.failure(SampleError.exampleError))
}
// NOTE(heckj) I'm not entirely clear on how you can/should check failure path of a result chain
// .sink() is a good place to drop in assertions for determining what happened in the success path,
// but never gets called when a Future publisher sends a failure result.
// IDEA: using .assertNoFailure()
// this causes a fatalException and invoke the debugger if you try this path
// badPlace
// .assertNoFailure()
// IDEA: Can we use "mapError" and slip in assert to validate the failure propagating through the chain?
// unfortunately, no - sticking an assert as the only thing in that closure will return it, which causes
// the compiler to complain about changing the error type to the Error type that XCTAssert... methods
// use to validate the test case.
// and using an assert in the sequence either never gets executed or doesn't end up propagating the error
// up to the test runner.
/*
let _ = badPlace
.mapError({ someError -> SampleError in // -> SampleError is because the compiler can't infer the type...
XCTAssertNil(someError) // by itself this errors with: Cannot convert value of type '()' to closure result type '_'
// XCTAssertEqual(SampleError.exampleError, someError)
// This doesn't work, compiler error: "Protocol type 'Error' cannot conform to 'Equatable' because only concrete types can conform to protocols"
return SampleError.aDifferentError
})
*/
// one way that *does* appear to work is to explicitly catch the error and using .catch() to
// convert it into a result value, and then verify that result value gets called.
_ = badPlace
.catch { _ in
// expected to return a publisher of SOME form...
// .catch() is used to keep the whole stream alive and connected
// XCTAssertNotNil(someError)
// trying to assert anything in the catch results in the compiler erroring:
// Cannot invoke 'sink' with an argument list of type '(receiveValue: @escaping (Any) -> Void)'
// while this is catching an error, I'm not entirely clear on if you can validate
// the kind and any details of the specifics of the instance of error - that is, which
// error happened...
Just("yo")
}
.sink(receiveValue: { placeholder in
XCTAssertEqual(placeholder, "yo")
})
}
// IDEA: It might make more sense to use Subject to check/test values being processed in Combine
// rather than dropping them into .sink() which triggers the invocation of everything, and in which failures
// propagate upward to see a failure.
}
| 38.99505 | 250 | 0.578012 |
f9e3f6686d506503550a095f038a50394fba5750 | 439 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class a<T{func b{(a{}func{struct B<I:T.T
| 43.9 | 79 | 0.747153 |
ebcf97bd6c53b36252b8abcd0d4011969da99562 | 1,459 | //
// SwiftPracticeProjectUITests.swift
// SwiftPracticeProjectUITests
//
// Created by Chiu Young on 2020/2/24.
// Copyright © 2020 qy. All rights reserved.
//
import XCTest
class SwiftPracticeProjectUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// 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() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.159091 | 182 | 0.660041 |
2898433cb7cd018da91d3ab7da3ab2d424cfd094 | 4,148 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// A `ByteString` represents a sequence of bytes.
///
/// This struct provides useful operations for working with buffers of
/// bytes. Conceptually it is just a contiguous array of bytes (UInt8), but it
/// contains methods and default behavor suitable for common operations done
/// using bytes strings.
///
/// This struct *is not* intended to be used for significant mutation of byte
/// strings, we wish to retain the flexibility to micro-optimize the memory
/// allocation of the storage (for example, by inlining the storage for small
/// strings or and by eliminating wasted space in growable arrays). For
/// construction of byte arrays, clients should use the `OutputByteStream` class
/// and then convert to a `ByteString` when complete.
public struct ByteString: ExpressibleByArrayLiteral, Hashable {
/// The buffer contents.
fileprivate var _bytes: [UInt8]
/// Create an empty byte string.
public init() {
_bytes = []
}
/// Create a byte string from a byte array literal.
public init(arrayLiteral contents: UInt8...) {
_bytes = contents
}
/// Create a byte string from an array of bytes.
public init(_ contents: [UInt8]) {
_bytes = contents
}
/// Create a byte string from an byte buffer.
public init<S: Sequence> (_ contents: S) where S.Iterator.Element == UInt8 {
_bytes = [UInt8](contents)
}
/// Create a byte string from the UTF8 encoding of a string.
public init(encodingAsUTF8 string: String) {
_bytes = [UInt8](string.utf8)
}
/// Access the byte string contents as an array.
public var contents: [UInt8] {
return _bytes
}
/// Return the byte string size.
public var count: Int {
return _bytes.count
}
/// Return the string decoded as a UTF8 sequence, if possible.
public var asString: String? {
// FIXME: This is very inefficient, we need a way to pass a buffer. It
// is also wrong if the string contains embedded '\0' characters.
let tmp = _bytes + [UInt8(0)]
return tmp.withUnsafeBufferPointer { ptr in
return String(validatingUTF8: unsafeBitCast(ptr.baseAddress, to: UnsafePointer<CChar>.self))
}
}
/// Return the string decoded as a UTF8 sequence, substituting replacement
/// characters for ill-formed UTF8 sequences.
public var asReadableString: String {
// FIXME: This is very inefficient, we need a way to pass a buffer. It
// is also wrong if the string contains embedded '\0' characters.
let tmp = _bytes + [UInt8(0)]
return tmp.withUnsafeBufferPointer { ptr in
return String(cString: unsafeBitCast(ptr.baseAddress, to: UnsafePointer<CChar>.self))
}
}
}
/// Conform to CustomStringConvertible.
extension ByteString: CustomStringConvertible {
public var description: String {
// For now, default to the "readable string" representation.
return "<ByteString:\"\(asReadableString)\">"
}
}
/// ByteStreamable conformance for a ByteString.
extension ByteString: ByteStreamable {
public func write(to stream: OutputByteStream) {
stream.write(_bytes)
}
}
/// StringLiteralConvertable conformance for a ByteString.
extension ByteString: ExpressibleByStringLiteral {
public typealias UnicodeScalarLiteralType = StringLiteralType
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
_bytes = [UInt8](value.utf8)
}
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
_bytes = [UInt8](value.utf8)
}
public init(stringLiteral value: StringLiteralType) {
_bytes = [UInt8](value.utf8)
}
}
| 36.069565 | 104 | 0.692623 |
e2f87e838b247629e8987b51e3bf211229b3ead4 | 513 | //
// TemplateProjectSwiftUIApp.swift
// TemplateProjectSwiftUI
//
// Created by hansong on 10/27/20.
//
import SwiftUI
@main
struct TemplateProjectSwiftUIApp: App {
var body: some Scene {
WindowGroup {
VStack {
TabbarView().accentColor(.yellow)
}
}
}
}
struct TemplateProjectSwiftUIApp_Previews: PreviewProvider {
static var previews: some View {
/*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
}
}
| 19.730769 | 71 | 0.606238 |
fccb917e0a6fdf2525d9efb46f0c65d14e148959 | 3,782 | import UIKit
extension GraffeineLayer {
public enum Region {
case main, topGutter, rightGutter, bottomGutter, leftGutter
public static func calculateMainRegionFrame(layers: [GraffeineLayer], bounds: CGRect) -> CGRect {
return layers.reduce(bounds) { result, next in
var output = result
switch next.region {
case .topGutter:
let delta = next.frame.size.height - output.origin.y
if (delta > 0) {
output.origin.y += delta
output.size.height -= delta
}
case .rightGutter:
let gutterX = output.origin.x + output.size.width
let gutterWidth = (bounds.size.width - gutterX)
let delta = next.frame.size.width - gutterWidth
if (delta > 0) {
output.size.width -= delta
}
case .bottomGutter:
let gutterY = output.origin.y + output.size.height
let gutterHeight = (bounds.size.height - gutterY)
let delta = next.frame.size.height - gutterHeight
if (delta > 0) {
output.size.height -= delta
}
case .leftGutter:
let delta = next.frame.size.width - output.origin.x
if (delta > 0) {
output.origin.x += delta
output.size.width -= delta
}
case .main:
break
}
return output
}
}
public static func calculateRegionFrame(layer: GraffeineLayer, precomputedMainRegionFrame mainFrame: CGRect) -> CGRect {
let layerFrame = layer.frame
let insets = layer.insets
let insetSize = CGSize(width: insets.left + insets.right,
height: insets.top + insets.bottom)
switch layer.region {
case .topGutter:
return CGRect(x: mainFrame.origin.x + insets.left,
y: 0.0 + insets.top,
width: mainFrame.size.width - insetSize.width,
height: layerFrame.height - insetSize.height)
case .rightGutter:
return CGRect(x: mainFrame.origin.x + mainFrame.size.width + insets.left,
y: mainFrame.origin.y + insets.top,
width: layerFrame.size.width - insetSize.width,
height: mainFrame.size.height - insetSize.height)
case .bottomGutter:
return CGRect(x: mainFrame.origin.x + insets.left,
y: mainFrame.origin.y + mainFrame.size.height + insets.top,
width: mainFrame.size.width - insetSize.width,
height: layerFrame.size.height - insetSize.height)
case .leftGutter:
return CGRect(x: 0.0 + insets.left,
y: mainFrame.origin.y + insets.top,
width: layerFrame.size.width - insetSize.width,
height: mainFrame.size.height - insetSize.height)
case .main:
return CGRect(x: mainFrame.origin.x + insets.left,
y: mainFrame.origin.y + insets.top,
width: mainFrame.size.width - insetSize.width,
height: mainFrame.size.height - insetSize.height)
}
}
}
}
| 40.234043 | 128 | 0.476467 |
1d3c542a0713d4ddfdf5c2f10c0fb844141ecbd3 | 1,413 | //
// AppDelegate.swift
// Photos
//
// Created by Ashvarya Singh on 29/08/20.
// Copyright © 2020 Ashvaray. 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.184211 | 179 | 0.747346 |
f5608d8e864349ce6642496916616873de77b8f8 | 875 | //
// MessageViewController.swift
// SwiftAnimationTransition
//
// Created by Jashion on 2017/2/6.
// Copyright © 2017年 BMu. All rights reserved.
//
import UIKit
class MessageViewController: UIViewController {
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.
}
/*
// 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.
}
*/
}
| 24.305556 | 106 | 0.676571 |
75e43ef5e44ff4722cdda68e39825bb05872f17e | 991 | //
// User.swift
// Hearing Aid App
//
// Created by Artem Sherbachuk on 5/17/21.
//
import Foundation
final class User: NSObject {
static let shared = User()
var subscriptionInfo: PurchasesInfo?
private var hasSubscription: Bool {
return subscriptionInfo?.isActive ?? false
}
var isPremium: Bool {
return hasSubscription || isTrialModeActive
}
var installDate: Date {
let date = UserDefaults.standard.value(forKey: "installDate") as? Date
if let date = date {
return date
} else {
let now = Date()
UserDefaults.standard.setValue(now, forKey: "installDate")
return now
}
}
private var trialTimeDays = 7
var trialEndDate: Date {
return Calendar.current.date(byAdding: .day, value: trialTimeDays, to: installDate) ?? Date()
}
var isTrialModeActive: Bool {
let now = Date()
return trialEndDate >= now
}
}
| 21.543478 | 101 | 0.601413 |
79f92222f31202dd1febb63b6b8a7e878aacf1d5 | 1,971 | //
// Keychain.swift
// k
//
// Created by William Henderson.
// Copyright (c) 2017 Serious Software. All rights reserved.
//
import Foundation
import KeychainAccess
import CocoaLumberjack
public class KeychainManager {
public static private(set) var shared : KeychainManager!
struct Static {
static var onceToken : Int = 0
static var sharedManager : KeychainManager?
}
private(set) var keychain: Keychain!
public var accessToken : String? {
get {
do {
if let token = try self.keychain.getString("accessToken") {
return token
}
} catch let error {
DDLogError("Error accessing keychain: \(error)")
}
return nil
}
set {
self.keychain["accessToken"] = newValue
}
}
public var accessTokenExpiresIn : Date? {
get {
do {
if let expiresInData = try self.keychain.getData("accessTokenExpiresIn"),
let expiresIn = NSKeyedUnarchiver.unarchiveObject(with: expiresInData) as? Date {
return expiresIn
}
} catch let error {
DDLogError("Error accessing keychain: \(error)")
}
return nil
}
set {
if let newExpiresIn = newValue {
self.keychain[data: "accessTokenExpiresIn"] = NSKeyedArchiver.archivedData(withRootObject: newExpiresIn)
} else {
self.keychain[data: "accessTokenExpiresIn"] = nil
}
}
}
class func startup() {
if (KeychainManager.shared == nil) {
KeychainManager.shared = KeychainManager()
KeychainManager.shared.keychain = Keychain(service: "com.Knock.RideReport").accessibility(.afterFirstUnlock)
}
}
}
| 28.157143 | 120 | 0.538813 |
147e8ee2162e7b3bcd4f2ee218a8f472ebe34023 | 1,539 | //
// LabelFactory.swift
// FlexControls
//
// Created by Martin Rehder on 22.07.16.
/*
* Copyright 2016-present Martin Jacob Rehder.
* http://www.rehsco.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import StyledLabel
public final class StyledLabelFactory {
public static func defaultStyledLabel() -> StyledLabel {
let label = StyledLabel()
label.textAlignment = .center
label.text = ""
return label
}
}
| 34.977273 | 80 | 0.719298 |
e2e348a16da34751613c376a366e2575b18ffed6 | 220 | //
// Cornucopia – (C) Dr. Lauer Information Technology
//
import UIKit.NSTextAttachment
public extension NSTextAttachment {
var CC_attributedString: NSAttributedString { NSAttributedString(attachment: self) }
}
| 20 | 88 | 0.768182 |
f566e43d6dffb5060330e930edba057cde26018b | 6,133 | import Foundation
import XCTest
@testable import TuistGenerator
final class InfoPlistContentProviderTests: XCTestCase {
var subject: InfoPlistContentProvider!
override func setUp() {
super.setUp()
subject = InfoPlistContentProvider()
}
func test_content_wheniOSApp() {
// Given
let target = Target.test(platform: .iOS, product: .app)
// When
let got = subject.content(target: target, extendedWith: ["ExtraAttribute": "Value"])
// Then
assertEqual(got, [
"CFBundleName": "$(PRODUCT_NAME)",
"CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)",
"UIRequiredDeviceCapabilities": ["armv7"],
"UISupportedInterfaceOrientations": [
"UIInterfaceOrientationPortrait",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight",
],
"CFBundleShortVersionString": "1.0",
"UIMainStoryboardFile": "Main",
"LSRequiresIPhoneOS": true,
"CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)",
"UILaunchStoryboardName": "LaunchScreen",
"CFBundlePackageType": "APPL",
"UISupportedInterfaceOrientations~ipad": [
"UIInterfaceOrientationPortrait",
"UIInterfaceOrientationPortraitUpsideDown",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight",
],
"CFBundleVersion": "1",
"ExtraAttribute": "Value",
"CFBundleExecutable": "$(EXECUTABLE_NAME)",
"CFBundleInfoDictionaryVersion": "6.0",
])
}
func test_content_whenMacosApp() {
// Given
let target = Target.test(platform: .macOS, product: .app)
// When
let got = subject.content(target: target, extendedWith: ["ExtraAttribute": "Value"])
// Then
assertEqual(got, [
"CFBundleIconFile": "",
"CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)",
"CFBundlePackageType": "APPL",
"NSHumanReadableCopyright": "Copyright ©. All rights reserved.",
"NSMainStoryboardFile": "Main",
"NSPrincipalClass": "NSApplication",
"CFBundleShortVersionString": "1.0",
"CFBundleName": "$(PRODUCT_NAME)",
"CFBundleInfoDictionaryVersion": "6.0",
"CFBundleVersion": "1",
"CFBundleExecutable": "$(EXECUTABLE_NAME)",
"CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)",
"ExtraAttribute": "Value",
"LSMinimumSystemVersion": "$(MACOSX_DEPLOYMENT_TARGET)",
])
}
func test_content_whenMacosFramework() {
// Given
let target = Target.test(platform: .macOS, product: .framework)
// When
let got = subject.content(target: target, extendedWith: ["ExtraAttribute": "Value"])
// Then
assertEqual(got, [
"CFBundleShortVersionString": "1.0",
"CFBundleExecutable": "$(EXECUTABLE_NAME)",
"CFBundleVersion": "1",
"NSHumanReadableCopyright": "Copyright ©. All rights reserved.",
"CFBundleInfoDictionaryVersion": "6.0",
"CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)",
"ExtraAttribute": "Value",
"CFBundlePackageType": "FMWK",
"CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)",
"CFBundleName": "$(PRODUCT_NAME)",
])
}
func test_content_whenMacosStaticLibrary() {
// Given
let target = Target.test(platform: .macOS, product: .staticLibrary)
// When
let got = subject.content(target: target, extendedWith: ["ExtraAttribute": "Value"])
// Then
XCTAssertNil(got)
}
func test_content_whenMacosDynamicLibrary() {
// Given
let target = Target.test(platform: .macOS, product: .dynamicLibrary)
// When
let got = subject.content(target: target, extendedWith: ["ExtraAttribute": "Value"])
// Then
XCTAssertNil(got)
}
func test_contentPackageType() {
assertPackageType(subject.content(target: .test(product: .app), extendedWith: [:]), "APPL")
assertPackageType(subject.content(target: .test(product: .unitTests), extendedWith: [:]), "BNDL")
assertPackageType(subject.content(target: .test(product: .uiTests), extendedWith: [:]), "BNDL")
assertPackageType(subject.content(target: .test(product: .bundle), extendedWith: [:]), "BNDL")
assertPackageType(subject.content(target: .test(product: .framework), extendedWith: [:]), "FMWK")
assertPackageType(subject.content(target: .test(product: .staticFramework), extendedWith: [:]), "FMWK")
}
fileprivate func assertPackageType(_ lhs: [String: Any]?,
_ packageType: String?,
file: StaticString = #file,
line: UInt = #line) {
let value = lhs?["CFBundlePackageType"] as? String
if let packageType = packageType {
XCTAssertEqual(value, packageType, "Expected package type \(packageType) but got \(value ?? "")", file: file, line: line)
} else {
XCTAssertNil(value, "Expected package type to be nil and got \(value ?? "")", file: file, line: line)
}
}
fileprivate func assertEqual(_ lhs: [String: Any]?,
_ rhs: [String: Any],
file: StaticString = #file,
line: UInt = #line) {
let lhsNSDictionary = NSDictionary(dictionary: lhs ?? [:])
let rhsNSDictionary = NSDictionary(dictionary: rhs)
let message = """
The dictionary:
\(lhs ?? [:])
Is not equal to the expected dictionary:
\(rhs)
"""
XCTAssertTrue(lhsNSDictionary.isEqual(rhsNSDictionary), message, file: file, line: line)
}
}
| 38.33125 | 133 | 0.581119 |
09c744d30e3b50416138069dc48b0e9cdddd844c | 703 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
//
// IntStreamExtension.swift
// Antlr.swift
//
// Created by janyou on 15/9/3.
//
extension IntStream {
///
/// The value returned by _#LA LA()_ when the end of the stream is
/// reached.
///
public static var EOF: Int {
return -1
}
///
/// The value returned by _#getSourceName_ when the actual name of the
/// underlying source is not known.
///
public static var UNKNOWN_SOURCE_NAME: String {
return "<unknown>"
}
}
| 21.30303 | 74 | 0.614509 |
e5be63804ada6d49c819e7f544330469606c7521 | 2,049 | import Async
import Service
/// Types conforming to this protocol can be used
/// as a database connection for executing queries.
public protocol DatabaseConnection: DatabaseConnectable, Extendable {
/// Closes the database connection when finished.
func close()
}
extension DatabaseConnection {
/// See `DatabaseConnectable.connect(to:)`
public func connect<D>(to database: DatabaseIdentifier<D>?) -> Future<D.Connection> {
return Future.map(on: self) {
guard let conn = self as? D.Connection else {
throw DatabaseKitError(
identifier: "connectable",
reason: "Unexpected \(#function): \(self) not \(D.Connection.self)",
source: .capture()
)
}
return conn
}
}
}
/// MARK: Deprecated
extension DatabaseConnection {
@available(*, deprecated, message: "Implement on `DatabaseConnection` instead.")
public var extend: Extend {
get {
let cache: ExtendCache
if let existing = extendCache.currentValue {
cache = existing
} else {
cache = .init()
extendCache.currentValue = cache
}
let extend: Extend
if let existing = cache.storage[.init(self)] {
extend = existing
} else {
extend = .init()
cache.storage[.init(self)] = extend
}
return extend
}
set {
let cache: ExtendCache
if let existing = extendCache.currentValue {
cache = existing
} else {
cache = .init()
extendCache.currentValue = cache
}
cache.storage[.init(self)] = newValue
}
}
}
fileprivate final class ExtendCache {
var storage: [ObjectIdentifier: Extend]
init() { storage = [:] }
}
fileprivate var extendCache: ThreadSpecificVariable<ExtendCache> = .init()
| 29.271429 | 89 | 0.549048 |
fb100decb2509750d5abb6e1bee4176bc2741721 | 4,945 | import Foundation
import Socket
public typealias BroadcastBeginCallback = (Broadcast?, PupilSocket?, Error?) -> Void
public protocol PupilSocketProtocol {
static func createStream(for broadcast: Broadcast, onReady: @escaping BroadcastBeginCallback)
var bytesWrote: Int { get }
func write(_ data: Data)
}
public enum PupilSocketError: Error {
case protocolsNotSupport
case noServers
case couldNotConnectToServers
}
public class PupilSocket: PupilSocketProtocol {
fileprivate var socket: Socket
fileprivate var socketQ: DispatchQueue
public private(set) var running = false
public var hostName: String
public var port: Int32
public var bytesWrote: Int = 0
private var writeBuffer: ThreadSafeArray<UInt8>
public func write(_ data: Data) {
self.writeBuffer.append(contentsOf: [UInt8](data))
self.sendBytesToServer(length: data.count)
}
private func sendBytesToServer(length: Int) {
self.socketQ.async {
do {
let bytes = self.writeBuffer.first(upTo: length)
let data = Data(bytes)
let wrote = try self.socket.write(from: data)
self.bytesWrote += wrote
self.writeBuffer.removeFirst(n: wrote)
} catch let error { print("Couldn't write bytes to server:", error.localizedDescription) }
}
}
public static func createStream(for broadcast: Broadcast,
onReady: @escaping BroadcastBeginCallback)
{
guard let servers = broadcast.pupil else {
onReady(broadcast, nil, PupilSocketError.noServers)
return
}
for server in servers {
do {
let socket = try PupilSocket.setup(broadcast.broadcastID, on: server)
onReady(broadcast, socket, nil)
return
} catch let error {
print("Problem setting up pupil socket session:", error)
}
}
onReady(broadcast, nil, PupilSocketError.couldNotConnectToServers)
}
internal static func setup(_ identifier: String,
on server: PupilServer) throws -> PupilSocket
{
let sync = DispatchGroup()
sync.enter()
let socket = try PupilSocket(identifier: identifier, server: server, onReady: { ps in
sync.leave()
})
sync.wait()
return socket
}
internal init(identifier: String, server: PupilServer, onReady: @escaping (PupilSocket) -> ()) throws {
if let port = server.ports.filter({ $0.proto == "tcp" }).first {
let sock = try Socket.create()
try sock.connect(to: server.host, port: port.port)
self.running = true
self.socket = sock
self.port = port.port
self.hostName = server.host
self.socketQ = DispatchQueue(label: "\(sock.socketfd).socket.q")
self.writeBuffer = ThreadSafeArray<UInt8>()
self.setup(with: identifier, onReady: onReady)
} else {
throw PupilSocketError.protocolsNotSupport
}
}
internal func setup(with identifier: String, onReady: @escaping (PupilSocket) -> ()) {
self.socketQ.async {[unowned self] in
var readBuf = Data(capacity: 1024)
repeat {
do {
let read = try self.socket.read(into: &readBuf)
if read > 0 {
if let msg = String(data: readBuf[0..<read], encoding: .utf8) {
switch msg {
case "HI\n":
try self.socket.write(from: "\(identifier)\n")
readBuf.count = 0
case "BEGIN\n":
onReady(self)
self.running = false
default:
_=0+0
}
}
} else {
if self.socket.remoteConnectionClosed {
self.socketClosed()
self.running = false
}
}
} catch {
self.running = false
if self.socket.remoteConnectionClosed { self.socketClosed() }
}
} while self.running
}
}
internal func set(broadcastID: String, onReady: @escaping () -> ()) {
do {
try self.socket.write(from: "\(broadcastID)\n")
onReady()
} catch { self.running = false }
}
private func socketClosed() {
print("socket closed")
}
}
| 34.58042 | 108 | 0.518706 |
0996e92a3b81ddae00f06320a854ab29b81afaa1 | 999 | import UIKit
import SDWebImage
class ImageManager {
static let shared: ImageManager = ImageManager()
let imageCache = SDWebImageManager.shared().imageCache!
private var downloadingUrls: Set<URL> = Set<URL>()
func getCache(forKey name: String) -> UIImage? {
return imageCache.imageFromMemoryCache(forKey: name) ?? imageCache.imageFromDiskCache(forKey: name)
}
func prefetch(urls: [URL]) {
var prefetchUrls: [URL] = []
for url in urls {
guard !downloadingUrls.contains(url) else {return}
guard getCache(forKey: url.absoluteString) == nil else {return}
downloadingUrls.insert(url)
prefetchUrls.append(url)
}
let prefetcher = SDWebImagePrefetcher()
prefetcher.options = [.highPriority, .handleCookies]
prefetcher.prefetchURLs(urls, progress: nil) { (_, _) in
prefetchUrls.forEach { self.downloadingUrls.remove($0) }
}
}
}
| 33.3 | 107 | 0.630631 |
231af01a2dcbcf261c696ba9df2a0c7bbef3cb0f | 2,011 | //
// WrapSampleView.swift
// Sample
//
// Created by Trung on 8/11/20.
// Copyright © 2020 trungnguyenthien. All rights reserved.
//
import Foundation
import UIKit
import Kiss
import UIBuilder
private func makeTag(_ text: String) -> UILabel {
let label = large(text: " \(text) ", line: 1)
.background(MaterialColor.grey100)
.stroke(size: 1, color: MaterialColor.black)
return label
}
private func box(
_ width: Double,
_ height: Double,
_ color: UIColor = MaterialColor.blue600
) -> Kiss.UIViewLayout {
return view(color).cornerRadius(4)
.kiss.layout.margin(5).size(width, height)
}
class WrapSampleView: UIView {
let tag1 = makeTag("Black")
let tag2 = makeTag("LightGreen")
let tag3 = makeTag("Orange")
let tag4 = makeTag("DarkRed")
let tag5 = makeTag("Red")
let view1 = view(.blue)
let view2 = view(.red)
let view3 = view(.green)
lazy var layout1 = wrap {
box(50, 50)
box(150, 20, .green).crossAlign(self: .start)
box(50, 80)
box(100, 50)
box(50, 10, .orange).crossAlign(self: .end)
box(150, 50)
box(150, 20, .red).crossAlign(self: .center)
box(50, 80)
box(100, 50)
box(50, 50)
}.padding(10).mainAlign(.center)
override init(frame: CGRect) {
super.init(frame: frame)
kiss.constructIfNeed(layout: layout1)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
kiss.constructIfNeed(layout: layout1)
}
public override func layoutSubviews() {
super.layoutSubviews()
kiss.updateChange(width: frame.width, height: frame.height)
}
public override var intrinsicContentSize: CGSize {
kiss.estimatedSize()
}
open override func sizeToFit() {
kiss.updateChange()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
kiss.estimatedSize(width: size.width, height: size.height)
}
}
| 24.82716 | 67 | 0.612133 |
46bf1947a89dfffbc8f633a46caaa2807806bb5c | 1,170 | //
// ThiagoUITests.swift
// ThiagoUITests
//
// Created by Thiago B Claramunt on 09/05/19.
// Copyright © 2019 Thiago B Claramunt. All rights reserved.
//
import XCTest
class ThiagoUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.428571 | 182 | 0.690598 |
4a412552d900fe6473513ce8864dc42770633ec5 | 448 | import Foundation
extension String {
static func characters(amount: Int = 255) -> String {
var chars = ""
if amount > 0 {
for _ in 0..<amount {
#if swift(>=4.2)
let char = Character(UnicodeScalar(Int.random(in: 0..<Int.max) % (122 - 97) + 97)!)
#else
let char = Character(UnicodeScalar(arc4random() % (122-97) + 97)!)
#endif
chars.append(char)
}
}
return chars
}
}
| 21.333333 | 91 | 0.542411 |
381b1ed65e06bab98bf3a342fe81b68b5c1d8f0b | 1,412 | //
// AppDelegate.swift
// FMDBTool_swift
//
// Created by sunke on 2020/9/20.
// Copyright © 2020 KentSun. 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.157895 | 179 | 0.747875 |
7974fbb27f7819b2863ca6dfeeeaa16e04bc3ab9 | 4,365 | /*
Copyright 2020. Huawei Technologies Co., Ltd. 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import SystemConfiguration
import CoreTelephony
import Foundation
let AgcAppmessagingLog = AgcAppmessagingLogger(version: "1.2.1.300", service: "ReactNativeAGCAppMessaging")
/// Custom AgcAppmessagingLogger Class to listen api log events from RN Side.
final class AgcAppmessagingLogger {
/// Info Types to declare success and failure scenarios.
public enum InfoType{
case call, success, fail
}
private var prefix: String = GenericFunctions.className(AgcAppmessagingLogger.self)
private var version: String?
private var service: String?
/// Version and Service names may be added to give more detail in panel.
/// - Parameters:
/// - version: Refers to version number of the framework.
/// - service: Refers to service declaration.
public init(version: String? = nil, service: String? = nil) {
self.version = version
self.service = service
}
/// This function can be used during synchronized events. It gets the method name, calculates start end end times and reports to console as single events.
/// - Parameters:
/// - file: Refers to file name that the function is in.
/// - line: Refers to line number.
/// - name: Refers to name of the function.
/// - eventType: Refers to InfoType instance.
/// - message: Refers to message that can be added in the panel.
/// - block: Refers to function that will be used.
/// - Returns: Void
func debug(file: String = #file, line: Int = #line, name: String = #function, _ message: String, block:()->()) {
showInPanel(file:file, line:line, name:name, message: message, type: .call)
block()
showInPanel(file:file, line:line, name:name, message: message, type: .success)
}
// MARK: - Private Functions
/// Shows infos in panel
func showInPanel(callTime: Double? = nil,
file: String = #file,
line: Int = #line,
name: String = #function,
message: String?,
timeElapsed: Double? = nil,
type: AgcAppmessagingLogger.InfoType) {
switch type {
case .call:
printCall(name)
return
case .success:
printStatus(name, true)
case .fail:
printStatus(name, false)
}
}
/// Prints call messages among with the function names.
private func printCall(_ message: String){
print("call \(message)")
}
/// Print status messages.
private func printStatus(_ name: String, _ status: Bool){
let statusMsg = status ? "success" : "failure"
print("\(name) \(statusMsg)")
}
/// Returns file name of the function is in.
private func getFileName(_ filePath: String) -> String {
let parser = filePath.split(separator:"/")
if let fileName = String(parser.last ?? "").split(separator: ".").first {
return String(fileName)
}
return ""
}
}
// MARK: - Helper Functions
struct GenericFunctions {
static func className<T>(_ name: T) -> String {
return "\(name)"
}
}
extension Bundle {
public var packageName: String {
if let result = Bundle.main.bundleIdentifier {
return result
} else {
return "⚠️"
}
}
public var appVersionShort: String {
if let result = infoDictionary?["CFBundleShortVersionString"] as? String {
return result
} else {
return "⚠️"
}
}
public var appVersionLong: String {
if let result = infoDictionary?["CFBundleVersion"] as? String {
return result
} else {
return "⚠️"
}
}
public var appName: String {
if let result = infoDictionary?["CFBundleName"] as? String {
return result
} else {
return "⚠️"
}
}
}
| 30.739437 | 156 | 0.646277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.