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
|
---|---|---|---|---|---|
4bc744a915d73e18b35ee262295642da6b7eef18 | 726 | //
// PromotionCodeInfoDTO.swift
// MozoSDK
//
// Created by Hoang Nguyen on 7/8/19.
//
import Foundation
import SwiftyJSON
public class PromotionCodeInfoDTO {
public var detail: PromotionDetailDTO?
public var promo: PromotionDTO?
public var userInfo: UserProfileDTO?
public required init?(json: SwiftyJSON.JSON) {
self.detail = PromotionDetailDTO(json: json["detail"])
self.promo = PromotionDTO(json: json["promo"])
self.userInfo = UserProfileDTO(json: json["userInfo"])
}
public static func arrayFrom(_ json: SwiftyJSON.JSON) -> [PromotionCodeInfoDTO] {
let array = json.array?.map({ PromotionCodeInfoDTO(json: $0)! })
return array ?? []
}
}
| 27.923077 | 85 | 0.668044 |
dd62fbe828c1ed3b1daaeb8c07f8d77aaaa8298f | 645 |
//
// PageViewMeddleware.swift
// App
//
// Created by Jinxiansen on 2018/5/30.
//
import Vapor
public final class PageViewMeddleware : Middleware {
public func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
try printLog(request)
return try next.respond(to: request)
}
func printLog(_ request: Request) throws {
let method = request.http.method
let path = request.http.url.absoluteString
let reqString = "\(method) \(path) \(TimeManager.currentTime()) \n"
print(reqString)
}
}
| 17.916667 | 110 | 0.610853 |
09218974909086aa9a36c77a5f0b4c353539bef6 | 24,492 | import Cocoa
import FlutterMacOS
import UserNotifications
public class FlutterLocalNotificationsPlugin: NSObject, FlutterPlugin, UNUserNotificationCenterDelegate, NSUserNotificationCenterDelegate {
struct MethodCallArguments {
static let presentAlert = "presentAlert"
static let presentSound = "presentSound"
static let presentBadge = "presentBadge"
static let payload = "payload"
static let defaultPresentAlert = "defaultPresentAlert"
static let defaultPresentSound = "defaultPresentSound"
static let defaultPresentBadge = "defaultPresentBadge"
static let requestAlertPermission = "requestAlertPermission"
static let requestSoundPermission = "requestSoundPermission"
static let requestBadgePermission = "requestBadgePermission"
static let alert = "alert"
static let sound = "sound"
static let badge = "badge"
static let notificationLaunchedApp = "notificationLaunchedApp"
static let id = "id"
static let title = "title"
static let subtitle = "subtitle"
static let body = "body"
static let scheduledDateTime = "scheduledDateTime"
static let timeZoneName = "timeZoneName"
static let scheduledNotificationRepeatFrequency = "scheduledNotificationRepeatFrequency"
static let platformSpecifics = "platformSpecifics"
static let badgeNumber = "badgeNumber"
static let repeatInterval = "repeatInterval"
static let attachments = "attachments"
static let identifier = "identifier"
static let filePath = "filePath"
}
struct DateFormatStrings {
static let isoFormat = "yyyy-MM-dd'T'HH:mm:ss"
}
enum ScheduledNotificationRepeatFrequency : Int {
case daily
case weekly
}
enum RepeatInterval: Int {
case everyMinute
case hourly
case daily
case weekly
}
var channel: FlutterMethodChannel
var initialized = false
var defaultPresentAlert = false
var defaultPresentSound = false
var defaultPresentBadge = false
var launchPayload: String?
var launchingAppFromNotification = false
init(fromChannel channel: FlutterMethodChannel) {
self.channel = channel
}
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "dexterous.com/flutter/local_notifications", binaryMessenger: registrar.messenger)
let instance = FlutterLocalNotificationsPlugin.init(fromChannel: channel)
if #available(OSX 10.14, *) {
let center = UNUserNotificationCenter.current()
center.delegate = instance
} else {
let center = NSUserNotificationCenter.default
center.delegate = instance
}
registrar.addMethodCallDelegate(instance, channel: channel)
}
@available(OSX 10.14, *)
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
var options:UNNotificationPresentationOptions = []
let presentAlert = notification.request.content.userInfo[MethodCallArguments.presentAlert] as! Bool
let presentSound = notification.request.content.userInfo[MethodCallArguments.presentSound] as! Bool
let presentBadge = notification.request.content.userInfo[MethodCallArguments.presentBadge] as! Bool
if presentAlert {
options.insert(.alert)
}
if presentSound {
options.insert(.sound)
}
if presentBadge {
options.insert(.badge)
}
completionHandler(options)
}
@available(OSX 10.14, *)
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let payload = response.notification.request.content.userInfo[MethodCallArguments.payload] as? String
if(initialized) {
handleSelectNotification(payload: payload)
} else {
launchPayload = payload
launchingAppFromNotification = true
}
}
public func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
if(notification.activationType == .contentsClicked) {
handleSelectNotification(payload: notification.userInfo![MethodCallArguments.payload] as? String)
}
}
public func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "initialize":
initialize(call, result)
case "requestPermissions":
requestPermissions(call, result)
case "getNotificationAppLaunchDetails":
getNotificationAppLaunchDetails(result)
case "cancel":
cancel(call, result)
case "cancelAll":
cancelAll(result)
case "pendingNotificationRequests":
pendingNotificationRequests(result)
case "show":
show(call, result)
case "zonedSchedule":
zonedSchedule(call, result)
case "periodicallyShow":
periodicallyShow(call, result)
default:
result(FlutterMethodNotImplemented)
}
}
func initialize(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
let arguments = call.arguments as! Dictionary<String, AnyObject>
defaultPresentAlert = arguments[MethodCallArguments.defaultPresentAlert] as! Bool
defaultPresentSound = arguments[MethodCallArguments.defaultPresentSound] as! Bool
defaultPresentBadge = arguments[MethodCallArguments.defaultPresentBadge] as! Bool
if #available(OSX 10.14, *) {
let requestedAlertPermission = arguments[MethodCallArguments.requestAlertPermission] as! Bool
let requestedSoundPermission = arguments[MethodCallArguments.requestSoundPermission] as! Bool
let requestedBadgePermission = arguments[MethodCallArguments.requestBadgePermission] as! Bool
requestPermissionsImpl(soundPermission: requestedSoundPermission, alertPermission: requestedAlertPermission, badgePermission: requestedBadgePermission, result: result)
if(launchingAppFromNotification) {
handleSelectNotification(payload: launchPayload)
}
initialized = true
}
else {
result(true)
initialized = true
}
}
func requestPermissions(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let requestedAlertPermission = arguments[MethodCallArguments.alert] as! Bool
let requestedSoundPermission = arguments[MethodCallArguments.sound] as! Bool
let requestedBadgePermission = arguments[MethodCallArguments.badge] as! Bool
requestPermissionsImpl(soundPermission: requestedSoundPermission, alertPermission: requestedAlertPermission, badgePermission: requestedBadgePermission, result: result)
} else {
result(nil)
}
}
func getNotificationAppLaunchDetails(_ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
let appLaunchDetails : [String: Any?] = [MethodCallArguments.notificationLaunchedApp : launchingAppFromNotification, MethodCallArguments.payload: launchPayload]
result(appLaunchDetails)
} else {
result(nil)
}
}
func cancel(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
let center = UNUserNotificationCenter.current()
let idsToRemove = [String(call.arguments as! Int)]
center.removePendingNotificationRequests(withIdentifiers: idsToRemove)
center.removeDeliveredNotifications(withIdentifiers: idsToRemove)
result(nil)
}
else {
let id = String(call.arguments as! Int)
let center = NSUserNotificationCenter.default
for scheduledNotification in center.scheduledNotifications {
if (scheduledNotification.identifier == id) {
center.removeScheduledNotification(scheduledNotification)
break
}
}
let notification = NSUserNotification.init()
notification.identifier = id
center.removeDeliveredNotification(notification)
result(nil)
}
}
func cancelAll(_ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
center.removeAllDeliveredNotifications()
result(nil)
} else {
let center = NSUserNotificationCenter.default
for scheduledNotification in center.scheduledNotifications {
center.removeScheduledNotification(scheduledNotification)
}
center.removeAllDeliveredNotifications()
result(nil)
}
}
func pendingNotificationRequests(_ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
var requestDictionaries:[Dictionary<String, Any?>] = []
for request in requests {
requestDictionaries.append([MethodCallArguments.id:Int(request.identifier) as Any, MethodCallArguments.title: request.content.title, MethodCallArguments.body: request.content.body, MethodCallArguments.payload: request.content.userInfo[MethodCallArguments.payload]])
}
result(requestDictionaries)
}
} else {
var requestDictionaries:[Dictionary<String, Any?>] = []
let center = NSUserNotificationCenter.default
for scheduledNotification in center.scheduledNotifications {
requestDictionaries.append([MethodCallArguments.id:Int(scheduledNotification.identifier!) as Any, MethodCallArguments.title: scheduledNotification.title, MethodCallArguments.body: scheduledNotification.informativeText, MethodCallArguments.payload: scheduledNotification.userInfo![MethodCallArguments.payload]])
}
result(requestDictionaries)
}
}
func show(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
do {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let content = try buildUserNotificationContent(fromArguments: arguments)
let center = UNUserNotificationCenter.current()
let request = UNNotificationRequest(identifier: getIdentifier(fromArguments: arguments), content: content, trigger: nil)
center.add(request)
result(nil)
} catch {
result(buildFlutterError(forMethodCallName: call.method, withError: error))
}
} else {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let notification = buildNSUserNotification(fromArguments: arguments)
NSUserNotificationCenter.default.deliver(notification)
result(nil)
}
}
func zonedSchedule(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
do {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let content = try buildUserNotificationContent(fromArguments: arguments)
let trigger = buildUserNotificationCalendarTrigger(fromArguments: arguments)
let center = UNUserNotificationCenter.current()
let request = UNNotificationRequest(identifier: getIdentifier(fromArguments: arguments), content: content, trigger: trigger)
center.add(request)
result(nil)
} catch {
result(buildFlutterError(forMethodCallName: call.method, withError: error))
}
} else {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let notification = buildNSUserNotification(fromArguments: arguments)
let scheduledDateTime = arguments[MethodCallArguments.scheduledDateTime] as! String
let timeZoneName = arguments[MethodCallArguments.timeZoneName] as! String
let timeZone = TimeZone.init(identifier: timeZoneName)
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = DateFormatStrings.isoFormat
let date = dateFormatter.date(from: scheduledDateTime)!
notification.deliveryDate = date
notification.deliveryTimeZone = timeZone
if let rawRepeatFrequency = arguments[MethodCallArguments.scheduledNotificationRepeatFrequency] as? Int {
let repeatFrequency = ScheduledNotificationRepeatFrequency.init(rawValue: rawRepeatFrequency)!
switch repeatFrequency {
case .daily:
notification.deliveryRepeatInterval = DateComponents.init(day: 1)
case .weekly:
notification.deliveryRepeatInterval = DateComponents.init(weekOfYear: 1)
}
}
NSUserNotificationCenter.default.scheduleNotification(notification)
result(nil)
}
}
func periodicallyShow(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
if #available(OSX 10.14, *) {
do {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let content = try buildUserNotificationContent(fromArguments: arguments)
let trigger = buildUserNotificationTimeIntervalTrigger(fromArguments: arguments)
let center = UNUserNotificationCenter.current()
let request = UNNotificationRequest(identifier: getIdentifier(fromArguments: arguments), content: content, trigger: trigger)
center.add(request)
result(nil)
} catch {
result(buildFlutterError(forMethodCallName: call.method, withError: error))
}
} else {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let notification = buildNSUserNotification(fromArguments: arguments)
let rawRepeatInterval = arguments[MethodCallArguments.repeatInterval] as! Int
let repeatInterval = RepeatInterval.init(rawValue: rawRepeatInterval)!
switch repeatInterval {
case .everyMinute:
notification.deliveryDate = Date.init(timeIntervalSinceNow: 60)
notification.deliveryRepeatInterval = DateComponents.init(minute: 1)
case .hourly:
notification.deliveryDate = Date.init(timeIntervalSinceNow: 60 * 60)
notification.deliveryRepeatInterval = DateComponents.init(hour: 1)
case .daily:
notification.deliveryDate = Date.init(timeIntervalSinceNow: 60 * 60 * 24)
notification.deliveryRepeatInterval = DateComponents.init(day: 1)
case .weekly:
notification.deliveryDate = Date.init(timeIntervalSinceNow: 60 * 60 * 24 * 7)
notification.deliveryRepeatInterval = DateComponents.init(weekOfYear: 1)
}
NSUserNotificationCenter.default.scheduleNotification(notification)
result(nil)
}
}
@available(OSX 10.14, *)
func buildUserNotificationContent(fromArguments arguments: Dictionary<String, AnyObject>) throws -> UNNotificationContent {
let content = UNMutableNotificationContent()
if let title = arguments[MethodCallArguments.title] as? String {
content.title = title
}
if let subtitle = arguments[MethodCallArguments.subtitle] as? String {
content.subtitle = subtitle
}
if let body = arguments[MethodCallArguments.body] as? String {
content.body = body
}
var presentSound = defaultPresentSound
var presentBadge = defaultPresentBadge
var presentAlert = defaultPresentAlert
if let platformSpecifics = arguments[MethodCallArguments.platformSpecifics] as? Dictionary<String, AnyObject> {
if let sound = platformSpecifics[MethodCallArguments.sound] as? String {
content.sound = UNNotificationSound.init(named: UNNotificationSoundName.init(sound))
}
if let badgeNumber = platformSpecifics[MethodCallArguments.badgeNumber] as? NSNumber {
content.badge = badgeNumber
}
if !(platformSpecifics[MethodCallArguments.presentSound] is NSNull) && platformSpecifics[MethodCallArguments.presentSound] != nil {
presentSound = platformSpecifics[MethodCallArguments.presentSound] as! Bool
}
if !(platformSpecifics[MethodCallArguments.presentAlert] is NSNull) && platformSpecifics[MethodCallArguments.presentAlert] != nil {
presentAlert = platformSpecifics[MethodCallArguments.presentAlert] as! Bool
}
if !(platformSpecifics[MethodCallArguments.presentBadge] is NSNull) && platformSpecifics[MethodCallArguments.presentBadge] != nil {
presentBadge = platformSpecifics[MethodCallArguments.presentBadge] as! Bool
}
if let attachments = platformSpecifics[MethodCallArguments.attachments] as? [Dictionary<String, AnyObject>] {
content.attachments = []
for attachment in attachments {
let identifier = attachment[MethodCallArguments.identifier] as! String
let filePath = attachment[MethodCallArguments.filePath] as! String
let notificationAttachment = try UNNotificationAttachment.init(identifier: identifier, url: URL.init(fileURLWithPath: filePath))
content.attachments.append(notificationAttachment)
}
}
}
content.userInfo = [MethodCallArguments.payload: arguments[MethodCallArguments.payload] as Any, MethodCallArguments.presentSound: presentSound, MethodCallArguments.presentBadge: presentBadge, MethodCallArguments.presentAlert: presentAlert]
if presentSound && content.sound == nil {
content.sound = UNNotificationSound.default
}
return content
}
func buildFlutterError(forMethodCallName methodCallName: String, withError error: Error) -> FlutterError {
return FlutterError.init(code: "\(methodCallName)_error", message: error.localizedDescription, details: "\(error)")
}
@available(OSX 10.14, *)
func buildUserNotificationCalendarTrigger(fromArguments arguments:Dictionary<String, AnyObject>) -> UNCalendarNotificationTrigger {
let scheduledDateTime = arguments[MethodCallArguments.scheduledDateTime] as! String
let timeZoneName = arguments[MethodCallArguments.timeZoneName] as! String
let timeZone = TimeZone.init(identifier: timeZoneName)
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = DateFormatStrings.isoFormat
dateFormatter.timeZone = timeZone
let date = dateFormatter.date(from: scheduledDateTime)!
var calendar = Calendar.current
calendar.timeZone = timeZone!
if let rawRepeatFrequency = arguments[MethodCallArguments.scheduledNotificationRepeatFrequency] as? Int {
let repeatFrequency = ScheduledNotificationRepeatFrequency.init(rawValue: rawRepeatFrequency)!
switch repeatFrequency {
case .daily:
let dateComponents = calendar.dateComponents([.day, .hour, .minute, .second, .timeZone], from: date)
return UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: true)
case .weekly:
let dateComponents = calendar.dateComponents([ .weekday,.hour, .minute, .second, .timeZone], from: date)
return UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: true)
}
}
let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .timeZone], from: date)
return UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: false)
}
@available(OSX 10.14, *)
func buildUserNotificationTimeIntervalTrigger(fromArguments arguments:Dictionary<String, AnyObject>) -> UNTimeIntervalNotificationTrigger {
let rawRepeatInterval = arguments[MethodCallArguments.repeatInterval] as! Int
let repeatInterval = RepeatInterval.init(rawValue: rawRepeatInterval)!
switch repeatInterval {
case .everyMinute:
return UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)
case .hourly:
return UNTimeIntervalNotificationTrigger.init(timeInterval: 60 * 60, repeats: true)
case .daily:
return UNTimeIntervalNotificationTrigger.init(timeInterval: 60 * 60 * 24, repeats: true)
case .weekly:
return UNTimeIntervalNotificationTrigger.init(timeInterval: 60 * 60 * 24 * 7, repeats: true)
}
}
@available(OSX 10.14, *)
func requestPermissionsImpl(soundPermission: Bool, alertPermission: Bool, badgePermission: Bool, result: @escaping FlutterResult) {
var options: UNAuthorizationOptions = []
if(soundPermission) {
options.insert(.sound)
}
if(alertPermission) {
options.insert(.alert)
}
if(badgePermission) {
options.insert(.badge)
}
UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, _) in
result(granted)
}
}
func buildNSUserNotification(fromArguments arguments: Dictionary<String, AnyObject>) -> NSUserNotification {
let notification = NSUserNotification.init()
notification.identifier = getIdentifier(fromArguments: arguments)
if let title = arguments[MethodCallArguments.title] as? String {
notification.title = title
}
if let subtitle = arguments[MethodCallArguments.subtitle] as? String {
notification.subtitle = subtitle
}
if let body = arguments[MethodCallArguments.body] as? String {
notification.informativeText = body
}
var presentSound = defaultPresentSound
if let platformSpecifics = arguments[MethodCallArguments.platformSpecifics] as? Dictionary<String, AnyObject> {
if let sound = platformSpecifics[MethodCallArguments.sound] as? String {
notification.soundName = sound
}
if !(platformSpecifics[MethodCallArguments.presentSound] is NSNull) && platformSpecifics[MethodCallArguments.presentSound] != nil {
presentSound = platformSpecifics[MethodCallArguments.presentSound] as! Bool
}
}
notification.userInfo = [MethodCallArguments.payload: arguments[MethodCallArguments.payload] as Any]
if presentSound && notification.soundName == nil {
notification.soundName = NSUserNotificationDefaultSoundName
}
return notification
}
func getIdentifier(fromArguments arguments: Dictionary<String, AnyObject>) -> String {
return String(arguments[MethodCallArguments.id] as! Int)
}
func handleSelectNotification(payload: String?) {
channel.invokeMethod("selectNotification", arguments: payload)
}
}
| 49.983673 | 326 | 0.666993 |
6a3a1f86f5b2173514c25587959cdd63e78e8e12 | 2,375 | //
// RemindersController.swift
// remindersPackageDescription
//
// Created by Vinh Nguyen on 30/11/17.
//
import Vapor
import FluentProvider
struct RemindersController {
// MARK: - Router
func addRoutes(to drop: Droplet) {
let reminderGroup = drop.grouped("api", "reminders")
// GET
// NOTE: by not specifying a path for this route, it will simple be registered to the root path of the route group
reminderGroup.get(handler: allReminders)
reminderGroup.get(Reminder.parameter, handler: getReminder)
reminderGroup.get(Reminder.parameter, "user", handler: getUserByReminder)
reminderGroup.get(Reminder.parameter, "categories", handler: getRemindersCategories)
// POST
reminderGroup.post("create", handler: createReminder)
}
// MARK: - Public
func createReminder(_ request: Request) throws -> ResponseRepresentable {
guard let json = request.json else {
throw Abort.badRequest
}
let reminder = try Reminder(json: json) // create new reminder instance
try reminder.save() // save to DB
if let categories = json[Category.Keypath.categories.rawValue]?.array {
for catJSON in categories {
guard let catName = catJSON.string else {
throw Abort.badRequest
}
try Category.addCategory(catName, to: reminder)
}
}
return reminder
}
func allReminders(_ request: Request) throws -> ResponseRepresentable {
let list = try Reminder.all()
return try list.makeJSON()
}
func getReminder(_ request: Request) throws -> ResponseRepresentable {
return try request.parameters.next(Reminder.self)
}
func getUserByReminder(_ request: Request) throws -> ResponseRepresentable {
let reminder = try request.parameters.next(Reminder.self)
guard let user = try reminder.user.get() else {
throw Abort.notFound
}
return user
}
func getRemindersCategories(_ request: Request) throws -> ResponseRepresentable {
let reminder = try request.parameters.next(Reminder.self)
return try reminder.categories.all().makeJSON()
}
}
| 31.666667 | 122 | 0.618947 |
f952ad9bfa36b914702f2870e937933c8dbb1c79 | 2,544 | //
// CaseIterableRemainingTests.swift
// AdditionalSwift
//
// Created by Stephen Martinez on 6/8/21.
// Copyright © 2021 Stephen L. Martinez. All rights reserved.
//
import XCTest
@testable import AdditionalSwift
final class CaseIterableRemainingTests: XCTestCase {
enum IterableEnum: String, CaseIterable, Equatable {
case one
case two
case three
case four
case five
}
func test_RemainingCasesShouldProduceAllWhenFirstIsUsed() {
// Arrange
let expOutput: [IterableEnum] = [
.one,
.two,
.three,
.four,
.five
]
// Act
let output = IterableEnum.one.remainingCases
// Assert
XCTAssertEqual(expOutput, output, "remaining cases should have produced all cases")
}
func test_RemainingCasesShouldProduceOnlyOneCaseWhenLastUsed() {
// Arrange
let expOutput: [IterableEnum] = [.five]
// Act
let output = IterableEnum.five.remainingCases
// Assert
XCTAssertEqual(expOutput, output, "remaining cases should have produced the 'five' case")
}
func test_RemainingCasesShouldIncludeTheCaseItsCalledOn() {
// Arrange
let expOutput: [IterableEnum] = [
.three,
.four,
.five
]
let iterableCase = IterableEnum.three
// Act
let output = iterableCase.remainingCases
// Assert
XCTAssertEqual(expOutput, output, "remaining cases should have produced three four and five")
XCTAssertTrue(expOutput.contains(iterableCase), "the case 'three' should be contained in the output")
}
func test_NextCaseShouldUseTheNextAvailableCase() {
// Arrange
let initialContent: [IterableEnum] = [
.one,
.two,
.three,
.four
]
let expOutput: [IterableEnum] = [
.two,
.three,
.four,
.five
]
// Act
let output = initialContent.compactMap(\.nextCase)
// Assert
XCTAssertEqual(expOutput, output, "next case should have produced the next available case")
}
func test_NextCaseShouldBeNilIfNoneAreLeft() {
// Arrange
let expOutput: IterableEnum? = .none
// Act
let output = IterableEnum.five.nextCase
// Assert
XCTAssertEqual(expOutput, output, "next case should be nil when none are left")
}
}
| 24.941176 | 109 | 0.590016 |
64dfda3524d070333e3d9b9006b4c20693c5112a | 1,532 | import Foundation
/** :nodoc: */
@objcMembers
open class PXPluginNavigationHandler: NSObject {
private var checkout: MercadoPagoCheckout?
public init(withCheckout: MercadoPagoCheckout) {
self.checkout = withCheckout
}
open func showFailure(message: String, errorDetails: String, retryButtonCallback: (() -> Void)?) {
MercadoPagoCheckoutViewModel.error = MPSDKError(message: message, errorDetail: errorDetails, retry: retryButtonCallback != nil)
checkout?.viewModel.errorCallback = retryButtonCallback
checkout?.executeNextStep()
}
open func next() {
checkout?.executeNextStep()
}
open func nextAndRemoveCurrentScreenFromStack() {
guard let currentViewController = self.checkout?.viewModel.pxNavigationHandler.navigationController.viewControllers.last else {
checkout?.executeNextStep()
return
}
checkout?.executeNextStep()
if let indexOfLastViewController = self.checkout?.viewModel.pxNavigationHandler.navigationController.viewControllers.index(of: currentViewController) {
self.checkout?.viewModel.pxNavigationHandler.navigationController.viewControllers.remove(at: indexOfLastViewController)
}
}
open func cancel() {
checkout?.cancelCheckout()
}
open func showLoading() {
checkout?.viewModel.pxNavigationHandler.presentLoading()
}
open func hideLoading() {
checkout?.viewModel.pxNavigationHandler.dismissLoading()
}
}
| 31.916667 | 159 | 0.708225 |
ddabe13d21bd33b80f6ce1a6a0c2d73e2aa3cf83 | 246 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a{
let t: AnyObject)
let >
func d{
struct c<T where k:T{
var d {
let:e
| 20.5 | 87 | 0.735772 |
18bc4a58f417fe126e55c6d794ef87c2671869a3 | 2,333 | //
// Project.swift
// StrideLib
//
// Created by pmacro on 04/03/2019.
//
import Foundation
import PromiseKit
import SPMClient
public enum ProjectError: Error {
case unsupportedProject
case invalidConfiguration(message: String)
}
public class Project: Codable, Equatable, Hashable {
public static func == (lhs: Project, rhs: Project) -> Bool {
return lhs.url == rhs.url
}
public func hash(into hasher: inout Hasher) {
hasher.combine(url)
}
public var name: String
public var url: URL
public var primaryLanguage: String
// Can this project be executed or is it only a library.
public var hasExecutable: Bool
public init(name: String,
url: URL,
primaryLanguage: String,
hasExecutable: Bool) {
self.name = name
self.url = url
self.primaryLanguage = primaryLanguage
self.hasExecutable = hasExecutable
}
public static func from(url: URL) -> Promise<Project> {
return Promise<Project> { resolver in
if url.pathExtension.lowercased() == "swift" {
let languageConfig = LanguageConfiguration
.for(languageNamed: "swift")
let compilerHome = languageConfig?.compilerHomeDirectory
let client = SPMClient(projectDirectory: url.deletingLastPathComponent(),
swiftHomePath: compilerHome)
guard let package = client?.generatePackageDescription() else {
let message = "Unable to read package at: \(url.path)"
resolver.reject(ProjectError
.invalidConfiguration(message: message))
return
}
resolver.fulfill(SwiftProject(from: package,
client: client!,
at: url))
}
resolver.reject(ProjectError.unsupportedProject)
}
}
}
public class SwiftProject: Project {
public var client: SPMClient?
public init(from package: Package, client: SPMClient, at url: URL) {
self.client = client
super.init(name: package.name,
url: url,
primaryLanguage: "swift",
hasExecutable: package.hasExecutable)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
| 26.816092 | 81 | 0.612087 |
7af0d19f1ac7131e51e220194124052e9fd0395a | 8,432 | //
// ServerTableViewController.swift
// Spice
//
// Created by Gianni on 13/12/2019.
// Copyright © 2019 Rodepanda. All rights reserved.
//
import UIKit
struct Server: Codable {
var name: String
var host: String
var port: UInt16
var password: String?
}
class ServerTableViewController: UITableViewController {
var servers: [Server] = [Server]()
var client: ConnectionController?
@IBOutlet weak var addServerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
loadData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
@IBAction func addServerButtonTapped(_ sender: Any) {
let editServerNavigationController = self.storyboard?.instantiateViewController(withIdentifier: "EditServerNavigationController") as! UINavigationController
let serverEditViewController = editServerNavigationController.topViewController as! EditServerViewController
serverEditViewController.delegate = self
present(editServerNavigationController, animated: true, completion: nil)
}
func persistData(){
let propertyListEncoder = PropertyListEncoder()
if let encodedServers = try? propertyListEncoder.encode(servers) {
savePlist(fileName: "servers", data: encodedServers)
}
}
func loadData(){
guard let serverData = getPlist(fileName: "servers") else {
return
}
let propertyListDecoder = PropertyListDecoder()
if let decodedData = try? propertyListDecoder.decode([Server].self, from: serverData) {
servers = decodedData
}
}
//
//
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// if(segue.identifier == "editServer"){
// let indexPath = tableView.indexPathForSelectedRow!
// let server = servers[indexPath.row]
// let navController = segue.destination as! UINavigationController
// let editServerViewController = navController.topViewController as! EditServerViewController
// editServerViewController.server = server
// } else if (segue.identifier == "connectToServer") {
// let dest = segue.destination as UIViewController
// self.client!.setUIViewController(uiViewController: dest)
// }
// }
//
// @IBAction
// func unwindToServerTableView(segue: UIStoryboardSegue){
// if segue.identifier == "saveUnwind",
// let sourceViewController = segue.source as? EditServerViewController,
// let server = sourceViewController.server {
//
// if let selectedIndexPath = tableView.indexPathForSelectedRow {
// servers[selectedIndexPath.row] = server
// tableView.reloadRows(at: [selectedIndexPath], with: .none)
// } else {
// let newIndexPath = IndexPath(row: servers.count, section: 0)
// servers.append(server)
// tableView.insertRows(at: [newIndexPath], with: .automatic)
// }
// persistData()
//
// }
// }
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
// return servers.count
return servers.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(self.isEditing){
//self.performSegue(withIdentifier: "editServer", sender: self)
let server = servers[indexPath.row]
let editServerNavigationController = self.storyboard?.instantiateViewController(withIdentifier: "EditServerNavigationController") as! UINavigationController
let serverEditViewController = editServerNavigationController.topViewController as! EditServerViewController
serverEditViewController.delegate = self
serverEditViewController.server = server
present(editServerNavigationController, animated: true, completion: nil)
} else {
showConnectionDialogOverlay(title: "Connecting...")
let server = servers[indexPath.row]
client = ConnectionController(uiViewController: self, host: server.host, port: server.port, password: server.password)
tableView.deselectRow(at: indexPath, animated: true)
self.client!.connect()
}
}
override func connectingSuccess() {
dismiss(animated: true, completion: {
//self.performSegue(withIdentifier: "connectToServer", sender: self)
let mainTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "MainTabBarController") as! TabBarViewController
self.client!.setUIViewController(uiViewController: mainTabBarController)
self.present(mainTabBarController, animated: true, completion: nil)
})
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "serverCell", for: indexPath)
let server = servers[indexPath.row]
cell.textLabel?.text = server.name
cell.detailTextLabel?.text = server.host + ":" + String(server.port)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
servers.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
persistData()
}
}
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let movedServer = servers.remove(at: fromIndexPath.row)
servers.insert(movedServer, at: to.row)
tableView.reloadData()
persistData()
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
override func connectingFailed() {
DispatchQueue.main.async {
self.dismiss(animated: true, completion: self.showNoConnectionError)
}
}
private func showNoConnectionError(){
let alert = UIAlertController(title: "Error", message: "Could not connect to server", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
extension ServerTableViewController: EditServerViewControllerDelegate{
func saveEditedServer(server: Server) {
if let selectedIndexPath = tableView.indexPathForSelectedRow{
servers[selectedIndexPath.row] = server
tableView.reloadRows(at: [selectedIndexPath], with: .none)
tableView.deselectRow(at: selectedIndexPath, animated: true)
}
persistData()
}
func saveNewServer(server: Server) {
let newIndexPath = IndexPath(row: servers.count, section: 0)
servers.append(server)
tableView.insertRows(at: [newIndexPath], with: .automatic)
persistData()
}
}
| 38.153846 | 168 | 0.659393 |
16868ef59803e8dc0fdaa9edd10f8b9fcf49d0b0 | 540 | //
// AppDelegate.swift
// VIPERS-Converter
//
// Created by Jan Bartel on 04/17/2016.
// Copyright (c) 2016 Jan Bartel. 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
}
}
| 20 | 144 | 0.687037 |
6a86486c42d35a784a4c444d5dfba3dc69ce3da5 | 5,759 | //
// ExtractionResourcesTests.swift
// Gini Switch SDK
//
// Created by Gini GmbH on 08.06.17.
// Copyright © 2017 Gini GmbH. All rights reserved.
//
import XCTest
@testable import GiniSwitchSDK
final class ExtractionResourcesTests: XCTestCase {
let token = "testToken"
var service = ExtractionResources()
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSettingToken() {
service.token = token
XCTAssertEqual(service.token, token, "ExtractionsService should have a token property")
}
func testInitializingWithToken() {
service = ExtractionResources(token: token)
XCTAssertNotNil(service, "ExtractionsService should have an initializer taking a token as parameter")
}
func testCreatingExtractionOrder() {
service.token = token
let orderResource = service.createExtractionOrder
XCTAssertEqual(orderResource.url, URL(string: "\(service.baseUrl)/extractionOrders"), "The create extraction order request URL doesn't match")
XCTAssertEqual(orderResource.method, .POST, "The create extraction order request method doesn't match")
XCTAssertEqual(String(data: orderResource.body!, encoding: .utf8), "{\n\n}", "The extraction order request should have an empty body")
XCTAssertEqual(orderResource.headers["Authorization"], "Bearer \(token)", "The extraction order request should have a bearer authentication header")
}
func testAddingPage() {
service.token = token
let imageData = testImageData()
let testOrderId = "testId"
let testOrder = "\(service.baseUrl)/extractionOrders/\(testOrderId)"
let pageResource = service.addPage(imageData: imageData, toOrder: testOrder)
XCTAssertEqual(pageResource.url, URL(string:testOrder)!.appendingPathComponent("pages"), "The add page request URL doesn't match")
XCTAssertEqual(pageResource.method, .POST, "The add page request method doesn't match")
XCTAssertEqual(pageResource.body, imageData, "The add page request should have the image data as body")
XCTAssertEqual(pageResource.headers["Authorization"], "Bearer \(token)", "The add page request should have a bearer authentication header")
XCTAssertEqual(pageResource.headers["Content-Type"], "image/jpeg", "The add page request should have a content type header")
}
func testOrderStatus() {
service.token = token
let testOrderId = "testId"
let testOrder = "https://switch.gini.net/extractionOrders/\(testOrderId)/pages"
let extractionsResource = service.statusFor(orderUrl:testOrder)
XCTAssertEqual(extractionsResource.url, URL(string: testOrder), "The extractions status request URL doesn't match")
XCTAssertEqual(extractionsResource.method, .GET, "The extractions status request method doesn't match")
XCTAssertNil(extractionsResource.body, "The extractions status request shouldn't have a body")
XCTAssertEqual(extractionsResource.headers["Authorization"], "Bearer \(token)", "The extractions status request should have a bearer authentication header")
}
func testDeletePage() {
service.token = token
let testOrderId = "testId"
let testPage = "myFirstPage"
let testPageUrl = "https://switch.gini.net/extractionOrders/\(testOrderId)/pages/\(testPage)"
let deleteResource = service.deletePageWith(id: testPageUrl, orderUrl:"")
XCTAssertEqual(deleteResource.url, URL(string: testPageUrl), "The delete page request URL doesn't match")
XCTAssertEqual(deleteResource.method, .DELETE, "The delete page request method doesn't match")
XCTAssertNil(deleteResource.body, "The delete page request shouldn't have a body")
XCTAssertEqual(deleteResource.headers["Authorization"], "Bearer \(token)", "The delete page request should have a bearer authentication header")
}
func testReplacePage() {
service.token = token
let imageData = testImageData()
let testOrderId = "testId"
let testOrder = "https://switch.gini.net/extractionOrders/\(testOrderId)/pages"
let testPage = "myFirstPage"
let replaceResource = service.replacePageWith(id: testPage, orderUrl: testOrder, imageData: imageData)
XCTAssertEqual(replaceResource.url, URL(string: testPage), "The delete page request URL doesn't match")
XCTAssertEqual(replaceResource.method, .PUT, "The delete page request method doesn't match")
XCTAssertEqual(replaceResource.body, imageData, "The replace page request should have the image data as body")
XCTAssertEqual(replaceResource.headers["Authorization"], "Bearer \(token)", "The delete page request should have a bearer authentication header")
}
func testExtractionsStatus() {
service.token = token
let testOrderId = "testId"
let testOrder = "https://switch.gini.net/extractionOrders/\(testOrderId)"
let deleteResource = service.extractionsFor(orderUrl: testOrder)
XCTAssertEqual(deleteResource.url, URL(string: "\(testOrder)/extractions"), "The delete page request URL doesn't match")
XCTAssertEqual(deleteResource.method, .GET, "The delete page request method doesn't match")
XCTAssertNil(deleteResource.body, "The delete page request shouldn't have a body")
XCTAssertEqual(deleteResource.headers["Authorization"], "Bearer \(token)", "The delete page request should have a bearer authentication header")
}
}
| 53.82243 | 164 | 0.706199 |
1ad3b0bd3bff41c703b130a49cfee883fd1c3b5b | 893 | //
// JXNamespace.swift
// Lantern
//
// Created by JiongXing on 2018/10/14.
// Copyright © 2019 JiongXing. All rights reserved.
//
import Foundation
/// 类型协议
public protocol JXTypeWrapperProtocol {
associatedtype JXWrappedType
var jxWrappedValue: JXWrappedType { get }
init(value: JXWrappedType)
}
public struct JXNamespaceWrapper<T>: JXTypeWrapperProtocol {
public let jxWrappedValue: T
public init(value: T) {
self.jxWrappedValue = value
}
}
/// 命名空间协议
public protocol JXNamespaceWrappable {
associatedtype JXWrappedType
var jx: JXWrappedType { get }
static var jx: JXWrappedType.Type { get }
}
extension JXNamespaceWrappable {
public var jx: JXNamespaceWrapper<Self> {
return JXNamespaceWrapper(value: self)
}
public static var jx: JXNamespaceWrapper<Self>.Type {
return JXNamespaceWrapper.self
}
}
| 21.780488 | 60 | 0.702128 |
9053ba1619ee09b78975cc519406d550491b4809 | 2,852 | //
// ECNetworkingHelper.swift
// EasyCheckout
//
// Created by parry on 8/3/16.
// Copyright © 2016 MCP. All rights reserved.
//
import Foundation
final class ECNetworkingHelper: NSObject {
static let sharedInstance = ECNetworkingHelper()
var keptItemIDs = [String]()
var keptItemsArray = [ECItem]()
func fetchCurrentFix(completionHandler: (data: [ECItem], error: NSError?) -> Void) -> Void {
let newURL = NSURL(string:"https://fake-mobile-backend.herokuapp.com/api/current_fix")
if let requestUrl = newURL {
let getRequest = ECRequest(requestMethod: "GET", url: requestUrl, params: [:])
getRequest.performRequestWithHandler(
{ (success: Bool, object: AnyObject?) -> Void in
var objectArray = [ECItem]()
if success {
if let itemArray = object?["shipment_items"] as? [[String:AnyObject]]{
for dic in itemArray {
let newResponseObject = ECItem(dictionary: dic)
objectArray.append(newResponseObject)
}
if itemArray.isEmpty == false {
completionHandler(data: objectArray, error: nil)
}
}else {
print("error retrieving fix")
}
}else {
print("error performing request")
NSNotificationCenter.defaultCenter().postNotificationName("badRequest", object: nil)
}
})
}
}
func updateCurrentFix(keptItemsArray: [String], completionHandler: (data: ECInvoice, error: NSError?) -> Void) -> Void {
let newURL = NSURL(string:"https://fake-mobile-backend.herokuapp.com/api/current_fix")
let params = ["keep" : keptItemsArray]
if let requestUrl = newURL {
let putRequest = ECRequest(requestMethod: "PUT", url: requestUrl, params: params)
putRequest.performRequestWithHandler(
{ (success: Bool, object: AnyObject?) -> Void in
var newResponseObject: ECInvoice
if success {
if let dic = object as? [String:AnyObject]{
newResponseObject = ECInvoice(dictionary: dic)
if dic.isEmpty == false {
completionHandler(data: newResponseObject, error: nil)
}
}else {
print("error retrieving fix")
}
}else {
print("error performing request")
// NSNotificationCenter.defaultCenter().postNotificationName("badRequest", object: nil)
}
})
}
}
}
| 27.423077 | 120 | 0.526999 |
224440234625bf862b8dc2cfc76b8287cc5b35f5 | 1,055 | //
// SelectableSegmentInteractor+Filter.swift
// InstantSearchCore
//
// Created by Vladislav Fitc on 13/05/2019.
// Copyright © 2019 Algolia. All rights reserved.
//
// swiftlint:disable type_name
import Foundation
import AlgoliaSearchClient
public struct SelectableFilterInteractorSearcherConnection<Filter: FilterType>: Connection {
public let interactor: SelectableSegmentInteractor<Int, Filter>
public let searcher: SingleIndexSearcher
public let attribute: Attribute
public func connect() {
searcher.indexQueryState.query.updateQueryFacets(with: attribute)
}
public func disconnect() {
}
}
public extension SelectableSegmentInteractor where SegmentKey == Int, Segment: FilterType {
@discardableResult func connectSearcher(_ searcher: SingleIndexSearcher, attribute: Attribute) -> SelectableFilterInteractorSearcherConnection<Segment> {
let connection = SelectableFilterInteractorSearcherConnection(interactor: self, searcher: searcher, attribute: attribute)
connection.connect()
return connection
}
}
| 28.513514 | 155 | 0.789573 |
5631a8c6736c93197245c6b9d08fad94d95353c7 | 2,682 | /**
* Copyright (c) 2017 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 WatchKit
import Foundation
import WatchConnectivity
class MovieRatingController: WKInterfaceController {
var movie: Movie!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let movie = context as? Movie {
self.movie = movie
setTitle(movie.title)
}
}
@IBAction func oneStarWasTapped() {
rateMovieWithRating("★☆☆☆☆")
}
@IBAction func twoStarWasTapped() {
rateMovieWithRating("★★☆☆☆")
}
@IBAction func threeStarWasTapped() {
rateMovieWithRating("★★★☆☆")
}
@IBAction func fourStarWasTapped() {
rateMovieWithRating("★★★★☆")
}
@IBAction func fiveStarWasTapped() {
rateMovieWithRating("★★★★★")
}
private func rateMovieWithRating(_ rating: String) {
TicketOffice.sharedInstance.rateMovie(movie.id, rating: rating)
sendRatingToPhone(rating)
pop()
}
}
// MARK: - Watch Connectivity
extension MovieRatingController {
func sendRatingToPhone(_ rating: String) {
// TODO: Update to send movie ratings to phone
}
}
| 32.707317 | 81 | 0.737136 |
e878988a78a26b73472de338dabf41d51613fa39 | 9,150 | import Foundation
import XCTest
@testable import LicensePlistCore
class PlistInfoTests: XCTestCase {
override class func setUp() {
super.setUp()
TestUtil.setGitHubToken()
}
private let options = Options(outputPath: URL(fileURLWithPath: "test_result_dir"),
cartfilePath: URL(fileURLWithPath: "test_result_dir"),
podsPath: URL(fileURLWithPath: "test_result_dir"),
packagePath: URL(fileURLWithPath: "test_result_dir"),
xcodeprojPath: URL(fileURLWithPath: "test_result_dir"),
prefix: Consts.prefix,
gitHubToken: nil,
htmlPath: nil,
markdownPath: nil,
config: Config(githubs: [GitHub(name: "facebook-ios-sdk",
nameSpecified: nil,
owner: "facebook",
version: "sdk-version-4.21.0"),
GitHub(name: "exclude",
nameSpecified: nil,
owner: "owner",
version: nil)],
manuals: [],
excludes: ["exclude"],
renames: ["Himotoki": "Himotoki2"]))
func testLoadCocoaPodsLicense() {
var target = PlistInfo(options: options)
XCTAssertNil(target.cocoaPodsLicenses)
let path = "https://raw.githubusercontent.com/mono0926/LicensePlist/master/Tests/LicensePlistTests/Resources/acknowledgements.plist"
let content = try! String(contentsOf: URL(string: path)!)
target.loadCocoaPodsLicense(acknowledgements: [content])
let licenses = target.cocoaPodsLicenses!
XCTAssertEqual(licenses.count, 11)
let licenseFirst = licenses.first!
XCTAssertEqual(licenseFirst.library, CocoaPods(name: "Firebase", nameSpecified: nil, version: nil))
XCTAssertEqual(licenseFirst.body, "Copyright 2017 Google")
}
func testLoadCocoaPodsLicense_empty() {
var target = PlistInfo(options: options)
XCTAssertNil(target.cocoaPodsLicenses)
target.loadCocoaPodsLicense(acknowledgements: [])
XCTAssertEqual(target.cocoaPodsLicenses!, [])
}
func testLoadGitHubLibraries() {
var target = PlistInfo(options: options)
XCTAssertNil(target.githubLibraries)
target.loadGitHubLibraries(cartfile: "github \"ikesyo/Himotoki\" \"3.0.1\"")
let libraries = target.githubLibraries!
XCTAssertEqual(libraries.count, 2)
let lib1 = libraries[0]
XCTAssertEqual(lib1, GitHub(name: "facebook-ios-sdk", nameSpecified: nil, owner: "facebook", version: "sdk-version-4.21.0"))
let lib2 = libraries[1]
XCTAssertEqual(lib2, GitHub(name: "Himotoki", nameSpecified: "Himotoki2", owner: "ikesyo", version: "3.0.1"))
}
func testLoadGitHubLibraries_empty() {
var target = PlistInfo(options: options)
XCTAssertNil(target.githubLibraries)
target.loadGitHubLibraries(cartfile: nil)
let libraries = target.githubLibraries!
XCTAssertEqual(libraries.count, 1)
let lib1 = libraries[0]
XCTAssertEqual(lib1, GitHub(name: "facebook-ios-sdk", nameSpecified: nil, owner: "facebook", version: "sdk-version-4.21.0"))
}
func testCompareWithLatestSummary() {
var target = PlistInfo(options: options)
target.cocoaPodsLicenses = []
target.manualLicenses = []
target.githubLibraries = []
XCTAssertNil(target.summary)
XCTAssertNil(target.summaryPath)
target.compareWithLatestSummary()
XCTAssertEqual(target.summary,
"add-version-numbers: false\n\nLicensePlist Version: 2.12.0")
XCTAssertNotNil(target.summaryPath)
}
func testDownloadGitHubLicenses() {
var target = PlistInfo(options: options)
let github = GitHub(name: "LicensePlist", nameSpecified: nil, owner: "mono0926", version: nil)
target.githubLibraries = [github]
XCTAssertNil(target.githubLicenses)
target.downloadGitHubLicenses()
XCTAssertEqual(target.githubLicenses!.count, 1)
let license = target.githubLicenses!.first!
XCTAssertEqual(license.library, github)
XCTAssertNotNil(license.body)
XCTAssertNotNil(license.githubResponse)
}
func testCollectLicenseInfos() {
var target = PlistInfo(options: options)
let github = GitHub(name: "LicensePlist", nameSpecified: nil, owner: "mono0926", version: nil)
let githubLicense = GitHubLicense(library: github,
body: "body",
githubResponse: LicenseResponse(content: "",
encoding: "",
kind: LicenseKindResponse(name: "name",
spdxId: nil)))
target.cocoaPodsLicenses = []
let manual = Manual(name: "FooBar", source: "https://foo.bar", nameSpecified: nil, version: nil)
let manualLicense = ManualLicense(library: manual,
body: "body")
target.manualLicenses = [manualLicense]
target.githubLicenses = [githubLicense]
XCTAssertNil(target.licenses)
target.collectLicenseInfos()
let licenses = target.licenses!
XCTAssertEqual(licenses.count, 2)
let license = licenses.last!
XCTAssertEqual(license.name, "LicensePlist")
}
// MEMO: No result assertions
func testOutputPlist() {
var target = PlistInfo(options: options)
let github = GitHub(name: "LicensePlist", nameSpecified: nil, owner: "mono0926", version: nil)
let githubLicense = GitHubLicense(library: github,
body: "body",
githubResponse: LicenseResponse(content: "",
encoding: "",
kind: LicenseKindResponse(name: "name",
spdxId: nil)))
target.licenses = [githubLicense]
target.outputPlist()
}
func testReportMissings() {
var target = PlistInfo(options: options)
let github = GitHub(name: "LicensePlist", nameSpecified: nil, owner: "mono0926", version: nil)
let githubLicense = GitHubLicense(library: github,
body: "body",
githubResponse: LicenseResponse(content: "",
encoding: "",
kind: LicenseKindResponse(name: "name",
spdxId: nil)))
target.githubLibraries = [github]
target.licenses = [githubLicense]
target.reportMissings()
}
func testFinish() {
var target = PlistInfo(options: options)
let github = GitHub(name: "LicensePlist", nameSpecified: nil, owner: "mono0926", version: nil)
let githubLicense = GitHubLicense(library: github,
body: "body",
githubResponse: LicenseResponse(content: "",
encoding: "",
kind: LicenseKindResponse(name: "name",
spdxId: nil)))
target.githubLibraries = [github]
target.githubLicenses = [githubLicense]
let podsLicense = CocoaPodsLicense(library: CocoaPods(name: "", nameSpecified: nil, version: nil), body: "body")
target.cocoaPodsLicenses = [podsLicense]
let manualLicense = ManualLicense(library: Manual(name: "", source: nil, nameSpecified: nil, version: nil), body: "body")
target.manualLicenses = [manualLicense]
target.licenses = [githubLicense, podsLicense]
target.summary = ""
target.summaryPath = URL(fileURLWithPath: "")
target.finish()
}
}
| 51.117318 | 140 | 0.513115 |
d752ce183e334fc54bdec644d60f8f2544958f51 | 272 | //
// ImageCollectionViewCell.swift
// QLearnerDemo
//
// Created by Alvin Yu on 6/16/18.
// Copyright © 2018 Alvin Yu. All rights reserved.
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
}
| 16 | 53 | 0.698529 |
f7ef49d44e1bf183c2596276c018cca65fe9a87c | 3,785 | import DroidKaigiMPP
public protocol TimetableItem {
var id: String { get set }
var lang: String { get set }
var title: MultiLangText { get set }
var category: MultiLangText { get set }
var targetAudience: String { get set }
var asset: TimetableAsset { get set }
var levels: [String] { get set }
var speakers: [Speaker] { get set }
var startsAt: Date { get set }
var endsAt: Date { get set }
}
@dynamicMemberLookup
public struct AnyTimetableItem: Equatable, Identifiable {
public var wrappedValue: TimetableItem
public var id: String {
wrappedValue.id
}
public init(_ timetableItem: TimetableItem) {
self.wrappedValue = timetableItem
}
public init?(from model: DroidKaigiMPP.TimetableItem) {
switch model {
case let session as DroidKaigiMPP.TimetableItem.Session:
self.init(Session(from: session))
case let special as DroidKaigiMPP.TimetableItem.Special:
self.init(Special(from: special))
default:
return nil
}
}
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs.wrappedValue, rhs.wrappedValue) {
case let (lhs, rhs) as (Session, Session):
return lhs == rhs
case let (lhs, rhs) as (Special, Special):
return lhs == rhs
default:
return false
}
}
public subscript<T>(dynamicMember keyPath: KeyPath<TimetableItem, T>) -> T {
self.wrappedValue[keyPath: keyPath]
}
}
#if DEBUG
public extension AnyTimetableItem {
static func sessionMock(
id: String = UUID().uuidString,
lang: String = "日本語",
title: MultiLangText = .init(enTitle: "Session Item", jaTitle: "セッションアイテム"),
category: MultiLangText = .init(enTitle: "Category", jaTitle: "カテゴリー"),
targetAudience: String = "Target Audience",
asset: TimetableAsset = .init(videoURLString: "", slideURLString: ""),
levels: [String] = ["easy"],
speakers: [Speaker] = [.mock()],
startsAt: Date = Date(timeIntervalSince1970: 0),
endsAt: Date = Date(timeIntervalSince1970: 100.0),
description: String = "description",
message: MultiLangText? = nil
) -> Self {
.init(
Session(
id: id,
lang: lang,
title: title,
category: category,
targetAudience: targetAudience,
asset: asset,
levels: levels,
speakers: speakers,
startsAt: startsAt,
endsAt: endsAt,
description: description,
message: message
)
)
}
static func specialMock(
id: String = UUID().uuidString,
lang: String = "日本語",
title: MultiLangText = .init(enTitle: "Special Item", jaTitle: "スペシャルアイテム"),
category: MultiLangText = .init(enTitle: "Category", jaTitle: "カテゴリー"),
targetAudience: String = "Target Audience",
asset: TimetableAsset = .init(videoURLString: "", slideURLString: ""),
levels: [String] = ["easy"],
speakers: [Speaker] = [.mock()],
startsAt: Date = Date(timeIntervalSince1970: 0),
endsAt: Date = Date(timeIntervalSince1970: 100.0)
) -> Self {
.init(
Special(
id: id,
lang: lang,
title: title,
category: category,
targetAudience: targetAudience,
asset: asset,
levels: levels,
speakers: speakers,
startsAt: startsAt,
endsAt: endsAt
)
)
}
}
#endif
| 32.076271 | 84 | 0.556407 |
3a8e86af24ce7341673d6c83f90d666d52fe0ef3 | 511 | //
// Domain
//
// Copyright © 2018 mkerekes. All rights reserved.
//
import Foundation
public struct FeatureFlags: Equatable {
public var searchTabs: Bool
public init(defaults: DefaultSettings) {
searchTabs = defaults.bool(forKey: FeatureFlags.searchTabsKey)
}
public init(uploadVideo: Bool, searchTabs: Bool, mention: Bool) {
self.searchTabs = searchTabs
}
}
public extension FeatureFlags {
static let searchTabsKey: String = "FeatureFlags.SearchTabs"
}
| 21.291667 | 70 | 0.690802 |
26757e8fa93f5d38526ea1e9bd71bf9e7a412f0d | 640 | //
// ViewController.swift
// hello color
//
// Created by imac on 4/22/19.
// Copyright © 2019 JeguLabs. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var isYellow = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func changeColor(_ sender: Any) {
if isYellow {
view.backgroundColor = UIColor.green
isYellow = false
} else {
view.backgroundColor = UIColor.yellow
isYellow = true
}
}
}
| 17.777778 | 58 | 0.565625 |
18066ebe4e6c4627cdeb9f39c0f971ff693924cc | 11,364 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020-2022 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
import struct TSCUtility.Versioning
#if canImport(FoundationNetworking)
// FIXME: this brings OpenSSL dependency on Linux
// need to decide how to best deal with that
import FoundationNetworking
#endif
public struct URLSessionHTTPClient {
private let dataTaskManager: DataTaskManager
private let downloadTaskManager: DownloadTaskManager
public init(configuration: URLSessionConfiguration = .default) {
self.dataTaskManager = DataTaskManager(configuration: configuration)
self.downloadTaskManager = DownloadTaskManager(configuration: configuration)
}
public func execute(_ request: HTTPClient.Request, progress: HTTPClient.ProgressHandler?, completion: @escaping HTTPClient.CompletionHandler) {
self.execute(request, observabilityScope: nil, progress: progress, completion: completion)
}
public func execute(_ request: HTTPClient.Request,
observabilityScope: ObservabilityScope? = nil,
progress: HTTPClient.ProgressHandler?,
completion: @escaping HTTPClient.CompletionHandler) {
switch request.kind {
case .generic:
let task = self.dataTaskManager.makeTask(request: request, progress: progress, completion: completion)
task.resume()
case .download(let fileSystem, let destination):
let task = self.downloadTaskManager.makeTask(request: request, fileSystem: fileSystem, destination: destination, progress: progress, completion: completion)
task.resume()
}
}
}
private class DataTaskManager: NSObject, URLSessionDataDelegate {
private var tasks = ThreadSafeKeyValueStore<Int, DataTask>()
private let delegateQueue: OperationQueue
private var session: URLSession!
public init(configuration: URLSessionConfiguration) {
self.delegateQueue = OperationQueue()
self.delegateQueue.name = "org.swift.swiftpm.urlsession-http-client-data-delegate"
self.delegateQueue.maxConcurrentOperationCount = 1
super.init()
self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: self.delegateQueue)
}
func makeTask(request: HTTPClient.Request, progress: HTTPClient.ProgressHandler?, completion: @escaping HTTPClient.CompletionHandler) -> URLSessionDataTask {
let task = self.session.dataTask(with: request.urlRequest())
self.tasks[task.taskIdentifier] = DataTask(task: task, progressHandler: progress, completionHandler: completion, authorizationProvider: request.options.authorizationProvider)
return task
}
public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let task = self.tasks[dataTask.taskIdentifier] else {
return completionHandler(.cancel)
}
task.response = response as? HTTPURLResponse
task.expectedContentLength = response.expectedContentLength
task.progressHandler?(0, response.expectedContentLength)
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let task = self.tasks[dataTask.taskIdentifier] else {
return
}
if task.buffer != nil {
task.buffer?.append(data)
} else {
task.buffer = data
}
task.progressHandler?(Int64(task.buffer?.count ?? 0), task.expectedContentLength) // safe since created in the line above
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let task = self.tasks.removeValue(forKey: task.taskIdentifier) else {
return
}
if let error = error {
task.completionHandler(.failure(error))
} else if let response = task.response {
task.completionHandler(.success(response.response(body: task.buffer)))
} else {
task.completionHandler(.failure(HTTPClientError.invalidResponse))
}
}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
// Don't remove task from dictionary because we want to resume it later
guard let task = self.tasks[task.taskIdentifier] else {
return
}
var request = request
// Set `Authorization` header for the redirected request
if let redirectURL = request.url, let authorization = task.authorizationProvider?(redirectURL), request.value(forHTTPHeaderField: "Authorization") == nil {
request.addValue(authorization, forHTTPHeaderField: "Authorization")
}
completionHandler(request)
}
class DataTask {
let task: URLSessionDataTask
let completionHandler: HTTPClient.CompletionHandler
let progressHandler: HTTPClient.ProgressHandler?
let authorizationProvider: HTTPClientAuthorizationProvider?
var response: HTTPURLResponse?
var expectedContentLength: Int64?
var buffer: Data?
init(task: URLSessionDataTask,
progressHandler: HTTPClient.ProgressHandler?,
completionHandler: @escaping HTTPClient.CompletionHandler,
authorizationProvider: HTTPClientAuthorizationProvider?) {
self.task = task
self.progressHandler = progressHandler
self.completionHandler = completionHandler
self.authorizationProvider = authorizationProvider
}
}
}
private class DownloadTaskManager: NSObject, URLSessionDownloadDelegate {
private var tasks = ThreadSafeKeyValueStore<Int, DownloadTask>()
private let delegateQueue: OperationQueue
private var session: URLSession!
public init(configuration: URLSessionConfiguration) {
self.delegateQueue = OperationQueue()
self.delegateQueue.name = "org.swift.swiftpm.urlsession-http-client-download-delegate"
self.delegateQueue.maxConcurrentOperationCount = 1
super.init()
self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: self.delegateQueue)
}
func makeTask(request: HTTPClient.Request, fileSystem: FileSystem, destination: AbsolutePath, progress: HTTPClient.ProgressHandler?, completion: @escaping HTTPClient.CompletionHandler) -> URLSessionDownloadTask {
let task = self.session.downloadTask(with: request.urlRequest())
self.tasks[task.taskIdentifier] = DownloadTask(task: task, fileSystem: fileSystem, destination: destination, progressHandler: progress, completionHandler: completion)
return task
}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let task = self.tasks[downloadTask.taskIdentifier] else {
return
}
let totalBytesToDownload = totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown ? totalBytesExpectedToWrite : nil
task.progressHandler?(totalBytesWritten, totalBytesToDownload)
}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let task = self.tasks[downloadTask.taskIdentifier] else {
return
}
do {
try task.fileSystem.move(from: AbsolutePath(location.path), to: task.destination)
} catch {
task.moveFileError = error
}
}
public func urlSession(_ session: URLSession, task downloadTask: URLSessionTask, didCompleteWithError error: Error?) {
guard let task = self.tasks.removeValue(forKey: downloadTask.taskIdentifier) else {
return
}
do {
if let error = error {
throw HTTPClientError.downloadError("\(error)")
} else if let error = task.moveFileError {
throw error
} else if let response = downloadTask.response as? HTTPURLResponse {
task.completionHandler(.success(response.response(body: nil)))
} else {
throw HTTPClientError.invalidResponse
}
} catch {
task.completionHandler(.failure(error))
}
}
class DownloadTask {
let task: URLSessionDownloadTask
let fileSystem: FileSystem
let destination: AbsolutePath
let completionHandler: HTTPClient.CompletionHandler
let progressHandler: HTTPClient.ProgressHandler?
var moveFileError: Error?
init(task: URLSessionDownloadTask, fileSystem: FileSystem, destination: AbsolutePath, progressHandler: HTTPClient.ProgressHandler?, completionHandler: @escaping HTTPClient.CompletionHandler) {
self.task = task
self.fileSystem = fileSystem
self.destination = destination
self.progressHandler = progressHandler
self.completionHandler = completionHandler
}
}
}
extension HTTPClient.Request {
func urlRequest() -> URLRequest {
var request = URLRequest(url: self.url)
request.httpMethod = self.methodString()
self.headers.forEach { header in
request.addValue(header.value, forHTTPHeaderField: header.name)
}
request.httpBody = self.body
if let interval = self.options.timeout?.timeInterval() {
request.timeoutInterval = interval
}
return request
}
func methodString() -> String {
switch self.method {
case .head:
return "HEAD"
case .get:
return "GET"
case .post:
return "POST"
case .put:
return "PUT"
case .delete:
return "DELETE"
}
}
}
extension HTTPURLResponse {
func response(body: Data?) -> HTTPClient.Response {
let headers = HTTPClientHeaders(self.allHeaderFields.map { header in
.init(name: "\(header.key)", value: "\(header.value)")
})
return HTTPClient.Response(statusCode: self.statusCode,
statusText: Self.localizedString(forStatusCode: self.statusCode),
headers: headers,
body: body)
}
}
| 42.402985 | 216 | 0.657515 |
2fc7ba41930d9f4402adddb29f97afcfeefa8a2f | 2,074 | //
// TicketValidator.swift
// PretixScan
//
// Created by Daniel Jilg on 19.03.19.
// Copyright © 2019 rami.io. All rights reserved.
//
import Foundation
/// Exposes methods to check the validity of tickets and show event status.
public protocol TicketValidator {
// MARK: - Initialization
/// Initialize ConfigStore and APIClient with Device Keys
func initialize(_ initializationRequest: DeviceInitializationRequest, completionHandler: @escaping (Error?) -> Void)
// MARK: - Check-In Lists and Events
/// Retrieve all available Events for the given user
func getEvents(completionHandler: @escaping ([Event]?, Error?) -> Void)
/// Retrieve all available Sub Events for the given event
func getSubEvents(event: Event, completionHandler: @escaping ([SubEvent]?, Error?) -> Void)
/// Retrieve all available CheckInLists for the current event
func getCheckinLists(event: Event, completionHandler: @escaping ([CheckInList]?, Error?) -> Void)
/// Retrieve Statistics for the currently selected CheckInList
func getCheckInListStatus(completionHandler: @escaping (CheckInListStatus?, Error?) -> Void)
/// Questions that should be answered for the current item
func getQuestions(for item: Item, event: Event, completionHandler: @escaping ([Question]?, Error?) -> Void)
// MARK: - Search
/// Search all OrderPositions within a CheckInList
func search(query: String, completionHandler: @escaping ([OrderPosition]?, Error?) -> Void)
// MARK: - Redemption
/// Check in an attendee, identified by their secret, into the currently configured CheckInList
///
/// - See `RedemptionResponse` for the response returned in the completion handler.
func redeem(secret: String, force: Bool, ignoreUnpaid: Bool, answers: [Answer]?,
as type: String,
completionHandler: @escaping (RedemptionResponse?, Error?) -> Void)
/// Indicates if the ticket validator instance uses online validation or local DataStore state validation.
var isOnline: Bool {get}
}
| 43.208333 | 120 | 0.709257 |
209599cb7d5ef2baf9429c094dd90c88bcb1b4a9 | 11,236 | //
// Goal.swift
// SwiftFHIR
//
// Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Goal) on 2016-09-16.
// 2016, SMART Health IT.
//
import Foundation
/**
* Describes the intended objective(s) for a patient, group or organization.
*
* Describes the intended objective(s) for a patient, group or organization care, for example, weight loss, restoring
* an activity of daily living, obtaining herd immunity via immunization, meeting a process improvement objective, etc.
*/
public class Goal: DomainResource {
override public class var resourceType: String {
get { return "Goal" }
}
/// Issues addressed by this goal.
public var addresses: [Reference]?
/// Who's responsible for creating Goal?.
public var author: Reference?
/// E.g. Treatment, dietary, behavioral, etc..
public var category: [CodeableConcept]?
/// What's the desired outcome?.
public var description_fhir: String?
/// External Ids for this goal.
public var identifier: [Identifier]?
/// Comments about the goal.
public var note: [Annotation]?
/// What was end result of goal?.
public var outcome: [GoalOutcome]?
/// high | medium |low.
public var priority: CodeableConcept?
/// When goal pursuit begins.
public var startCodeableConcept: CodeableConcept?
/// When goal pursuit begins.
public var startDate: FHIRDate?
/// proposed | planned | accepted | rejected | in-progress | achieved | sustaining | on-hold | cancelled.
public var status: String?
/// When goal status took effect.
public var statusDate: FHIRDate?
/// Reason for current status.
public var statusReason: CodeableConcept?
/// Who this goal is intended for.
public var subject: Reference?
/// Reach goal on or before.
public var targetDate: FHIRDate?
/// Reach goal on or before.
public var targetQuantity: Quantity?
/** Initialize with a JSON object. */
public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) {
super.init(json: json, owner: owner)
}
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(description_fhir: String, status: String) {
self.init(json: nil)
self.description_fhir = description_fhir
self.status = status
}
public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? {
var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]()
if let js = json {
if let exist = js["addresses"] {
presentKeys.insert("addresses")
if let val = exist as? [FHIRJSON] {
self.addresses = Reference.instantiate(fromArray: val, owner: self) as? [Reference]
}
else {
errors.append(FHIRJSONError(key: "addresses", wants: Array<FHIRJSON>.self, has: type(of: exist)))
}
}
if let exist = js["author"] {
presentKeys.insert("author")
if let val = exist as? FHIRJSON {
self.author = Reference(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "author", wants: FHIRJSON.self, has: type(of: exist)))
}
}
if let exist = js["category"] {
presentKeys.insert("category")
if let val = exist as? [FHIRJSON] {
self.category = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept]
}
else {
errors.append(FHIRJSONError(key: "category", wants: Array<FHIRJSON>.self, has: type(of: exist)))
}
}
if let exist = js["description"] {
presentKeys.insert("description")
if let val = exist as? String {
self.description_fhir = val
}
else {
errors.append(FHIRJSONError(key: "description", wants: String.self, has: type(of: exist)))
}
}
else {
errors.append(FHIRJSONError(key: "description"))
}
if let exist = js["identifier"] {
presentKeys.insert("identifier")
if let val = exist as? [FHIRJSON] {
self.identifier = Identifier.instantiate(fromArray: val, owner: self) as? [Identifier]
}
else {
errors.append(FHIRJSONError(key: "identifier", wants: Array<FHIRJSON>.self, has: type(of: exist)))
}
}
if let exist = js["note"] {
presentKeys.insert("note")
if let val = exist as? [FHIRJSON] {
self.note = Annotation.instantiate(fromArray: val, owner: self) as? [Annotation]
}
else {
errors.append(FHIRJSONError(key: "note", wants: Array<FHIRJSON>.self, has: type(of: exist)))
}
}
if let exist = js["outcome"] {
presentKeys.insert("outcome")
if let val = exist as? [FHIRJSON] {
self.outcome = GoalOutcome.instantiate(fromArray: val, owner: self) as? [GoalOutcome]
}
else {
errors.append(FHIRJSONError(key: "outcome", wants: Array<FHIRJSON>.self, has: type(of: exist)))
}
}
if let exist = js["priority"] {
presentKeys.insert("priority")
if let val = exist as? FHIRJSON {
self.priority = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "priority", wants: FHIRJSON.self, has: type(of: exist)))
}
}
if let exist = js["startCodeableConcept"] {
presentKeys.insert("startCodeableConcept")
if let val = exist as? FHIRJSON {
self.startCodeableConcept = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "startCodeableConcept", wants: FHIRJSON.self, has: type(of: exist)))
}
}
if let exist = js["startDate"] {
presentKeys.insert("startDate")
if let val = exist as? String {
self.startDate = FHIRDate(string: val)
}
else {
errors.append(FHIRJSONError(key: "startDate", wants: String.self, has: type(of: exist)))
}
}
if let exist = js["status"] {
presentKeys.insert("status")
if let val = exist as? String {
self.status = val
}
else {
errors.append(FHIRJSONError(key: "status", wants: String.self, has: type(of: exist)))
}
}
else {
errors.append(FHIRJSONError(key: "status"))
}
if let exist = js["statusDate"] {
presentKeys.insert("statusDate")
if let val = exist as? String {
self.statusDate = FHIRDate(string: val)
}
else {
errors.append(FHIRJSONError(key: "statusDate", wants: String.self, has: type(of: exist)))
}
}
if let exist = js["statusReason"] {
presentKeys.insert("statusReason")
if let val = exist as? FHIRJSON {
self.statusReason = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "statusReason", wants: FHIRJSON.self, has: type(of: exist)))
}
}
if let exist = js["subject"] {
presentKeys.insert("subject")
if let val = exist as? FHIRJSON {
self.subject = Reference(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "subject", wants: FHIRJSON.self, has: type(of: exist)))
}
}
if let exist = js["targetDate"] {
presentKeys.insert("targetDate")
if let val = exist as? String {
self.targetDate = FHIRDate(string: val)
}
else {
errors.append(FHIRJSONError(key: "targetDate", wants: String.self, has: type(of: exist)))
}
}
if let exist = js["targetQuantity"] {
presentKeys.insert("targetQuantity")
if let val = exist as? FHIRJSON {
self.targetQuantity = Quantity(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "targetQuantity", wants: FHIRJSON.self, has: type(of: exist)))
}
}
}
return errors.isEmpty ? nil : errors
}
override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON {
var json = super.asJSON(with: options)
if let addresses = self.addresses {
json["addresses"] = addresses.map() { $0.asJSON(with: options) }
}
if let author = self.author {
json["author"] = author.asJSON(with: options)
}
if let category = self.category {
json["category"] = category.map() { $0.asJSON(with: options) }
}
if let description_fhir = self.description_fhir {
json["description"] = description_fhir.asJSON(with: options)
}
if let identifier = self.identifier {
json["identifier"] = identifier.map() { $0.asJSON(with: options) }
}
if let note = self.note {
json["note"] = note.map() { $0.asJSON(with: options) }
}
if let outcome = self.outcome {
json["outcome"] = outcome.map() { $0.asJSON(with: options) }
}
if let priority = self.priority {
json["priority"] = priority.asJSON(with: options)
}
if let startCodeableConcept = self.startCodeableConcept {
json["startCodeableConcept"] = startCodeableConcept.asJSON(with: options)
}
if let startDate = self.startDate {
json["startDate"] = startDate.asJSON(with: options)
}
if let status = self.status {
json["status"] = status.asJSON(with: options)
}
if let statusDate = self.statusDate {
json["statusDate"] = statusDate.asJSON(with: options)
}
if let statusReason = self.statusReason {
json["statusReason"] = statusReason.asJSON(with: options)
}
if let subject = self.subject {
json["subject"] = subject.asJSON(with: options)
}
if let targetDate = self.targetDate {
json["targetDate"] = targetDate.asJSON(with: options)
}
if let targetQuantity = self.targetQuantity {
json["targetQuantity"] = targetQuantity.asJSON(with: options)
}
return json
}
}
/**
* What was end result of goal?.
*
* Identifies the change (or lack of change) at the point where the goal was deepmed to be cancelled or achieved.
*/
public class GoalOutcome: BackboneElement {
override public class var resourceType: String {
get { return "GoalOutcome" }
}
/// Code or observation that resulted from goal.
public var resultCodeableConcept: CodeableConcept?
/// Code or observation that resulted from goal.
public var resultReference: Reference?
/** Initialize with a JSON object. */
public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) {
super.init(json: json, owner: owner)
}
public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? {
var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]()
if let js = json {
if let exist = js["resultCodeableConcept"] {
presentKeys.insert("resultCodeableConcept")
if let val = exist as? FHIRJSON {
self.resultCodeableConcept = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "resultCodeableConcept", wants: FHIRJSON.self, has: type(of: exist)))
}
}
if let exist = js["resultReference"] {
presentKeys.insert("resultReference")
if let val = exist as? FHIRJSON {
self.resultReference = Reference(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "resultReference", wants: FHIRJSON.self, has: type(of: exist)))
}
}
}
return errors.isEmpty ? nil : errors
}
override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON {
var json = super.asJSON(with: options)
if let resultCodeableConcept = self.resultCodeableConcept {
json["resultCodeableConcept"] = resultCodeableConcept.asJSON(with: options)
}
if let resultReference = self.resultReference {
json["resultReference"] = resultReference.asJSON(with: options)
}
return json
}
}
| 31.29805 | 120 | 0.667853 |
61f0f0553085b929d0f9a7c9bb8215f0bd1659bd | 1,185 | // Created by yaoshuai on 2018/5/22.
// Copyright © 2018 ys. All rights reserved.
import UIKit
class YSLoadingIndicatorView_default:YSLoadingIndicatorView{
private lazy var loadingIndicatorView = UIActivityIndicatorView(style: .gray)
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
private func setupUI(){
addSubview(loadingIndicatorView)
loadingIndicatorView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: loadingIndicatorView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: loadingIndicatorView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
override func ys_startLoadingIndicatorView() {
loadingIndicatorView.startAnimating()
}
override func ys_stopLoadingIndicatorView() {
loadingIndicatorView.stopAnimating()
}
}
| 32.916667 | 172 | 0.695359 |
62a7fef8807de085c06b282923b985e804ef1afc | 2,881 | //
// TimelineViewController.swift
// twitter_alamofire_demo
//
// Created by Aristotle on 2018-08-11.
// Copyright © 2018 Charles Hieger. All rights reserved.
//
import UIKit
class TimelineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var tweets: [Tweet] = []
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
let nav = self.navigationController?.navigationBar
nav!.barTintColor = UIColor(red:0.11, green:0.63, blue:0.95, alpha:1.0)
nav!.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
self.refreshControl = UIRefreshControl()
self.refreshControl.addTarget(self, action: #selector(TimelineViewController.didPullToRefresh(_:)), for: .valueChanged)
tableView.dataSource = self
tableView.rowHeight = 180
tableView.estimatedRowHeight = 180
tableView.insertSubview(refreshControl, at: 0)
fetchTweets()
}
@objc func didPullToRefresh(_ refreshControl: UIRefreshControl){
fetchTweets()
}
@IBAction func onLogoutButton(_ sender: Any) {
//print("Log Out Successfully")
let actionSheet = UIAlertController(title: "Closing Session", message: "Are you sure you want to log Out?", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Disconnect Session", style: .default, handler: {(UIAlertAction) in
APIManager.shared.logout()
//NotificationCenter.default.post(name: NSNotification.Name("didLogout"), object: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell
cell.tweet = tweets[indexPath.row]
return cell
}
func fetchTweets() {
APIManager.shared.getHomeTimeLine { (tweets, error) in
if let error = error {
print(error.localizedDescription)
}
else {
self.tweets = tweets!
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 32.738636 | 145 | 0.636932 |
75ae8d025803ac1b7a4ea0eaa81b9de9102a58a4 | 4,993 | //
// MessageBubbleDecorator.swift
// Tinodios
//
// Copyright © 2019 Tinode. All rights reserved.
//
import UIKit
/// Draws message bubble as bezier path in iMessage style.
class MessageBubbleDecorator {
public enum Style {
case single, last, middle, first
}
private static func drawIncomig(path: UIBezierPath, size: CGSize, style: Style) {
let width = size.width
let height = size.height
// Start at bottom-left corner.
if style == .single || style == .last {
// Leave space for the rounded corner.
path.move(to: CGPoint(x: 22, y: height))
} else {
path.move(to: CGPoint(x: 4, y: height))
}
// Move to bottom right
path.addLine(to: CGPoint(x: width - 17, y: height))
// Add bottom-right rounded corner
path.addCurve(to: CGPoint(x: width, y: height - 17), controlPoint1: CGPoint(x: width - 7.61, y: height), controlPoint2: CGPoint(x: width, y: height - 7.61))
// Move to top right corner
path.addLine(to: CGPoint(x: width, y: 17))
// Add top-right round corner
path.addCurve(to: CGPoint(x: width - 17, y: 0), controlPoint1: CGPoint(x: width, y: 7.61), controlPoint2: CGPoint(x: width - 7.61, y: 0))
// Move to top left corner
if style == .single || style == .first {
// Leave space for the rounded corner.
path.addLine(to: CGPoint(x: 21, y: 0))
// Top left round corner
path.addCurve(to: CGPoint(x: 4, y: 17), controlPoint1: CGPoint(x: 11.61, y: 0), controlPoint2: CGPoint(x: 4, y: 7.61))
} else {
path.addLine(to: CGPoint(x: 4, y: 0))
}
// Move to bottom-left.
if style == .single || style == .last {
// Leave space for pigtail.
path.addLine(to: CGPoint(x: 4, y: height - 11))
// Pigtail top
path.addCurve(to: CGPoint(x: 0, y: height), controlPoint1: CGPoint(x: 4, y: height - 1), controlPoint2: CGPoint(x: 0, y: height))
// Pigtail bottom
path.addCurve(to: CGPoint(x: 11, y: height - 4), controlPoint1: CGPoint(x: 4, y: height + 0.43), controlPoint2: CGPoint(x: 8.16, y: height - 1.06))
// Remainder of the bottom left round corner
path.addCurve(to: CGPoint(x: 22, y: height), controlPoint1: CGPoint(x: 16, y: height), controlPoint2: CGPoint(x: 19, y: height))
} else {
// Move to bottom-left
path.addLine(to: CGPoint(x: 4, y: height))
}
}
private static func drawOutgoing(path: UIBezierPath, size: CGSize, style: Style) {
let width = size.width
let height = size.height
// Start at bottom-right corner
if style == .single || style == .last {
path.move(to: CGPoint(x: width - 22, y: height))
} else {
path.move(to: CGPoint(x: width - 4, y: height))
}
// Move to bottom-left
path.addLine(to: CGPoint(x: 17, y: height))
// Bottom-left round corner
path.addCurve(to: CGPoint(x: 0, y: height - 17), controlPoint1: CGPoint(x: 7.61, y: height), controlPoint2: CGPoint(x: 0, y: height - 7.61))
// Move to top-left
path.addLine(to: CGPoint(x: 0, y: 17))
// Top-left round corner
path.addCurve(to: CGPoint(x: 17, y: 0), controlPoint1: CGPoint(x: 0, y: 7.61), controlPoint2: CGPoint(x: 7.61, y: 0))
// Move to top-right
if style == .single || style == .first {
path.addLine(to: CGPoint(x: width - 21, y: 0))
path.addCurve(to: CGPoint(x: width - 4, y: 17), controlPoint1: CGPoint(x: width - 11.61, y: 0), controlPoint2: CGPoint(x: width - 4, y: 7.61))
} else {
path.addLine(to: CGPoint(x: width - 4, y: 0))
}
// Move to bottom-right
if style == .single || style == .last {
path.addLine(to: CGPoint(x: width - 4, y: height - 11))
// Pigtail
path.addCurve(to: CGPoint(x: width, y: height), controlPoint1: CGPoint(x: width - 4, y: height - 1), controlPoint2: CGPoint(x: width, y: height))
path.addCurve(to: CGPoint(x: width - 11.04, y: height - 4.04), controlPoint1: CGPoint(x: width - 4.07, y: height + 0.43), controlPoint2: CGPoint(x: width - 8.16, y: height - 1.06))
path.addCurve(to: CGPoint(x: width - 22, y: height), controlPoint1: CGPoint(x: width - 16, y: height), controlPoint2: CGPoint(x: width - 19, y: height))
} else {
path.addLine(to: CGPoint(x: width - 4, y: height))
}
}
public static func draw(_ rect: CGRect, isIncoming: Bool, style: Style) -> UIBezierPath {
let path = UIBezierPath()
if isIncoming {
drawIncomig(path: path, size: rect.size, style: style)
} else {
drawOutgoing(path: path, size: rect.size, style: style)
}
path.close()
return path
}
}
| 41.608333 | 192 | 0.565792 |
298ec1649d607c50b4df2c48a9b4b5c3fa60f6bb | 381 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
func f: A? {
return "
}
protocol b {
protocol a {
protocol a {
}
(T) {
protocol P {
enum A {
}
}
}
}
typealias B : B)
private class A {
}
class func ^(.
| 14.653846 | 87 | 0.677165 |
87a191930991cccca58aadc9dab3bfeee2e0754d | 2,976 | import XCTest
import BigInt
import VioletCore
@testable import VioletBytecode
// MARK: - Assert
func XCTAssertNoInstructions(_ code: CodeObject,
file: StaticString = #file,
line: UInt = #line) {
let count = code.instructions.count
XCTAssertEqual(count, 0, "Instuction count: \(count)", file: file, line: line)
}
func XCTAssertInstructions(_ code: CodeObject,
_ expected: Instruction...,
file: StaticString = #file,
line: UInt = #line) {
let count = code.instructions.count
let expectedCount = expected.count
XCTAssertEqual(count, expectedCount, "Count", file: file, line: line)
for (index, (i, e)) in zip(code.instructions, expected).enumerated() {
XCTAssertEqual(i, e, "Instruction: \(index)", file: file, line: line)
}
}
func XCTAssertInstructionsEndWith(_ code: CodeObject,
_ expected: Instruction...,
file: StaticString = #file,
line: UInt = #line) {
let count = code.instructions.count
let startIndex = count - expected.count
guard startIndex >= 0 else {
XCTFail("Got only \(count) instructions", file: file, line: line)
return
}
let tail = code.instructions[startIndex...]
for (index, (i, e)) in zip(tail, expected).enumerated() {
XCTAssertEqual(i, e, "Instruction: \(index)", file: file, line: line)
}
}
// MARK: - Assert filled
func XCTAssertFilledInstructions(_ code: CodeObject,
_ expected: Instruction.Filled...,
file: StaticString = #file,
line: UInt = #line) {
var expectedIndex = 0
var instructionIndex: Int? = 0
while let index = instructionIndex {
let filled = code.getFilledInstruction(index: index)
let instruction = filled.instruction
// We may have more 'instructions' than 'expected'
if expectedIndex < expected.count {
let expectedInstruction = expected[expectedIndex]
XCTAssertEqual(instruction, expectedInstruction, file: file, line: line)
}
expectedIndex += 1
instructionIndex = filled.nextInstructionIndex
}
let instructionCount = expectedIndex
XCTAssertEqual(instructionCount, expected.count, "Count", file: file, line: line)
}
// MARK: - Assert lines
func XCTAssertInstructionLines(_ code: CodeObject,
_ expected: SourceLocation...,
file: StaticString = #file,
line: UInt = #line) {
let count = code.instructionLines.count
let expectedCount = expected.count
XCTAssertEqual(count, expectedCount, "Count", file: file, line: line)
guard count == expectedCount else {
return
}
for (l, e) in zip(code.instructionLines, expected) {
XCTAssertEqual(l, e.line, file: file, line: line)
}
}
| 32.703297 | 83 | 0.606855 |
3885f9137a8ff0fa5cd53730342b08517d424438 | 68 | import Foundation
public protocol Cancelable {
func cancel()
}
| 11.333333 | 28 | 0.735294 |
2248b6324c357f0ed2187bbe7188584581b1b089 | 13,136 | import Foundation
import TSCBasic
import TuistCore
import TuistCoreTesting
import TuistGraph
import TuistSupport
import XCTest
@testable import TuistCache
@testable import TuistCore
@testable import TuistSupportTesting
final class ContentHashingIntegrationTests: TuistTestCase {
var subject: CacheGraphContentHasher!
var temporaryDirectoryPath: String!
var source1: SourceFile!
var source2: SourceFile!
var source3: SourceFile!
var source4: SourceFile!
var resourceFile1: ResourceFileElement!
var resourceFile2: ResourceFileElement!
var resourceFolderReference1: ResourceFileElement!
var resourceFolderReference2: ResourceFileElement!
var coreDataModel1: CoreDataModel!
var coreDataModel2: CoreDataModel!
override func setUp() {
super.setUp()
do {
let temporaryDirectoryPath = try temporaryPath()
source1 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "1", content: "1")
source2 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "2", content: "2")
source3 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "3", content: "3")
source4 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "4", content: "4")
resourceFile1 = try createTemporaryResourceFile(on: temporaryDirectoryPath, name: "r1", content: "r1")
resourceFile2 = try createTemporaryResourceFile(on: temporaryDirectoryPath, name: "r2", content: "r2")
resourceFolderReference1 = try createTemporaryResourceFolderReference(on: temporaryDirectoryPath, name: "rf1", content: "rf1")
resourceFolderReference2 = try createTemporaryResourceFolderReference(on: temporaryDirectoryPath, name: "rf2", content: "rf2")
_ = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "CoreDataModel1", content: "cd1")
_ = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "CoreDataModel2", content: "cd2")
_ = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "Info.plist", content: "plist")
coreDataModel1 = CoreDataModel(path: temporaryDirectoryPath.appending(component: "CoreDataModel1"), versions: [], currentVersion: "1")
coreDataModel2 = CoreDataModel(path: temporaryDirectoryPath.appending(component: "CoreDataModel2"), versions: [], currentVersion: "2")
} catch {
XCTFail("Error while creating files for stub project")
}
subject = CacheGraphContentHasher(contentHasher: CacheContentHasher())
}
override func tearDown() {
subject = nil
source1 = nil
source2 = nil
source3 = nil
source4 = nil
resourceFile1 = nil
resourceFile2 = nil
resourceFolderReference1 = nil
resourceFolderReference2 = nil
coreDataModel1 = nil
coreDataModel2 = nil
super.tearDown()
}
// MARK: - Sources
func test_contentHashes_frameworksWithSameSources() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source2, source1])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_frameworksWithDifferentSources() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source3, source4])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_hashIsConsistent() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source3, source4])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
let cacheProfile = TuistGraph.Cache.Profile(name: "Simulator", configuration: "Debug")
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: cacheProfile, cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], "5b1073381e4136d10d15ac767f8cc2cb")
XCTAssertEqual(contentHash[framework2], "2e261ee6310a4f02ee6f1830e79df77f")
}
func test_contentHashes_hashChangesWithCacheOutputType() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source3, source4])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentFrameworkHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
let contentXCFrameworkHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .xcframework)
// Then
XCTAssertNotEqual(contentFrameworkHash[framework1], contentXCFrameworkHash[framework1])
XCTAssertNotEqual(contentFrameworkHash[framework2], contentXCFrameworkHash[framework2])
}
// MARK: - Resources
func test_contentHashes_differentResourceFiles() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", resources: [resourceFile1])
let framework2 = makeFramework(named: "f2", resources: [resourceFile2])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_differentResourcesFolderReferences() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", resources: [resourceFolderReference1])
let framework2 = makeFramework(named: "f2", resources: [resourceFolderReference2])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_sameResources() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let resources: [ResourceFileElement] = [resourceFile1, resourceFolderReference1]
let framework1 = makeFramework(named: "f1", resources: resources)
let framework2 = makeFramework(named: "f2", resources: resources)
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - Core Data Models
func test_contentHashes_differentCoreDataModels() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", coreDataModels: [coreDataModel1])
let framework2 = makeFramework(named: "f2", coreDataModels: [coreDataModel2])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_sameCoreDataModels() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", coreDataModels: [coreDataModel1])
let framework2 = makeFramework(named: "f2", coreDataModels: [coreDataModel1])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - Target Actions
// MARK: - Platform
func test_contentHashes_differentPlatform() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", platform: .iOS)
let framework2 = makeFramework(named: "f2", platform: .macOS)
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - ProductName
func test_contentHashes_differentProductName() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", productName: "1")
let framework2 = makeFramework(named: "f2", productName: "2")
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - Private helpers
private func createTemporarySourceFile(on temporaryDirectoryPath: AbsolutePath, name: String, content: String) throws -> SourceFile {
let filePath = temporaryDirectoryPath.appending(component: name)
try FileHandler.shared.touch(filePath)
try FileHandler.shared.write(content, path: filePath, atomically: true)
return SourceFile(path: filePath, compilerFlags: nil)
}
private func createTemporaryResourceFile(on temporaryDirectoryPath: AbsolutePath,
name: String,
content: String) throws -> ResourceFileElement
{
let filePath = temporaryDirectoryPath.appending(component: name)
try FileHandler.shared.touch(filePath)
try FileHandler.shared.write(content, path: filePath, atomically: true)
return ResourceFileElement.file(path: filePath)
}
private func createTemporaryResourceFolderReference(on temporaryDirectoryPath: AbsolutePath,
name: String,
content: String) throws -> ResourceFileElement
{
let filePath = temporaryDirectoryPath.appending(component: name)
try FileHandler.shared.touch(filePath)
try FileHandler.shared.write(content, path: filePath, atomically: true)
return ResourceFileElement.folderReference(path: filePath)
}
private func makeFramework(named: String,
platform: Platform = .iOS,
productName: String? = nil,
sources: [SourceFile] = [],
resources: [ResourceFileElement] = [],
coreDataModels: [CoreDataModel] = [],
targetActions: [TargetAction] = []) -> TargetNode
{
TargetNode.test(
project: .test(path: AbsolutePath("/test/\(named)")),
target: .test(platform: platform,
product: .framework,
productName: productName,
sources: sources,
resources: resources,
coreDataModels: coreDataModels,
actions: targetActions)
)
}
}
| 43.068852 | 146 | 0.655755 |
752ff96377f74c2542cc634cb95be1b907248490 | 3,489 | /*
* license-start
*
* Copyright (C) 2021 Ministero della Salute and all other contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// CRLProgress.swift
// Verifier
//
// Created by Andrea Prosseda on 07/09/21.
//
import Foundation
struct CRLProgress: Codable {
var currentVersion: Int
var requestedVersion: Int
var currentChunk: Int?
var totalChunk: Int?
var sizeSingleChunkInByte: Int?
var totalSizeInByte: Int?
var downloadedSize: Double?
static let FIRST_VERSION: Int = 0
static let FIRST_CHUNK: Int = 1
public init(version: Int? = nil) {
currentVersion = version ?? CRLProgress.FIRST_VERSION
requestedVersion = version ?? CRLProgress.FIRST_VERSION
}
init(serverStatus: CRLStatus?) {
self.init(
currentVersion: serverStatus?.fromVersion,
requestedVersion: serverStatus?.version,
currentChunk: CRLProgress.FIRST_CHUNK,
totalChunk: serverStatus?.totalChunk,
sizeSingleChunkInByte: serverStatus?.sizeSingleChunkInByte,
totalSizeInByte: serverStatus?.totalSizeInByte
)
}
public init(
currentVersion: Int?,
requestedVersion: Int?,
currentChunk: Int? = nil,
totalChunk: Int? = nil,
sizeSingleChunkInByte: Int? = nil,
totalSizeInByte: Int? = nil,
downloadedSize: Double? = nil
) {
self.currentVersion = currentVersion ?? CRLProgress.FIRST_VERSION
self.requestedVersion = requestedVersion ?? CRLProgress.FIRST_VERSION
self.currentChunk = currentChunk
self.totalChunk = totalChunk
self.sizeSingleChunkInByte = sizeSingleChunkInByte
self.totalSizeInByte = totalSizeInByte
self.downloadedSize = downloadedSize ?? 0
}
var remainingSize: String {
guard let responseSize = totalSizeInByte else { return "" }
guard let downloadedSize = downloadedSize else { return "" }
return (responseSize.doubleValue - downloadedSize).toMegaBytes.byteReadableValue
}
var current: Float {
guard let currentChunk = currentChunk else { return 0 }
guard let totalChunks = totalChunk else { return 0 }
return Float(currentChunk)/Float(totalChunks)
}
var chunksMessage: String {
guard let currentChunk = currentChunk else { return "" }
guard let totalChunks = totalChunk else { return "" }
return "crl.update.progress".localizeWith(currentChunk, totalChunks)
}
var downloadedMessage: String {
guard let responseSize = totalSizeInByte else { return "" }
guard let downloadedSize = downloadedSize else { return "" }
let total = responseSize.toMegaBytes.byteReadableValue
let downloaded = downloadedSize.toMegaBytes.byteReadableValue
return "crl.update.progress.mb".localizeWith(downloaded, total)
}
}
| 34.544554 | 88 | 0.672112 |
91140d60b79441f1c0e0b8d53e649665575de412 | 231 | //
// ClaudeCardApp.swift
// ClaudeCard
//
// Created by Kevin Babou on 9/27/21.
//
import SwiftUI
@main
struct ClaudeCardApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.833333 | 38 | 0.5671 |
1a173792b80fc21d1686f004275530e2794ef3f1 | 3,689 | //
// Percy+Context.swift
// Percy
//
// Created by Alexander Kulabukhov on 28/04/2018.
//
import CoreData
extension Percy {
// MARK: - Context
func makeTemporaryContext() -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.parent = self.mainContext
context.mergePolicy = NSOverwriteMergePolicy
return context
}
func performSync<T>(execute block: (NSManagedObjectContext) throws -> T) -> T? {
if Thread.isMainThread {
return try? block(self.mainContext)
} else {
var result: T?
let context = self.makeTemporaryContext()
context.performAndWait { result = try? block(context) }
return result
}
}
/// Synchronous save
func performWithSave(_ changesBlock: (NSManagedObjectContext) throws -> Void) throws {
guard !coordinator.persistentStores.isEmpty else { throw PercyError.closedStorage }
if Thread.isMainThread {
try changesBlock(self.mainContext)
try saveMainContext()
} else {
let context = self.makeTemporaryContext()
try context.performThrowsAndWait {
try changesBlock(context)
try saveTemporaryContext(context)
}
}
}
/// Asynchronous save
func performWithSave(_ changesBlock: @escaping (NSManagedObjectContext) throws -> (), completion: PercyResultHandler<Void>?) {
guard !coordinator.persistentStores.isEmpty else { completion?(.failure(PercyError.closedStorage)); return }
let context = self.makeTemporaryContext()
context.perform { [weak self] in
do { try changesBlock(context) }
catch { DispatchQueue.main.async { completion?(.failure(error)) }; return }
self?.saveTemporaryContext(context, completion: completion)
}
}
// MARK: - Private
private func saveTemporaryContext(_ context: NSManagedObjectContext) throws {
guard context.hasChanges else { return }
try context.save()
try saveMainContextSync()
}
private func saveMainContext() throws {
guard mainContext.hasChanges else { return }
do { try mainContext.save() }
catch { mainContext.rollback(); throw error }
savePrivateContext()
}
private func saveMainContextSync() throws {
guard mainContext.hasChanges else { return }
try mainContext.performThrowsAndWait {
try saveMainContext()
}
}
private func savePrivateContext() {
guard privateContext.hasChanges else { return }
privateContext.perform { [context = privateContext] in
try? context.save()
}
}
private func saveTemporaryContext(_ context: NSManagedObjectContext, completion: PercyResultHandler<Void>?) {
let result = context.saveWithResult()
self.mainContext.performAndWait { [weak self] in
guard let `self` = self else { completion?(.failure(PercyError.closedStorage)); return }
guard case .success = result else { completion?(result); return }
do { try self.saveMainContext(); completion?(.success) }
catch { completion?(.failure(error)) }
}
}
}
fileprivate extension NSManagedObjectContext {
@discardableResult
func saveWithResult() -> PercyResult<Void> {
guard self.hasChanges else { return .success }
do { try self.save(); return .success }
catch { return .failure(error) }
}
}
| 33.844037 | 130 | 0.624288 |
0e84e2573c28e6dfaca3c9cbc77d952caaf1eeec | 752 | @testable import Beowulf
import XCTest
fileprivate let sig = Signature(
signature: Data("7a6fa349f1f624643119f667f394a435c1d31d6f39d8191389305e519a0c051222df037180dc86e00ca4fe43ab638f1e8a96403b3857780abaad4017e03d1ef0"),
recoveryId: 1
)
fileprivate let sigHex = "207a6fa349f1f624643119f667f394a435c1d31d6f39d8191389305e519a0c051222df037180dc86e00ca4fe43ab638f1e8a96403b3857780abaad4017e03d1ef0"
class SignatureTest: XCTestCase {
func testEncodable() {
AssertEncodes(sig, sigHex)
}
func testEncodeDecode() {
AssertDecodes(string: sigHex, sig)
}
func testRecover() {
XCTAssertEqual(sig.recover(message: Data(count: 32)), PublicKey("BEO6BohVaUq55WgAD38pYVMZE4oxmoX7hAgxsni5EdNdgaKJ8FQDR"))
}
}
| 31.333333 | 157 | 0.791223 |
f4d2d458328038852eae5cd8af1dbe792eb23d6c | 262 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a<T {
class n {
func a
var _ = ( ( ( ) {
}
var _ = [ ]
func p( ) {
enum b {
var _ = a<T
| 18.714286 | 87 | 0.656489 |
0ead44a0d7d5fb176eda9ffec49b1d3a27b09d1e | 314 | //
// Locking.swift
//
//
// Created by Sergej Jaskiewicz on 11.06.2019.
//
import COpenCombineHelpers
extension UnfairRecursiveLock {
@inlinable
internal func `do`<Result>(_ body: () throws -> Result) rethrows -> Result {
lock()
defer { unlock() }
return try body()
}
}
| 16.526316 | 80 | 0.598726 |
2637916c404661c22152f7c23de89b6db7e3514c | 932 | import Foundation
/// Classification of the album by it's type of content: soundtrack, live album, studio album, etc.
public enum MusicAlbumProduction: String, CaseIterable, Codable {
case compilation = "CompilationAlbum"
case djMix = "DJMixAlbum"
case demo = "DemoAlbum"
case live = "LiveAlbum"
case mixtape = "MixtapeAlbum"
case remix = "RemixAlbum"
case soundtrack = "SoundtrackAlbum"
case spokenWord = "SpokenWordAlbum"
case studio = "StudioAlbum"
public var displayValue: String {
switch self {
case .compilation: return "Compilation"
case .djMix: return "DJ Mix"
case .demo: return "Demo"
case .live: return "Live"
case .mixtape: return "Mixtape"
case .remix: return "Remix"
case .soundtrack: return "Soundtrack"
case .spokenWord: return "Spoken Word"
case .studio: return "Studio"
}
}
}
| 32.137931 | 99 | 0.645923 |
230580a70b2f23a39eb71301701978c37c952cb6 | 880 | // swift-tools-version:5.2
import PackageDescription
import Foundation
let theosPath = ProcessInfo.processInfo.environment["THEOS"]!
let libFlags: [String] = [
"-F\(theosPath)/vendor/lib",
"-F\(theosPath)/lib",
"-I\(theosPath)/vendor/include",
"-I\(theosPath)/include"
]
let cFlags: [String] = libFlags + [
"-Wno-unused-command-line-argument",
"-Qunused-arguments",
]
let package = Package(
name: "TipTapTime",
platforms: [.iOS("13.0")],
products: [
.library(
name: "TipTapTime",
targets: ["TipTapTime"]
),
],
targets: [
.target(
name: "TipTapTimeC",
cSettings: [.unsafeFlags(cFlags)]
),
.target(
name: "TipTapTime",
dependencies: ["TipTapTimeC"],
swiftSettings: [.unsafeFlags(libFlags)]
),
]
)
| 21.463415 | 61 | 0.552273 |
f9596c806a97646bc7703a12a88d457bee67271d | 204 | //
// Constants.swift
// SimpleCounter
//
// Created by Erik Maximilian Martens on 25.03.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import Foundation
enum Constants {}
| 17 | 66 | 0.710784 |
f55ffd57c12cb38e5bdf3aeffaede078500c53a6 | 2,206 | //
// AppDelegate.swift
// com.awareframework.ios.sensor.significantmotion
//
// Created by tetujin on 11/20/2018.
// Copyright (c) 2018 tetujin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.93617 | 285 | 0.75612 |
5b43fd04f21a37ccaeb745af63b788f70e4c7bb8 | 749 | import XCTest
import FooterLinker
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.827586 | 111 | 0.602136 |
5d3876b78613cdb857b38bdd821b143c1c6f99bc | 3,116 | //
// AppDelegate.swift
// CoreMLSimple
//
// Created by 杨萧玉 on 2017/6/9.
// Copyright © 2017年 杨萧玉. All rights reserved.
// Based on Shuichi Tsutsumi's Code
import AVFoundation
// CREDIT: github.com/yulingtianxia/Core-ML-Sample
extension AVCaptureDevice {
private func availableFormatsFor(preferredFps: Float64) -> [AVCaptureDevice.Format] {
var availableFormats: [AVCaptureDevice.Format] = []
for format in formats
{
let ranges = format.videoSupportedFrameRateRanges
for range in ranges where range.minFrameRate <= preferredFps && preferredFps <= range.maxFrameRate
{
availableFormats.append(format)
}
}
return availableFormats
}
private func formatWithHighestResolution(_ availableFormats: [AVCaptureDevice.Format]) -> AVCaptureDevice.Format?
{
var maxWidth: Int32 = 0
var selectedFormat: AVCaptureDevice.Format?
for format in availableFormats {
let desc = format.formatDescription
let dimensions = CMVideoFormatDescriptionGetDimensions(desc)
let width = dimensions.width
if width >= maxWidth {
maxWidth = width
selectedFormat = format
}
}
return selectedFormat
}
private func formatFor(preferredSize: CGSize, availableFormats: [AVCaptureDevice.Format]) -> AVCaptureDevice.Format?
{
for format in availableFormats {
let desc = format.formatDescription
let dimensions = CMVideoFormatDescriptionGetDimensions(desc)
if dimensions.width >= Int32(preferredSize.width) && dimensions.height >= Int32(preferredSize.height)
{
return format
}
}
return nil
}
func updateFormatWithPreferredVideoSpec(preferredSpec: VideoSpec)
{
let availableFormats: [AVCaptureDevice.Format]
if let preferredFps = preferredSpec.fps {
availableFormats = availableFormatsFor(preferredFps: Float64(preferredFps))
}
else {
availableFormats = formats
}
var selectedFormat: AVCaptureDevice.Format?
if let preferredSize = preferredSpec.size {
selectedFormat = formatFor(preferredSize: preferredSize, availableFormats: availableFormats)
} else {
selectedFormat = formatWithHighestResolution(availableFormats)
}
print("selected format: \(String(describing: selectedFormat))")
if let selectedFormat = selectedFormat {
do {
try lockForConfiguration()
}
catch {
fatalError("")
}
activeFormat = selectedFormat
if let preferredFps = preferredSpec.fps {
activeVideoMinFrameDuration = CMTimeMake(1, preferredFps)
activeVideoMaxFrameDuration = CMTimeMake(1, preferredFps)
unlockForConfiguration()
}
}
}
}
| 33.869565 | 120 | 0.609435 |
8a4a702e0106e6ca7101e4055e61591781d57755 | 1,295 | import SwiftUI
struct EventDetailHeaderView: View {
let viewModel: EventDetailHeaderViewModel
var body: some View {
VStack {
HStack(spacing: 16) {
Spacer()
Text(viewModel.event.title)
.font(.title)
.foregroundColor(Color.white)
Spacer()
}
.background(
DownloadPhotoView(viewModel: viewModel.photoViewModel())
)
}
}
}
struct EventDetailHeaderView_Previews: PreviewProvider {
static var previews: some View {
Group {
EventCardView(
viewModel: EventCardViewModel(
event: Event(
id: "1",
people: [Person(picture: "", name: "Person 01", eventId: "1", id: "1")],
date: "20/10/2020",
description: "A brief description about the event",
image: "",
longitude: -1.1,
latitude: -2.2,
price: "R$ 5,90",
title: "A good Event"
)
)
)
}.previewLayout(.fixed(width: 400, height: 150))
}
}
| 30.116279 | 96 | 0.432432 |
6ad8291da91fb9da74dab276dbefd865ccd4bfd8 | 3,113 | import Foundation
public struct AnyCodable: Codable {
public let value: Any
public init<T>(_ value: T?) {
self.value = value ?? ()
}
}
extension AnyCodable: AnyEncodableProtocol, AnyDecodableProtocol {}
extension AnyCodable {
public var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
// swiftlint:disable cyclomatic_complexity
extension AnyCodable: Equatable {
public static func == (lhs: AnyCodable, rhs: AnyCodable) -> Bool {
switch (lhs.value, rhs.value) {
case is (Void, Void):
return true
case let (lhs as Bool, rhs as Bool):
return lhs == rhs
case let (lhs as Int, rhs as Int):
return lhs == rhs
case let (lhs as Int8, rhs as Int8):
return lhs == rhs
case let (lhs as Int16, rhs as Int16):
return lhs == rhs
case let (lhs as Int32, rhs as Int32):
return lhs == rhs
case let (lhs as Int64, rhs as Int64):
return lhs == rhs
case let (lhs as UInt, rhs as UInt):
return lhs == rhs
case let (lhs as UInt8, rhs as UInt8):
return lhs == rhs
case let (lhs as UInt16, rhs as UInt16):
return lhs == rhs
case let (lhs as UInt32, rhs as UInt32):
return lhs == rhs
case let (lhs as UInt64, rhs as UInt64):
return lhs == rhs
case let (lhs as Float, rhs as Float):
return lhs == rhs
case let (lhs as Double, rhs as Double):
return lhs == rhs
case let (lhs as String, rhs as String):
return lhs == rhs
case let (lhs as [String: AnyCodable], rhs as [String: AnyCodable]):
return lhs == rhs
case let (lhs as [AnyCodable], rhs as [AnyCodable]):
return lhs == rhs
default:
return false
}
}
}
extension AnyCodable: CustomStringConvertible {
public var description: String {
switch value {
case is Void:
return String(describing: nil as Any?)
case let value as CustomStringConvertible:
return value.description
default:
return String(describing: value)
}
}
}
extension AnyCodable: CustomDebugStringConvertible {
public var debugDescription: String {
switch value {
case let value as CustomDebugStringConvertible:
return "AnyCodable(\(value.debugDescription))"
default:
return "AnyCodable(\(description))"
}
}
}
extension AnyCodable: ExpressibleByNilLiteral {}
extension AnyCodable: ExpressibleByBooleanLiteral {}
extension AnyCodable: ExpressibleByIntegerLiteral {}
extension AnyCodable: ExpressibleByFloatLiteral {}
extension AnyCodable: ExpressibleByStringLiteral {}
extension AnyCodable: ExpressibleByArrayLiteral {}
extension AnyCodable: ExpressibleByDictionaryLiteral {}
| 32.768421 | 121 | 0.608416 |
162e1524591ba8f0c65f5b4ae3c5e2a083e0428a | 2,376 | //
// LexisView.swift
// Lexis
//
// Created by Wellington Moreno on 9/20/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Foundation
import RedRomaColors
import UIKit
@IBDesignable class LexisView: UIView
{
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override func prepareForInterfaceBuilder()
{
updateView()
}
@IBInspectable var circular: Bool = false
{
didSet
{
updateView()
}
}
@IBInspectable var borderThickness: CGFloat = 0
{
didSet
{
updateView()
}
}
@IBInspectable var borderColor: UIColor = UIColor.black
{
didSet
{
updateView()
}
}
@IBInspectable var shouldRasterize: Bool = false
{
didSet
{
updateView()
}
}
@IBInspectable var shadowOffset: CGSize = CGSize(width: 3, height: 0)
{
didSet
{
updateView()
}
}
@IBInspectable var shadowColor: UIColor = Colors.fromRGBA(red: 0, green: 0, blue: 0, alpha: 50)
{
didSet
{
updateView()
}
}
@IBInspectable var shadowBlur: CGFloat = 4
{
didSet
{
updateView()
}
}
private func updateView()
{
if circular
{
let radius = self.frame.width / 2
layer.cornerRadius = radius
layer.masksToBounds = true
}
else
{
layer.cornerRadius = 0
layer.masksToBounds = false
}
layer.borderWidth = borderThickness
layer.borderColor = borderColor.cgColor
layer.shouldRasterize = shouldRasterize
layer.shadowOffset = shadowOffset
layer.shadowColor = shadowColor.cgColor
if shouldRasterize
{
layer.rasterizationScale = UIScreen.main.scale
}
}
override func layoutSubviews()
{
super.layoutSubviews()
updateView()
}
override func draw(_ rect: CGRect)
{
super.draw(rect)
updateView()
}
}
| 18.418605 | 99 | 0.509259 |
72539846c1b283f2ac1243bf4de35ca72f51fae0 | 2,746 | //
// SceneDelegate.swift
// NextWatch
//
// Created by حمد الحريصي on 24/12/2021.
//
import UIKit
import Firebase
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let window = window {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let _ = Auth.auth().currentUser {
let navigationController = storyboard.instantiateViewController(withIdentifier: "HomeNavigationController") as! UITabBarController
window.rootViewController = navigationController
window.makeKeyAndVisible()
}
}
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.587302 | 147 | 0.697742 |
1e1926fa9bf174ea78493fb530150bf68b038011 | 888 | //
// NewsTests.swift
// NewsTests
//
// Created by Ravi Theja on 16/03/20.
// Copyright © 2020 Idlebrains. All rights reserved.
//
import XCTest
@testable import News
class NewsTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.371429 | 111 | 0.648649 |
d69c537fc0f77e7ae311256a9ea94cd6b98ee099 | 1,791 | //
// getRemoteFilelist.swift
// RsyncOSX
//
// Created by Thomas Evensen on 21.05.2017.
// Copyright © 2017 Thomas Evensen. All rights reserved.
//
import Foundation
final class GetRemoteFileListingsArguments {
private var config: Configuration?
private var args: [String]?
private func remotearguments(recursive: Bool) {
if let config = config {
if config.sshport != nil {
let eparam: String = "-e"
let sshp: String = "ssh -p"
args?.append(eparam)
args?.append(sshp + String(config.sshport!))
} else {
let eparam: String = "-e"
let ssh: String = "ssh"
args?.append(eparam)
args?.append(ssh)
}
if recursive {
args?.append("-r")
}
args?.append("--list-only")
if config.offsiteServer.isEmpty == false {
args?.append(config.offsiteUsername + "@" + config.offsiteServer + ":" + config.offsiteCatalog)
} else {
args?.append(":" + config.offsiteCatalog)
}
}
}
private func localarguments(recursive: Bool) {
if recursive {
args?.append("-r")
}
args?.append("--list-only")
args?.append(config?.offsiteCatalog ?? "")
}
func getArguments() -> [String]? {
return args
}
init(config: Configuration?, recursive: Bool) {
guard config != nil else { return }
self.config = config
args = [String]()
if config?.offsiteServer.isEmpty == false {
remotearguments(recursive: recursive)
} else {
localarguments(recursive: recursive)
}
}
}
| 28.428571 | 111 | 0.522055 |
bfcd645ec03a66864e228a6ab41d7d30366b2ae1 | 507 |
import UIKit
struct Constants {
static let googleSDKClientId1 = "1033599919942-sag920l97oi1tlitu9j"
static let googleSDKClientId2 = "51mc3nlvrq16i.apps.googleusercontent.com"
static let grayColor = UIColor(red: 54/255, green: 54/255, blue: 54/255, alpha: 1.0)
}
extension Notification.Name {
static let showCalendar = Notification.Name("ShowCalendar")
static let openImagePicker = Notification.Name("OpenImagePicker")
static let setEventDate = Notification.Name("SetEventDate")
}
| 33.8 | 88 | 0.761341 |
0e48c7d79cf8d04be0440e14c772d9bcf954a9e5 | 2,031 | //
// BaseCollectionSection.swift
// EasyList
//
// Created by Red10 on 12/04/2019.
// Copyright © 2019 mathieu lecoupeur. All rights reserved.
//
import UIKit
open class BaseCollectionSection: NSObject, CollectionItemLayoutProvider {
typealias ReturnType = CollectionSource
public weak var source: CollectionSource?
var items: [CollectionItemType] = []
@discardableResult
public func addItem(_ item: CollectionItemType, at index: Int? = nil) -> BaseCollectionSection {
item.setSection?(section: self)
let itemIndex = index ?? items.count
items.insert(item, at: itemIndex)
source?.addItem(at: itemIndex, in: self)
return self
}
@discardableResult
public func addItem<ItemTypeToInsert: CollectionItemType>(_ item: ItemTypeToInsert, after predicate: (CollectionItemType, ItemTypeToInsert) -> Bool) -> BaseCollectionSection {
item.setSection?(section: self)
var itemIndex = 0
for (currentIndex, currentItem) in items.enumerated() {
if predicate(currentItem, item) {
itemIndex = max(itemIndex, currentIndex + 1)
}
}
items.insert(item, at: itemIndex)
source?.addItem(at: itemIndex, in: self)
return self
}
@discardableResult
public func deleteItem(at index: Int) -> BaseCollectionSection {
items.remove(at: index)
source?.deleteItem(at: index, in :self)
return self
}
@discardableResult
public func deleteAllItems(where predicate: (CollectionItemType) -> Bool) -> BaseCollectionSection {
items.removeAll(where: predicate)
return self
}
@discardableResult
public func deleteAllItems() -> BaseCollectionSection {
items.removeAll()
return self
}
public func getItem(at index: Int) -> CollectionItemType? {
return items[safe: index]
}
internal func itemCount() -> Int {
return items.count
}
}
| 29.867647 | 179 | 0.643525 |
9ba69a259cb0cfd960928122e3f04e7cac8c7994 | 370 | //
// Created by mac on 2019-05-27.
// Copyright (c) 2019 A. All rights reserved.
//
import Foundation
import RxRequester
struct TimeoutHandler: NSErrorHandler {
var supportedErrors: [Int] = [
NSURLErrorTimedOut
]
func handle(error: NSError, presentable: Presentable?) {
presentable?.showError(error: error.localizedDescription)
}
}
| 19.473684 | 65 | 0.686486 |
64bf04a02df5dd130c350778e5beae4d00aaf229 | 264 | //
// URLRequest.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 6/29/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
public protocol URLRequest {
var url: URL { get }
var timeoutInterval: TimeInterval { get }
}
| 17.6 | 52 | 0.651515 |
287bc3a5121380632a166eb11646a43664c95ac3 | 1,022 | //
// ReachabilityManager.swift
// SWFrame
//
// Created by 杨建祥 on 2020/4/6.
//
import UIKit
import RxSwift
import RxCocoa
import Alamofire
public let reachSubject = BehaviorRelay<NetworkReachabilityManager.NetworkReachabilityStatus>.init(value: .unknown)
final public class ReachabilityManager {
public static let shared = ReachabilityManager()
let network = NetworkReachabilityManager.default
init() {
}
deinit {
}
func start() {
self.network?.startListening(onUpdatePerforming: { status in
logger.print("网络状态: \(status)", module: .swframe)
reachSubject.accept(status)
})
}
}
extension NetworkReachabilityManager.NetworkReachabilityStatus: CustomStringConvertible {
public var description: String {
switch self {
case .unknown: return "未知网络"
case .notReachable: return "网络不可达"
case let .reachable(type): return type == .cellular ? "cellular" : "wifi"
}
}
}
| 21.744681 | 115 | 0.652642 |
e05180258351f313b016eb3df0badb597180fbbd | 18,092 |
import Foundation
import UserNotifications
class HypePubSub
{
// Members
var ownSubscriptions = SubscriptionsList()
var managedServices = ServiceManagersList()
// Private
private static let HYPE_PUB_SUB_LOG_PREFIX = HpsConstants.LOG_PREFIX + "<HypePubSub> "
private let network = Network.getInstance()
private var notificationId = 0
private static let hps = HypePubSub() // Early loading to avoid thread-safety issues
public static func getInstance() -> HypePubSub {
return hps
}
//////////////////////////////////////////////////////////////////////////////
// Request Issuing
//////////////////////////////////////////////////////////////////////////////
func issueSubscribeReq(serviceName: String) -> Bool
{
let serviceKey = HpsGenericUtils.hash(ofString: serviceName)
let managerClient = network.determineClientResponsibleForService(withKey: serviceKey)
let wasSubscriptionAdded = ownSubscriptions.addSubscription(Subscription(withName: serviceName, withManager: managerClient!))
if(!wasSubscriptionAdded) {
return false
}
updateSubscriptionsUI()
if(HpsGenericUtils.areClientsEqual(network.ownClient!, managerClient!)) {
HypePubSub.printIssueReqToHostInstanceLog("Subscribe", serviceName)
self.processSubscribeReq(serviceKey, network.ownClient!.instance) // bypass protocol manager
}
else{
_ = Protocol.sendSubscribeMsg(serviceKey, (managerClient?.instance)!)
}
return true
}
func issueUnsubscribeReq(serviceName: String) -> Bool
{
let serviceKey = HpsGenericUtils.hash(ofString: serviceName)
let managerClient = network.determineClientResponsibleForService(withKey: serviceKey)
let wasSubscriptionRemoved = ownSubscriptions.removeSubscription(withServiceName: serviceName)
if(!wasSubscriptionRemoved) {
return false
}
updateSubscriptionsUI()
if(HpsGenericUtils.areClientsEqual(network.ownClient!, managerClient!)) {
HypePubSub.printIssueReqToHostInstanceLog("Unsubscribe", serviceName)
self.processUnsubscribeReq(serviceKey, network.ownClient!.instance) // bypass protocol manager
}
else {
_ = Protocol.sendUnsubscribeMsg(serviceKey, (managerClient?.instance)!)
}
return true
}
func issuePublishReq(serviceName: String, msg: String)
{
let serviceKey = HpsGenericUtils.hash(ofString: serviceName)
let managerClient = network.determineClientResponsibleForService(withKey: serviceKey)
if(HpsGenericUtils.areClientsEqual(network.ownClient!, managerClient!)) {
HypePubSub.printIssueReqToHostInstanceLog("Publish", serviceName)
self.processPublishReq(serviceKey, msg) // bypass protocol manager
}
else {
_ = Protocol.sendPublishMsg(serviceKey, (managerClient?.instance)!, msg)
}
}
//////////////////////////////////////////////////////////////////////////////
// Request Processing
//////////////////////////////////////////////////////////////////////////////
func processSubscribeReq(_ serviceKey: Data, _ requesterInstance: HYPInstance)
{
SyncUtils.lock(obj: self)
{
let managerClient = network.determineClientResponsibleForService(withKey: serviceKey)
if( !HpsGenericUtils.areClientsEqual(managerClient!, network.ownClient!))
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Another instance should be responsible for the service 0x%@: %@",
BinaryUtils.toHexString(data: serviceKey),
HpsGenericUtils.getLogStr(fromClient: managerClient!)))
return
}
var serviceManager = self.managedServices.findServiceManager(withKey: serviceKey)
if(serviceManager == nil ) // If the service does not exist we create it.
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Processing Subscribe request for non-existent ServiceManager 0x%@ ServiceManager will be created.",
BinaryUtils.toHexString(data: serviceKey)))
_ = self.managedServices.addServiceManager(ServiceManager(fromServiceKey: serviceKey))
updateServiceManagersUI()
serviceManager = self.managedServices.getLast()
}
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Adding instance %@ to the list of subscribers of the service 0x%@",
HpsGenericUtils.getLogStr(fromHYPInstance: requesterInstance),
BinaryUtils.toHexString(data: serviceKey)))
_ = serviceManager!.subscribers.addClient(Client(fromHYPInstance:requesterInstance))
updateSubscribersUI(fromServiceManager: serviceManager!)
}
}
func processUnsubscribeReq(_ serviceKey: Data, _ requesterInstance: HYPInstance)
{
SyncUtils.lock(obj: self)
{
let serviceManager = self.managedServices.findServiceManager(withKey: serviceKey)
if(serviceManager == nil) // If the service does not exist nothing is done
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Processing Unsubscribe request for non-existent ServiceManager 0x%@. Nothing will be done",
BinaryUtils.toHexString(data: serviceKey)))
return
}
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Removing instance %@ from the list of subscribers of the service 0x%@",
HpsGenericUtils.getLogStr(fromHYPInstance: requesterInstance),
BinaryUtils.toHexString(data: serviceKey)))
_ = serviceManager!.subscribers.removeClient(withHYPInstance: requesterInstance)
updateSubscribersUI(fromServiceManager: serviceManager!)
if(serviceManager!.subscribers.count() == 0) { // Remove the service if there is no subscribers
_ = self.managedServices.removeServiceManager(withKey: serviceKey)
updateServiceManagersUI()
}
}
}
func processPublishReq(_ serviceKey: Data, _ msg: String)
{
SyncUtils.lock(obj: self)
{
let serviceManager = self.managedServices.findServiceManager(withKey: serviceKey)
if(serviceManager == nil)
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Processing Publish request for non-existent ServiceManager 0x%@. Nothing will be done",
BinaryUtils.toHexString(data: serviceKey)))
return
}
for i in 0..<serviceManager!.subscribers.count()
{
let client = serviceManager?.subscribers.get(i)
if(client == nil){
continue
}
if(HpsGenericUtils.areClientsEqual(network.ownClient!, client!))
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Publishing info from service 0x%@ to Host instance",
BinaryUtils.toHexString(data: serviceKey)))
self.processInfoMsg(serviceKey, msg)
}
else
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Publishing info from service 0x%@ to %@",
BinaryUtils.toHexString(data: serviceKey),
HpsGenericUtils.getLogStr(fromHYPInstance: client!.instance)))
_ = Protocol.sendInfoMsg(serviceKey, client!.instance, msg)
}
}
}
}
func processInfoMsg(_ serviceKey: Data, _ msg: String)
{
let subscription = ownSubscriptions.findSubscription(withServiceKey: serviceKey)
if(subscription == nil){
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Info received from the unsubscribed service 0x%@: %@",
BinaryUtils.toHexString(data: serviceKey), msg))
return
}
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let msgWithTimeStamp = formatter.string(from: now) + ": " + msg
subscription!.receivedMsg.insert(msgWithTimeStamp, at: 0)
displayNotification(title: subscription!.serviceName, msg: msg)
updateMessagesUI(fromServiceName: subscription!.serviceName)
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Info received from the subscribed service '%@': %@",
subscription!.serviceName, msg))
}
func updateManagedServices()
{
SyncUtils.lock(obj: self)
{
var toRemove = [Data]()
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Executing updateManagedServices (%i services managed)",
self.managedServices.count()))
for i in 0..<self.managedServices.count()
{
let managedService = managedServices.get(i)
// Check if a new Hype client with a closer key to this service key has appeared. If this happens
// we remove the service from the list of managed services of this Hype client.
let newManagerClient = network.determineClientResponsibleForService(withKey: managedService!.serviceKey)
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Analyzing ServiceManager from service 0x%@",
BinaryUtils.toHexString(data: managedService!.serviceKey)))
if( !HpsGenericUtils.areClientsEqual(newManagerClient!, network.ownClient!))
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "The service 0x%@ will be managed by %@. ServiceManager will be removed",
BinaryUtils.toHexString(data: managedService!.serviceKey),
HpsGenericUtils.getLogStr(fromClient: newManagerClient!)))
toRemove.append((managedService?.serviceKey)!)
}
}
for i in 0..<toRemove.count{
_ = self.managedServices.removeServiceManager(withKey: toRemove[i])
updateServiceManagersUI()
}
}
}
func updateOwnSubscriptions()
{
SyncUtils.lock(obj: self)
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Executing updateOwnSubscriptions (%i subscriptions)",
self.ownSubscriptions.count()))
for i in 0..<self.ownSubscriptions.count()
{
let subscription = ownSubscriptions.get(i)
let newManagerClient = network.determineClientResponsibleForService(withKey: subscription!.serviceKey)
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Analyzing subscription %@",
HpsGenericUtils.getLogStr(fromSubscription: subscription!)))
// If there is a node with a closer key to the service key we change the subscription manager
if( !HpsGenericUtils.areClientsEqual(newManagerClient!, subscription!.manager))
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "The manager of the subscribed service '%@' has changed: %@. A new Subscribe message will be issued)",
subscription!.serviceName,
HpsGenericUtils.getLogStr(fromClient: newManagerClient!)))
subscription!.manager = newManagerClient!
if(HpsGenericUtils.areClientsEqual(network.ownClient!, newManagerClient!)) {
self.processSubscribeReq((subscription?.serviceKey)!, network.ownClient!.instance) // bypass protocol manager
}
else {
_ = Protocol.sendSubscribeMsg((subscription?.serviceKey)!, (newManagerClient?.instance)!)
}
}
}
}
}
func removeSubscriptionsFromLostInstance(fromHYPInstance instance: HYPInstance)
{
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Executing removeSubscriptionsFromLostInstance"))
SyncUtils.lock(obj: self)
{
var keysOfServicesToUnsubscribe = [Data]()
for i in 0..<self.managedServices.count(){
keysOfServicesToUnsubscribe.append((managedServices.get(i)?.serviceKey)!)
}
for i in 0..<keysOfServicesToUnsubscribe.count {
processUnsubscribeReq(keysOfServicesToUnsubscribe[i], instance)
}
}
}
//////////////////////////////////////////////////////////////////////////////
// UI Methods
//////////////////////////////////////////////////////////////////////////////
private func displayNotification(title: String, notificationcontent: String, notificationId: String)
{
let content = UNMutableNotificationContent()
content.title = title
content.body = notificationcontent
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let error = error {
LogUtils.log(prefix: HypePubSub.HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Something went wrong when showing the info message notification. Error: %s", error.localizedDescription))
}
})
}
//////////////////////////////////////////////////////////////////////////////
// Logging Methods
//////////////////////////////////////////////////////////////////////////////
static func printIssueReqToHostInstanceLog(_ reqType: String, _ serviceName: String)
{
LogUtils.log(prefix: HYPE_PUB_SUB_LOG_PREFIX,
logMsg: String(format: "Issuing %@ for service '%@' to HOST instance", reqType, serviceName))
}
//////////////////////////////////////////////////////////////////////////////
// UI Update Methods
//////////////////////////////////////////////////////////////////////////////
private func updateSubscriptionsUI()
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: HpsConstants.NOTIFICATION_SUBSCRIPTIONS_VIEW_CONTROLLER),
object: nil, userInfo: nil)
}
private func updateServiceManagersUI()
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: HpsConstants.NOTIFICATION_SERVICE_MANAGERS_VIEW_CONTROLLER),
object: nil, userInfo: nil)
}
private func updateMessagesUI(fromServiceName serviceName: String)
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: HpsConstants.NOTIFICATION_MESSAGES_VIEW_CONTROLLER + serviceName),
object: nil, userInfo: nil)
}
private func updateSubscribersUI(fromServiceManager serviceManager: ServiceManager)
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: HpsConstants.NOTIFICATION_SUBSCRIBERS_VIEW_CONTROLLER + BinaryUtils.toHexString(data: (serviceManager.serviceKey))),
object: nil, userInfo: nil)
}
private func displayNotification(title: String, msg: String)
{
displayNotification(title: title,
notificationcontent: msg,
notificationId: HpsConstants.NOTIFICATIONS_TITLE + String(notificationId))
notificationId = notificationId + 1
}
}
| 46.870466 | 192 | 0.559419 |
ab493ea78733c12f0ab5cb992f17400043dbf150 | 1,440 | //
// Progress+JSON.swift
// XcodesKit
//
// Created by Ruslan Alikhamov on 12.12.2020.
//
import Foundation
extension Progress {
private enum Constants {
static let estimatedTimeRemaining = "estimatedTimeRemaining"
static let throughput = "throughput"
static let totalUnitCount = "totalUnitCount"
static let completedUnitCount = "completedUnitCount"
}
private var serialized : [String : Any?] {
[ Constants.estimatedTimeRemaining : self.estimatedTimeRemaining,
Constants.throughput : self.throughput,
Constants.totalUnitCount : self.totalUnitCount,
Constants.completedUnitCount : self.completedUnitCount ]
}
var base64EncodedJSON : String? {
try? JSONSerialization.data(withJSONObject: self.serialized, options: []).base64EncodedString()
}
func fromBase64Encoded(string : String) {
guard let data = Data(base64Encoded: string) else { return }
guard let object = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else { return }
self.estimatedTimeRemaining = object[Constants.estimatedTimeRemaining] as? TimeInterval
self.throughput = object[Constants.throughput] as? Int
self.totalUnitCount = object[Constants.totalUnitCount] as? Int64 ?? 0
self.completedUnitCount = object[Constants.completedUnitCount] as? Int64 ?? 0
}
}
| 36 | 120 | 0.685417 |
1e06ac73271d7b542c707128c059936a8d9fb2c1 | 267 | //
// Client.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct Client: Codable {
public private(set) var client: String?
public init(client: String?) {
self.client = client
}
}
| 12.714286 | 43 | 0.64794 |
0341732e096cdce8861395681de67c9d0de5226d | 295 | class Permission: Hashable {
var code: String
init(code: String) {
self.code = code
}
static func == (lhs: Permission, rhs: Permission) -> Bool {
return lhs.code == rhs.code
}
func hash(into hasher: inout Hasher) {
hasher.combine(code)
}
}
| 18.4375 | 63 | 0.569492 |
bb7ba8b0b37389945fa09d86b015bab8c46a483f | 567 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "GFGoogleDirection",
products: [
.library(
name: "GFGoogleDirection",
targets: ["GFGoogleDirection"]),
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.8"),
],
targets: [
.target(
name: "GFGoogleDirection",
dependencies: ["Vapor"]),
.testTarget(
name: "GFGoogleDirectionTests",
dependencies: ["GFGoogleDirection"]),
]
)
| 24.652174 | 74 | 0.552028 |
206cd6c5918d89009023e677448674d4396c3c97 | 7,055 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// stablePartition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix
/// of the collection, preserving their relative order, and returns the
/// start of the resulting suffix.
///
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
/// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
internal mutating func stablePartition(
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
switch n {
case 0,
1 where try belongsInSecondPartition(self[subrange.lowerBound]):
return subrange.lowerBound
case 1: return subrange.upperBound
default:
let h = n / 2, i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition(
count: h,
subrange: subrange.lowerBound..<i,
by: belongsInSecondPartition)
let k = try stablePartition(
count: n - h,
subrange: i..<subrange.upperBound,
by: belongsInSecondPartition)
return rotate(subrange: j..<k, toStartAt: i)
}
}
/// Moves all elements satisfying the given predicate into a suffix of the
/// given range, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
///
/// - Parameters:
/// - subrange: The range of elements within this collection to partition.
/// - belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
public mutating func stablePartition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
try stablePartition(
count: count,
subrange: subrange,
by: belongsInSecondPartition)
}
/// Moves all elements satisfying the given predicate into a suffix of this
/// collection, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
///
/// - Parameter belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
try stablePartition(
subrange: startIndex..<endIndex,
by: belongsInSecondPartition)
}
}
//===----------------------------------------------------------------------===//
// partition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
// This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound }
var j = index(after: i)
while j != subrange.upperBound {
if try !belongsInSecondPartition(self[j]) {
swapAt(i, j)
formIndex(after: &i)
}
formIndex(after: &j)
}
return i
}
}
extension MutableCollection where Self: BidirectionalCollection {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var lo = subrange.lowerBound
var hi = subrange.upperBound
// 'Loop' invariants (at start of Loop, all are true):
// * lo < hi
// * predicate(self[i]) == false, for i in startIndex ..< lo
// * predicate(self[i]) == true, for i in hi ..< endIndex
Loop: while true {
FindLo: repeat {
while lo < hi {
if try belongsInSecondPartition(self[lo]) { break FindLo }
formIndex(after: &lo)
}
break Loop
} while false
FindHi: repeat {
formIndex(before: &hi)
while lo < hi {
if try !belongsInSecondPartition(self[hi]) { break FindHi }
formIndex(before: &hi)
}
break Loop
} while false
swapAt(lo, hi)
formIndex(after: &lo)
}
return lo
}
}
//===----------------------------------------------------------------------===//
// partitioningIndex(where:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns the index of the first element in the collection that matches
/// the predicate.
///
/// The collection must already be partitioned according to the predicate.
/// That is, there should be an index `i` where for every element in
/// `collection[..<i]` the predicate is `false`, and for every element
/// in `collection[i...]` the predicate is `true`.
///
/// - Parameter belongsInSecondPartition: A predicate that partitions the
/// collection.
/// - Returns: The index of the first element in the collection for which
/// `predicate` returns `true`.
///
/// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
public func partitioningIndex(
where belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var n = count
var l = startIndex
while n > 0 {
let half = n / 2
let mid = index(l, offsetBy: half)
if try belongsInSecondPartition(self[mid]) {
n = half
} else {
l = index(after: mid)
n -= half + 1
}
}
return l
}
}
| 35.099502 | 80 | 0.595322 |
89d7b61af0af5436ac947548de9b79ca9fa3e2db | 809 |
import PackageDescription
let package = Package(
name: "Jeeves",
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", versions: Version(2,1,0)..<Version(2, 1, .max)),
.Package(url: "https://github.com/PerfectlySoft/Perfect-CURL.git", versions: Version(2,0,0)..<Version(2, 0, .max)),
.Package(url: "https://github.com/StartAppsPe/StartAppsKitExtensions.git", versions: Version(1,0,0)..<Version(1, .max, .max)),
.Package(url: "https://github.com/StartAppsPe/StartAppsKitLogger.git", versions: Version(1,0,0)..<Version(1, .max, .max)),
.Package(url: "https://github.com/StartAppsPe/Jessie.git", versions: Version(2,5,1)..<Version(2, .max, .max)),
.Package(url: "https://github.com/kareman/SwiftShell", "3.0.0-beta")
]
)
| 53.933333 | 134 | 0.66131 |
014c389e44b3af4cf022bedfb4a386e1c10f4f2d | 1,554 | //
// GithubCommunicationTest.swift
// CallistoTest
//
// Created by Patrick Kladek on 12.01.18.
// Copyright © 2018 IdeasOnCanvas. All rights reserved.
//
import XCTest
class GithubCommunicationTests: XCTestCase {
func testGithubCommunication() {
let communicationController = self.communicationController()
let allPRs = communicationController.allPullRequests()
XCTAssertFalse(allPRs.isEmpty)
let settings = self.settingsDictionary()
let branch = settings["branch"]!
guard let pullRequest = try? communicationController.pullRequest(forBranch: branch) else { XCTFail(); fatalError() }
XCTAssertFalse(pullRequest.isEmpty)
}
}
private extension GithubCommunicationTests {
func settingsDictionary() -> [String: String] {
let bundle = Bundle(for: type(of: self))
guard let url = bundle.url(forResource: "githubSettings", withExtension: "plist") else { XCTFail(); fatalError() }
return NSDictionary(contentsOf: url) as? [String: String] ?? [:]
}
func communicationController() -> GitHubCommunicationController {
let settings = self.settingsDictionary()
let username = settings["username"]!
let token = settings["token"]!
let organisation = settings["organisation"]!
let repository = settings["repository"]!
let account = GithubAccount(username: username, token: token)
return GitHubCommunicationController(account: account, organisation: organisation, repository: repository)
}
}
| 31.08 | 124 | 0.69112 |
c18ffc37f50bf1f7977e9dbb52a24b7248dabfe1 | 2,175 | //
// AppDelegate.swift
// CollectionViews
//
// Created by iOS Café on 27/08/2017.
// Copyright © 2017 iOS Café. 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.276596 | 285 | 0.755402 |
899d77c9293b2930249759eaf564611ed744afe6 | 11,786 | //
// ResizableControllerObserver.swift
//
// Created by Arjun Baru on 05/05/20.
// Copyright © 2020 Paytm Money 🚀. All rights reserved.
//
import UIKit
/// Protocol to integrate Resizable Controller model presentation. To be conformed by the modally presented controller
public protocol ResizableControllerPositionHandler: UIViewController {
/// Override this property if you do not want to include intuitive slide up indicator. Disabled by default for non-resizable views controllers.
var shouldShowSlideUpIndication: Bool { get }
/// Override this property to give differnent colour to Slider up indicator. Defaults to darkGrey with alpha 0.5
var sliderBackgroundColor: UIColor { get }
/// Override this property to give initial custom height, calculated from top.
var initialTopOffset: CGFloat { get }
/// Override this property to give custom final height, calculated from top. Resizable controller will change its height from initialTopOffset to finalTopOffset.
var finalTopOffset: CGFloat { get }
/// Override this property to add behaviours to view controller before it changes it size.
/// - Parameter value: new top offset to which view controller will shifted position.
func willMoveTopOffset(value: CGFloat)
/// Override this property to add additional behaviours to view controller after it changes it size.
/// - Parameter value: new top offset after view controller has shifted position
func didMoveTopOffset(value: CGFloat)
}
extension ResizableControllerPositionHandler {
var onView: UIView {
return self.view
}
}
// MARK: Public default Implementation for protocol
public extension ResizableControllerPositionHandler {
func willMoveTopOffset(value: CGFloat) {
if initialTopOffset == finalTopOffset || value > initialTopOffset {
self.dismiss(animated: true, completion: nil)
}
}
var sliderBackgroundColor: UIColor {
UIColor.darkGray.withAlphaComponent(0.5)
}
var initialTopOffset: CGFloat {
return ResizableConstants.maximumTopOffset
}
var finalTopOffset: CGFloat {
return ResizableConstants.maximumTopOffset
}
var shouldShowSlideUpIndication: Bool {
return initialTopOffset != finalTopOffset
}
func didMoveTopOffset(value: CGFloat) {}
}
/// This class is responsible for handling swipe related recoganisation.
/// It provides call backs on to ResizableControllerPositionHandler protocol conformed class once user interacts with the view controller.
/// Refer to ResizableControllerPositionHandler to see what observations can be subscibed
class ResizableControllerObserver: NSObject, UIGestureRecognizerDelegate, UIScrollViewDelegate {
private let panGesture = UIPanGestureRecognizer()
private var viewPosition: SliderPosition = .present
private weak var view: UIView?
private let animationDuration: TimeInterval
weak var delegate: ResizableControllerPositionHandler?
weak var presentingVC: UIViewController?
var estimatedFinalTopOffset = UIScreen.main.bounds.height * 0.08
var estimatedInitialTopOffset = UIScreen.main.bounds.height * 0.55
var presentingVCminY: CGFloat = 0
private var gestureDidEndedState = true
private lazy var slideIndicativeView: UIView = {
let view = UIView()
view.backgroundColor = delegate?.sliderBackgroundColor
view.widthAnchor.constraint(equalToConstant: 55).isActive = true
view.heightAnchor.constraint(equalToConstant: 5).isActive = true
view.layer.cornerRadius = 2
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
init(in view: UIView, duration: TimeInterval = 0.3, delegate: ResizableControllerPositionHandler? = nil) {
self.view = view
self.animationDuration = duration
super.init()
setupDelegate(delegate)
commonInit()
}
private func commonInit() {
setupGestureRecoganisers()
addSliderView()
}
private func setupGestureRecoganisers() {
guard let view = view else { return }
self.panGesture.addTarget(self, action: #selector(handlePan))
self.panGesture.delegate = self
view.addGestureRecognizer(panGesture)
}
fileprivate func setupDelegate(_ delegate: ResizableControllerPositionHandler?) {
self.delegate = delegate
self.estimatedFinalTopOffset = delegate?.finalTopOffset ?? ResizableConstants.maximumTopOffset
self.estimatedInitialTopOffset = delegate?.initialTopOffset ?? ResizableConstants.maximumTopOffset
}
/// handles user's swipe interactions
@objc private func handlePan(_ gestureRecognizer: UIGestureRecognizer) {
guard let currentView = panGesture.view,
gestureRecognizer == panGesture,
let _ = view else { return }
switch panGesture.state {
case .changed:
guard gestureDidEndedState else { return }
switch panGesture.dragDirection(inView: currentView) {
case .upwards where !isHeightEqualToEstimatedHeight:
translate(value: estimatedFinalTopOffset)
case .downwards where isHeightEqualToEstimatedHeight:
translate(value: estimatedInitialTopOffset)
case .downwards:
delegate?.willMoveTopOffset(value: UIScreen.main.bounds.maxY)
delegate?.didMoveTopOffset(value: UIScreen.main.bounds.maxY)
default:
break
}
gestureDidEndedState = false
case .ended, .failed, .cancelled:
gestureDidEndedState = true
default: break
}
}
}
// MARK: PanGesture Delegates
extension ResizableControllerObserver {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let currentView = panGesture.view, gestureRecognizer == panGesture else {
return false
}
switch panGesture.dragDirection(inView: currentView) {
case .upwards where !isHeightEqualToEstimatedHeight:
guard delegate?.initialTopOffset != delegate?.finalTopOffset else { return false }
return true
case .downwards:
return true
case .idle where !isHeightEqualToEstimatedHeight:
return true
default: return false
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard let currentView = gestureRecognizer.view,
let otherView = otherGestureRecognizer.view else {
return false
}
let isPanGesture = gestureRecognizer == panGesture
let isDescendant = otherView.isDescendant(of: currentView)
guard isPanGesture && isDescendant else {
return false
}
guard let scrollView = otherView as? UIScrollView else {
return true
}
return scrollView.contentOffset.y == 0
}
}
// MARK: All About View Transaltion
private extension ResizableControllerObserver {
var isHeightEqualToEstimatedHeight: Bool {
guard let view = view else { return false }
return Int(view.frame.minY) == Int(estimatedFinalTopOffset)
}
/// performs resizable transformation for presented and presenting view controllers
func translate(value: CGFloat) {
delegate?.willMoveTopOffset(value: value)
UIView.animate(withDuration: animationDuration, animations: {
self.view?.frame.origin.y = value
self.presentingViewTransaltion(transaltion: value)
}, completion: { _ in
self.delegate?.didMoveTopOffset(value: value)
self.panGesture.setTranslation(.zero, in: self.view)
})
}
func addSliderView() {
guard let currentView = view, delegate?.shouldShowSlideUpIndication == true else { return }
currentView.addSubview(slideIndicativeView)
NSLayoutConstraint.activate([
slideIndicativeView.centerXAnchor.constraint(equalTo: currentView.centerXAnchor),
slideIndicativeView.topAnchor.constraint(equalTo: currentView.topAnchor, constant: 15)
])
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.addSliderAnimation()
}
}
/// Scales presenting view controller as per translation
func presentingViewTransaltion(transaltion: CGFloat) {
guard let viewController = presentingVC else { return }
self.viewPosition.toggle(on: self.slideIndicativeView)
switch viewController.viewPresentationStyle() {
case .custom where estimatedFinalTopOffset == transaltion:
presentingVCminY = viewController.view.frame.minY
viewController.view.frame.origin.y = estimatedFinalTopOffset - 15
case .custom where estimatedInitialTopOffset == transaltion:
viewController.view.layer.transform = ViewControlerScale.backgroundPopUpScale.transform
viewController.view.frame.origin.y = presentingVCminY
case .default where estimatedFinalTopOffset == transaltion:
presentingVCminY = viewController.view.frame.minY
presentingVC?.view.frame.origin.y = .zero
case .default where transaltion == estimatedInitialTopOffset:
presentingVC?.view.frame.origin.y = presentingVCminY
case .none where estimatedFinalTopOffset == transaltion:
viewController.view.layer.transform = ViewControlerScale.backgroundFullScreenScale.transform
case .none where estimatedInitialTopOffset == transaltion:
viewController.view.layer.transform = ViewControlerScale.backgroundPopUpScale.transform
default:
viewController.view.layer.transform = ViewControlerScale.reset.transform
}
}
/// adds slider bar animation
func addSliderAnimation() {
let group = CAAnimationGroup()
let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = NSValue(cgPoint: CGPoint(x: self.slideIndicativeView.layer.position.x,
y: self.slideIndicativeView.layer.position.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: self.slideIndicativeView.layer.position.x,
y: self.slideIndicativeView.layer.position.y - 6))
let animationForOpactity = CABasicAnimation(keyPath: "opacity")
animationForOpactity.fromValue = 1
animationForOpactity.toValue = 0.7
group.animations = [animation, animationForOpactity]
group.duration = 0.6
group.autoreverses = true
group.repeatCount = 2
group.speed = 2
group.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
self.slideIndicativeView.layer.add(group, forKey: "position")
}
}
// MARK: Pan helper functions to derive swipe direction
extension UIPanGestureRecognizer {
enum DraggingState {
case upwards, downwards, idle
}
func dragDirection(inView view: UIView) -> DraggingState {
let velocity = self.velocity(in: view)
guard abs(velocity.x) < abs(velocity.y) else { return .idle }
return velocity.y < 0 ? .upwards : .downwards
}
}
enum SliderPosition {
case present
case dismiss
mutating func toggle(on view: UIView) {
switch self {
case .present:
view.alpha = 0
self = .dismiss
case .dismiss:
view.alpha = 1
self = .present
}
}
}
| 36.946708 | 165 | 0.685644 |
39b8afa5390f9b14e5a088337ebd8f4dd57e996b | 106 | #if MIXBOX_ENABLE_IN_APP_SERVICES
struct MethodNameContainer: Codable {
let method: String
}
#endif
| 13.25 | 37 | 0.783019 |
56182d1d0678287663b37c5420299ddf726a0d08 | 1,935 | //
// SplashScreenController.swift
// Pee break
//
// Created by Leo Marcotte on 23/02/2019.
// Copyright © 2019 Leo Marcotte. All rights reserved.
//
import UIKit
final class SplashScreenController: RxViewController {
@IBOutlet private weak var backgroundImageView: UIImageView!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
private let viewModel: SplashScreenViewModelInterface
init(with viewModel: SplashScreenViewModelInterface) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: SplashScreenController.bundle)
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupRxBindings()
viewModel.fetchData()
}
}
private extension SplashScreenController {
// *****************************************************************************
// - MARK: View
func setupView() {
navigationController?.navigationBar.isHidden = true
setupActivityIndicator()
}
func setupActivityIndicator() {
activityIndicator.isHidden = true
}
// *****************************************************************************
// - MARK: Rx Bindings
func setupRxBindings() {
bindBackgroundImage()
bindIsLoading()
}
func bindBackgroundImage() {
viewModel.backgroundImage.bind(to: backgroundImageView.rx.image).disposed(by: bag)
}
func bindIsLoading() {
viewModel.isLoading
.map { !$0 }
.bind(to: activityIndicator.rx.isHidden)
.disposed(by: bag)
viewModel.isLoading
.subscribe(onNext: { [weak self] isLoading in
if isLoading {
self?.activityIndicator.startAnimating()
} else {
self?.activityIndicator.stopAnimating()
}
})
.disposed(by: bag)
}
}
| 27.253521 | 90 | 0.570026 |
d636bd0d526e774788d4a96d21a21a5f2d77d1e1 | 4,803 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
/** Represents an entry of a Page.
Defines what specific piece of content should be presented e.g. an Item or ItemList.
Also defines what visual template should be used to render that content.
*/
public class PageEntry: APIModel {
/** The type of PageEntry. Used to help identify what type of content will be presented. */
public enum `Type`: String, Codable, Equatable, CaseIterable {
case itemEntry = "ItemEntry"
case itemDetailEntry = "ItemDetailEntry"
case listEntry = "ListEntry"
case listDetailEntry = "ListDetailEntry"
case userEntry = "UserEntry"
case textEntry = "TextEntry"
case imageEntry = "ImageEntry"
case customEntry = "CustomEntry"
case peopleEntry = "PeopleEntry"
}
/** The unique identifier for a page entry. */
public var id: String
/** The type of PageEntry. Used to help identify what type of content will be presented. */
public var type: `Type`
/** The name of the Page Entry. */
public var title: String
/** Template type used to present the content of the PageEntry. */
public var template: String
/** A map of custom fields defined by a curator for a page entry. */
public var customFields: [String: Any]?
/** The images for the page entry if any.
For example the images of an `ImageEntry`.
*/
public var images: [String: URL]?
/** If 'type' is 'ItemEntry' then this is the item to be represented. */
public var item: ItemSummary?
/** If 'type' is 'ListEntry' or 'UserEntry' then this is the list to be represented. */
public var list: ItemList?
/** If 'type' is 'PeopleEntry' then this is the array of people to present. */
public var people: [Person]?
/** If 'type' is 'TextEntry' then this is the text to be represented. */
public var text: String?
public init(id: String, type: `Type`, title: String, template: String, customFields: [String: Any]? = nil, images: [String: URL]? = nil, item: ItemSummary? = nil, list: ItemList? = nil, people: [Person]? = nil, text: String? = nil) {
self.id = id
self.type = type
self.title = title
self.template = template
self.customFields = customFields
self.images = images
self.item = item
self.list = list
self.people = people
self.text = text
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
id = try container.decode("id")
type = try container.decode("type")
title = try container.decode("title")
template = try container.decode("template")
customFields = try container.decodeAnyIfPresent("customFields")
images = try container.decodeIfPresent("images")
item = try container.decodeIfPresent("item")
list = try container.decodeIfPresent("list")
people = try container.decodeArrayIfPresent("people")
text = try container.decodeIfPresent("text")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(id, forKey: "id")
try container.encode(type, forKey: "type")
try container.encode(title, forKey: "title")
try container.encode(template, forKey: "template")
try container.encodeAnyIfPresent(customFields, forKey: "customFields")
try container.encodeIfPresent(images, forKey: "images")
try container.encodeIfPresent(item, forKey: "item")
try container.encodeIfPresent(list, forKey: "list")
try container.encodeIfPresent(people, forKey: "people")
try container.encodeIfPresent(text, forKey: "text")
}
public func isEqual(to object: Any?) -> Bool {
guard let object = object as? PageEntry else { return false }
guard self.id == object.id else { return false }
guard self.type == object.type else { return false }
guard self.title == object.title else { return false }
guard self.template == object.template else { return false }
guard NSDictionary(dictionary: self.customFields ?? [:]).isEqual(to: object.customFields ?? [:]) else { return false }
guard self.images == object.images else { return false }
guard self.item == object.item else { return false }
guard self.list == object.list else { return false }
guard self.people == object.people else { return false }
guard self.text == object.text else { return false }
return true
}
public static func == (lhs: PageEntry, rhs: PageEntry) -> Bool {
return lhs.isEqual(to: rhs)
}
}
| 39.694215 | 237 | 0.655424 |
d578dbc1c3157bc78be81ebd5086e9303bae72bf | 146 | import XCTest
#if !os(macOS)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(JWTVaporTests.allTests),
]
}
#endif
| 14.6 | 45 | 0.643836 |
d7e7028cc5421a9c174b37658d2e2fd314636004 | 411 | //
// UserPhoneData.swift
// AutoRia Light
//
// Created by Vlad Shchuka on 01.07.2021.
//
import Foundation
// MARK: - UserPhoneData
struct UserPhoneData: Codable, Equatable {
let phoneID, phone: String
enum CodingKeys: String, CodingKey {
case phoneID = "phoneId"
case phone
}
}
extension UserPhoneData {
static let test: UserPhoneData = .init(phoneID: "", phone: "")
}
| 17.869565 | 66 | 0.654501 |
0a642a8e76bfef0370b6f921df044b99275b7d11 | 3,856 | //
// PolymorphDataProvider.swift
// DataMapper
//
// Created by Filip Dolnik on 28.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
public final class PolymorphDataProvider {
private var nameAndKeyOfTypeCache: [ObjectIdentifier: (name: String, key: String)] = [:]
private var keysOfTypeCache: [ObjectIdentifier: Set<String>] = [:]
private var castableFromTypeByNameByKeyCache: [ObjectIdentifier: [String: [String: Polymorphic.Type]]] = [:]
private let syncQueue = DispatchQueue(label: "PolymorphDataProvider_syncQueue")
public init() {
}
public func nameAndKey(of type: Polymorphic.Type) -> (name: String, key: String) {
return syncQueue.sync {
// Used also in serialization (not as a base type).
cache(type: type, throwErrorIfPolymorphicInfoIsNotOverriden: false)
// Value always exists.
return nameAndKeyOfTypeCache[ObjectIdentifier(type)]!
}
}
public func keys(of type: Polymorphic.Type) -> Set<String> {
return syncQueue.sync {
cache(type: type)
// Value always exists.
return keysOfTypeCache[ObjectIdentifier(type)]!
}
}
public func polymorphType(of type: Polymorphic.Type, named name: String, forKey key: String) -> Polymorphic.Type? {
return syncQueue.sync {
cache(type: type)
return castableFromTypeByNameByKeyCache[ObjectIdentifier(type)]?[name]?[key]
}
}
private func cache(type: Polymorphic.Type, throwErrorIfPolymorphicInfoIsNotOverriden: Bool = true) {
precondition(!throwErrorIfPolymorphicInfoIsNotOverriden || type.polymorphicInfo.type == type,
"\(type) does not override polymorphicInfo. Using it as a base polymorphic type is in most cases programming error.")
if nameAndKeyOfTypeCache[ObjectIdentifier(type)] == nil {
addToCache(type: type)
}
}
private func addToCache(type: Polymorphic.Type) {
let identifier = ObjectIdentifier(type)
let polymorphicInfo = type.polymorphicInfo
let isPolymorphicInfoOverriden = polymorphicInfo.type == type
let name = isPolymorphicInfoOverriden ? polymorphicInfo.name : type.defaultName
nameAndKeyOfTypeCache[identifier] = (name: name, key: type.polymorphicKey)
keysOfTypeCache[identifier] = [type.polymorphicKey]
castableFromTypeByNameByKeyCache[identifier] = [name:[type.polymorphicKey:type]]
if isPolymorphicInfoOverriden {
polymorphicInfo.registeredSubtypes.forEach { addSubtypeToCache(for: identifier, subtype: $0) }
}
}
private func addSubtypeToCache(for typeIdentifier: ObjectIdentifier, subtype: Polymorphic.Type) {
cache(type: subtype, throwErrorIfPolymorphicInfoIsNotOverriden: false)
let subtypeIdentifier = ObjectIdentifier(subtype)
let keysOfSubtype = keysOfTypeCache[subtypeIdentifier] ?? []
keysOfTypeCache[typeIdentifier]?.formUnion(keysOfSubtype)
castableFromTypeByNameByKeyCache[subtypeIdentifier]?.forEach { name, dictionary in
dictionary.forEach { key, castableType in
precondition(castableFromTypeByNameByKeyCache[typeIdentifier]?[name]?[key] == nil,
"\(castableType) and \((castableFromTypeByNameByKeyCache[typeIdentifier]?[name]?[key])!) cannot have the same key and name.")
if castableFromTypeByNameByKeyCache[typeIdentifier]?[name] == nil {
castableFromTypeByNameByKeyCache[typeIdentifier]?[name] = [:]
}
castableFromTypeByNameByKeyCache[typeIdentifier]?[name]?[key] = castableType
}
}
}
}
| 43.325843 | 154 | 0.66027 |
e43f99f065cb624bbfd34c1dfeabe69c8b9a3df7 | 4,648 | //
// MyLovcationViewController.swift
// Yanolja
//
// Created by Chunsu Kim on 06/07/2019.
// Copyright © 2019 Chunsu Kim. All rights reserved.
//
import UIKit
import Alamofire
class MyLocationViewController: UIViewController {
var topNaviView = TopNaviView()
var listCollectionView = ListCollectionView()
let notiCenter = NotificationCenter.default
fileprivate let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
detailRegionSearch(searchKeyword: singleTon.searchKeyword, personnel: singleTon.numberOfPeople, requestCheckIn: self.formatter.string(from: singleTon.saveDate[0])+singleTon.checkInTime, requestCheckOut: self.formatter.string(from: singleTon.saveDate[1])+singleTon.checkOutTime, filter: singleTon.filter,category:singleTon.category , completion: {
self.listCollectionView.listSenderData = singleTon.saveDetailSearchList
self.listCollectionView.listMotelData = self.listCollectionView.listSenderData.filter {
$0.category == "모텔"
}
self.listCollectionView.listHotelData = self.listCollectionView.listSenderData.filter {
$0.category == "호텔/리조트"
}
})
navigationController?.isNavigationBarHidden = true
configureViewComponents()
}
override func viewWillAppear(_ animated: Bool) {
moveDetailVC()
topNaviView.selectDateButton.setTitle(singleTon.selectDateButtonCurrentTitle, for: .normal)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
notiCenter.removeObserver(self)
}
private func reloadCollectionView() {
listCollectionView.reloadData()
}
private func configureViewComponents() {
view.addSubview(topNaviView)
view.addSubview(listCollectionView)
listCollectionView.menuTitles = listMenuTitles
listCollectionView.customMenuBar.menuCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .centeredHorizontally)
topNaviView.delegate = self
topNaviView.translatesAutoresizingMaskIntoConstraints = false
listCollectionView.translatesAutoresizingMaskIntoConstraints = false
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
topNaviView.topAnchor.constraint(equalTo: guide.topAnchor),
topNaviView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
topNaviView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
listCollectionView.topAnchor.constraint(equalTo: topNaviView.bottomAnchor),
listCollectionView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
listCollectionView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
listCollectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
])
}
// MARK: - addObserver
private func moveDetailVC(){
notiCenter.addObserver(self, selector: #selector(moveDetailEvent(_:)), name: Notification.Name("moveDetailVC"), object: nil)
}
// MARK: - Action Method
@objc private func moveDetailEvent(_ sender: Any) {
let detailVC = DetailViewController()
present(detailVC, animated: true, completion: nil)
}
}
// MARK: - checkBoxDelegate Extension
extension MyLocationViewController: checkBoxDelegate {
func possibleChkButton() {
if topNaviView.possibleChkButton.isSelected == false {
topNaviView.possibleChkButton.isSelected = true
} else {
topNaviView.possibleChkButton.isSelected = false
}
}
func searchButton() {
let vc = SearchViewController()
vc.modalPresentationStyle = .overCurrentContext
present(vc, animated: true, completion: nil)
}
func backButton() {
navigationController?.popViewController(animated: true)
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
func calendarButton() {
self.present(CalendarViewController(), animated: true)
}
func selectPeopleButton() {
self.present(NumberOfPeopleViewController(), animated: true)
}
func presentFilterViewController() {
self.present(FilterViewController(), animated: true, completion: nil)
}
}
| 36.888889 | 354 | 0.682659 |
621cac2f2760868db76e527c2fc9a02ec1372ab9 | 725 | //
// BaseImageView.swift
// BookStore
//
// Created by Elon on 2021/11/17.
//
import UIKit
class BaseImageView: UIImageView {
override init(image: UIImage?) {
super.init(image: image)
initialize()
}
override init(image: UIImage?, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initialize() {
// Override here
translatesAutoresizingMaskIntoConstraints = false
}
}
| 19.594595 | 66 | 0.633103 |
726ca5a24cb3ef378a7c3535217316c02ab307dc | 10,203 | //
// Created by Erik Little on 3/25/17.
//
import Foundation
import XCTest
@testable import Discord
public class TestDiscordGuild : XCTestCase {
func testCreatingGuildSetsId() {
let guild = DiscordGuild(guildObject: testGuild, client: nil)
XCTAssertEqual(guild.id, 100, "init should set id")
}
func testCreatingGuildSetsName() {
let guild = DiscordGuild(guildObject: testGuild, client: nil)
XCTAssertEqual(guild.name, "Test Guild", "init should set name")
}
func testCreatingGuildSetsDefaultMessageNotifications() {
let guild = DiscordGuild(guildObject: testGuild, client: nil)
XCTAssertEqual(guild.defaultMessageNotifications, 0, "init should set default message notifications")
}
func testCreatingGuildSetsWidgetEnabled() {
tGuild["widget_enabled"] = true
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertTrue(guild.widgetEnabled, "init should set widget enabled")
}
func testCreatingGuildSetsWidgetChannel() {
tGuild["widget_channel_id"] = "200"
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.widgetChannelId, 200, "init should set the widget channel id")
}
func testCreatingGuildSetsIcon() {
tGuild["icon"] = "someicon"
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.icon, "someicon", "init should set icon")
}
func testCreatingGuildSetsLarge() {
tGuild["large"] = true
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertTrue(guild.large, "init should set large")
}
func testCreatingGuildSetsMemberCount() {
tGuild["member_count"] = 20000
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.memberCount, 20000, "init should set member count")
}
func testCreatingGuildSetsMFALevel() {
tGuild["mfa_level"] = 1
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.mfaLevel, 1, "init should set MFA level")
}
func testCreatingGuildSetsOwnerId() {
tGuild["owner_id"] = "601"
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.ownerId, 601, "init should set owner id")
}
func testCreatingGuildSetsRegion() {
tGuild["region"] = "us-east"
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.region, "us-east", "init should set region")
}
func testCreatingGuildSetsSplash() {
tGuild["splash"] = "somesplash"
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.splash, "somesplash", "init should set splash")
}
func testCreatingGuildSetsVerificationLevel() {
tGuild["verification_level"] = 1
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertEqual(guild.verificationLevel, 1, "init should set verification level")
}
func testCreatingGuildSetsUnavailable() {
tGuild["unavailable"] = true
let guild = DiscordGuild(guildObject: tGuild, client: nil)
XCTAssertTrue(guild.unavailable, "init should set unavailable")
}
func testGuildCorrectlyGetsRolesForMember() {
var tMember = testMember
var role2 = testRole
role2["id"] = "401"
role2["name"] = "A new role"
tMember["roles"] = [testRole["id"] as! String, role2["id"] as! String]
let guild = DiscordGuild(guildObject: ["id": "guildid",
"roles": [testRole, role2]
], client: nil)
let member = DiscordGuildMember(guildMemberObject: tMember, guildId: guild.id, guild: guild)
XCTAssertEqual(guild.roles.count, 2, "guild should have two roles")
let roles = guild.roles(for: member)
XCTAssertEqual(roles.count, 2, "guild should find two roles for member")
XCTAssertNotNil(roles.first(where: { $0.id == Snowflake(testRole["id"] as! String)! }), "roles should find testrole")
XCTAssertNotNil(roles.first(where: { $0.id == Snowflake(role2["id"] as! String)! }), "roles should find role2")
}
func testGuildFromObjectCorrectlyCreatesChannelCategory() {
switch guildChannel(fromObject: testGuildChannelCategory, guildID: nil) {
case let channel as DiscordGuildChannelCategory:
XCTAssertEqual(Snowflake(testGuildChannelCategory["id"] as! String), channel.id,
"It should create a guild category id correctly")
default:
XCTFail("It should create a guild category")
}
}
func testGuildFromObjectCorrectlyCreatesTextChannel() {
switch guildChannel(fromObject: testGuildTextChannel, guildID: nil) {
case let channel as DiscordGuildTextChannel:
XCTAssertEqual(Snowflake(testGuildTextChannel["id"] as! String), channel.id,
"It should create a guild text channel id correctly")
default:
XCTFail("It should create a guild text channel")
}
}
func testGuildFromObjectCorrectlyCreatesVoiceChannel() {
switch guildChannel(fromObject: testGuildVoiceChannel, guildID: nil) {
case let channel as DiscordGuildVoiceChannel:
XCTAssertEqual(Snowflake(testGuildVoiceChannel["id"] as! String), channel.id,
"It should create a guild voice channel id correctly")
XCTAssertEqual(testGuildVoiceChannel["bitrate"] as! Int, channel.bitrate,
"It should create a guild voice channel bitrate correctly")
default:
XCTFail("It should create a guild category")
}
}
func testGuildFromObjectCreatesNoChannelOnInvalidType() {
var newChannel = testGuildTextChannel
newChannel["type"] = 200
switch guildChannel(fromObject: newChannel, guildID: nil) {
case .some:
XCTFail("It should not crete a channel if the type is not known")
default:
break
}
}
func testGuildReturnsABasicMemberObjectLazyCreationFails() {
let guild = DiscordGuild(guildObject: tGuild, client: nil)
var tPresence = testPresence
tPresence["status"] = "online"
let presence = DiscordPresence(presenceObject: testPresence, guildId: guild.id)
guild.updateGuild(fromPresence: presence, fillingUsers: true, pruningUsers: false)
XCTAssertEqual(guild.members.count, 1, "It should add a placeholder member")
XCTAssertEqual(guild.members[presence.user.id]?.user.id, presence.user.id, "It should create a basic member")
}
#if PERFTEST
func testCreatingGuildWithALargeNumberOfMembersIsConsistent() {
tGuild["members"] = createGuildMemberObjects(n: 100_000)
var guild: DiscordGuild!
measure {
guild = DiscordGuild(guildObject: self.tGuild, client: nil)
}
XCTAssertEqual(guild.members.count, 100_000, "init should create 100_000 members")
XCTAssertEqual(guild.members[5000]?.user.id, 5000, "init should create members correctly")
}
func testCreatingGuildWithALargeNumberOfPresencesIsConsistent() {
tGuild["presences"] = createPresenceObjects(n: 100_000)
var guild: DiscordGuild!
measure {
guild = DiscordGuild(guildObject: self.tGuild, client: nil)
}
XCTAssertEqual(guild.presences.count, 100_000, "init should create 100_000 presences")
XCTAssertEqual(guild.presences[5000]?.user.id, 5000, "init should create presences correctly")
}
#endif
var tGuild: [String: Any]!
public static var allTests: [(String, (TestDiscordGuild) -> () -> ())] {
var tests = [
("testCreatingGuildSetsId", testCreatingGuildSetsId),
("testCreatingGuildSetsName", testCreatingGuildSetsName),
("testCreatingGuildSetsDefaultMessageNotifications", testCreatingGuildSetsDefaultMessageNotifications),
("testCreatingGuildSetsWidgetEnabled", testCreatingGuildSetsWidgetEnabled),
("testCreatingGuildSetsWidgetChannel", testCreatingGuildSetsWidgetChannel),
("testCreatingGuildSetsIcon", testCreatingGuildSetsIcon),
("testCreatingGuildSetsLarge", testCreatingGuildSetsLarge),
("testCreatingGuildSetsMemberCount", testCreatingGuildSetsMemberCount),
("testCreatingGuildSetsMFALevel", testCreatingGuildSetsMFALevel),
("testCreatingGuildSetsOwnerId", testCreatingGuildSetsOwnerId),
("testCreatingGuildSetsRegion", testCreatingGuildSetsRegion),
("testCreatingGuildSetsSplash", testCreatingGuildSetsSplash),
("testCreatingGuildSetsVerificationLevel", testCreatingGuildSetsVerificationLevel),
("testCreatingGuildSetsUnavailable", testCreatingGuildSetsUnavailable),
("testGuildCorrectlyGetsRolesForMember", testGuildCorrectlyGetsRolesForMember),
("testGuildFromObjectCorrectlyCreatesChannelCategory", testGuildFromObjectCorrectlyCreatesChannelCategory),
("testGuildFromObjectCorrectlyCreatesTextChannel", testGuildFromObjectCorrectlyCreatesTextChannel),
("testGuildFromObjectCorrectlyCreatesVoiceChannel", testGuildFromObjectCorrectlyCreatesVoiceChannel),
("testGuildFromObjectCreatesNoChannelOnInvalidType", testGuildFromObjectCreatesNoChannelOnInvalidType),
("testGuildReturnsABasicMemberObjectLazyCreationFails", testGuildReturnsABasicMemberObjectLazyCreationFails)
]
#if PERFTEST
tests += [
("testCreatingGuildWithALargeNumberOfMembersIsConsistent", testCreatingGuildWithALargeNumberOfMembersIsConsistent),
("testCreatingGuildWithALargeNumberOfPresencesIsConsistent", testCreatingGuildWithALargeNumberOfPresencesIsConsistent),
]
#endif
return tests
}
public override func setUp() {
tGuild = testGuild
}
}
| 38.501887 | 131 | 0.678036 |
ef8d714c62823b59e7db0e35eabac8370eec8089 | 2,792 |
import Foundation
import NeedleFoundation
// swiftlint:disable unused_declaration
private let needleDependenciesHash : String? = nil
// MARK: - Registration
public func registerProviderFactories() {
__DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent") { component in
return EmptyDependencyProvider(component: component)
}
__DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent->FavoritesScreenComponent->MainScreenComponent") { component in
return MainScreenDependency9e402a1f46102151b059Provider(component: component)
}
__DependencyProviderRegistry.instance.registerDependencyProviderFactory(for: "^->RootComponent->FavoritesScreenComponent") { component in
return FavoritesScreenDependency27addd39e085479c7065Provider(component: component)
}
}
// MARK: - Providers
private class MainScreenDependency9e402a1f46102151b059BaseProvider: MainScreenDependency {
var coreDataManager: CoreDataManager {
return rootComponent.coreDataManager
}
var networkManager: NetworkManager {
return rootComponent.networkManager
}
var popupNotificationsManager: PopupNotificationsManager {
return rootComponent.popupNotificationsManager
}
var favoritesScreenViewController: FavoritesScreenView {
return favoritesScreenComponent.favoritesScreenViewController
}
private let favoritesScreenComponent: FavoritesScreenComponent
private let rootComponent: RootComponent
init(favoritesScreenComponent: FavoritesScreenComponent, rootComponent: RootComponent) {
self.favoritesScreenComponent = favoritesScreenComponent
self.rootComponent = rootComponent
}
}
/// ^->RootComponent->FavoritesScreenComponent->MainScreenComponent
private class MainScreenDependency9e402a1f46102151b059Provider: MainScreenDependency9e402a1f46102151b059BaseProvider {
init(component: NeedleFoundation.Scope) {
super.init(favoritesScreenComponent: component.parent as! FavoritesScreenComponent, rootComponent: component.parent.parent as! RootComponent)
}
}
private class FavoritesScreenDependency27addd39e085479c7065BaseProvider: FavoritesScreenDependency {
var coreDataManager: CoreDataManager {
return rootComponent.coreDataManager
}
private let rootComponent: RootComponent
init(rootComponent: RootComponent) {
self.rootComponent = rootComponent
}
}
/// ^->RootComponent->FavoritesScreenComponent
private class FavoritesScreenDependency27addd39e085479c7065Provider: FavoritesScreenDependency27addd39e085479c7065BaseProvider {
init(component: NeedleFoundation.Scope) {
super.init(rootComponent: component.parent as! RootComponent)
}
}
| 41.671642 | 162 | 0.799069 |
fc2657e0da52825583f52c8bfd4784b7b4c0ac03 | 3,438 | //
// Copyright (c) 2018. Uber Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
extension String {
static let doneInit = "_doneInit"
static let `static` = "static"
static let `import` = "import "
static public let `class` = "class"
static let override = "override"
static let mockType = "protocol"
static let unknownVal = "Unknown"
static let any = "Any"
static let anyObject = "AnyObject"
static let fatalError = "fatalError"
static let handlerSuffix = "Handler"
static let observableVarPrefix = "Observable<"
static let rxObservableVarPrefix = "RxSwift.Observable<"
static let rxPublishSubject = "RxSwift.PublishSubject"
static let publishSubject = "PublishSubject"
static let behaviorSubject = "BehaviorSubject"
static let replaySubject = "ReplaySubject"
static let rx = "Rx"
static let observableEmpty = "Observable.empty()"
static let rxObservableEmpty = "RxSwift.Observable.empty()"
static let `required` = "required"
static let `throws` = "throws"
static let `rethrows` = "rethrows"
static let `try` = "try"
static let closureArrow = "->"
static let `typealias` = "typealias"
static let annotationArgDelimiter = ";"
static let rxReplaySubject = "RxSwift.ReplaySubject"
static let replaySubjectAllocSuffix = ".create(bufferSize: 1)"
static let subjectSuffix = "Subject"
static let underlyingVarPrefix = "underlying"
static let setCallCountSuffix = "SetCallCount"
static let callCountSuffix = "CallCount"
static let closureVarSuffix = "Handler"
static let initializerPrefix = "init("
static let `escaping` = "@escaping"
static let autoclosure = "@autoclosure"
static public let mockAnnotation = "@mockable"
static public let poundIf = "#if "
static public let poundEndIf = "#endif"
static public let headerDoc =
"""
///
/// @Generated by Mockolo
///
"""
var isThrowsOrRethrows: Bool {
return self == .throws || self == .rethrows
}
}
extension StringProtocol {
var isNotEmpty: Bool {
return !isEmpty
}
var capitlizeFirstLetter: String {
return prefix(1).capitalized + dropFirst()
}
func shouldParse(with exclusionList: [String]? = nil) -> Bool {
guard hasSuffix(".swift") else { return false }
if let name = components(separatedBy: ".swift").first, let exlist = exclusionList {
for ex in exlist {
if name.hasSuffix(ex) {
return false
}
}
return true
}
return false
}
var displayableComponents: [String] {
let ret = self.replacingOccurrences(of: "?", with: "Optional")
return ret.components(separatedBy: CharacterSet(charactersIn: "<>[] :,()_-.&@#!{}@+\"\'"))
}
}
| 33.705882 | 98 | 0.650669 |
26b28476205507f6594c361dcde55d9226c653e5 | 695 | // swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "ReactiveSwift",
platforms: [
.macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2)
],
products: [
.library(name: "ReactiveSwift", targets: ["ReactiveSwift"]),
],
dependencies: [
.package(url: "https://github.com/Quick/Quick.git", from: "2.0.0"),
.package(url: "https://github.com/Quick/Nimble.git", from: "8.0.0"),
],
targets: [
.target(name: "ReactiveSwift", dependencies: [], path: "Sources"),
.testTarget(name: "ReactiveSwiftTests", dependencies: ["ReactiveSwift", "Quick", "Nimble"]),
],
swiftLanguageVersions: [.v5]
)
| 31.590909 | 100 | 0.595683 |
e20720a3c8d0f0dd063b12627e33c0f03914a9c2 | 3,246 | /*
MIT License
Copyright (c) 2017-2019 MessageKit
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 XCTest
@testable import MessageKit
class AvatarViewTests: XCTestCase {
var avatarView: AvatarView!
override func setUp() {
super.setUp()
avatarView = AvatarView()
avatarView.frame.size = CGSize(width: 30, height: 30)
}
override func tearDown() {
super.tearDown()
avatarView = nil
}
func testNoParams() {
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
// For certain dynamic colors, need to compare cgColor in XCTest
// https://stackoverflow.com/questions/58065340/how-to-compare-two-uidynamicprovidercolor
XCTAssertEqual(avatarView.backgroundColor!.cgColor, UIColor.avatarViewBackground.cgColor)
}
func testWithImage() {
let avatar = Avatar(image: UIImage())
avatarView.set(avatar: avatar)
XCTAssertEqual(avatar.initials, "?")
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
XCTAssertEqual(avatarView.backgroundColor!.cgColor, UIColor.avatarViewBackground.cgColor)
}
func testInitialsOnly() {
let avatar = Avatar(initials: "DL")
avatarView.set(avatar: avatar)
XCTAssertEqual(avatarView.initials, avatar.initials)
XCTAssertEqual(avatar.initials, "DL")
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
XCTAssertEqual(avatarView.backgroundColor!.cgColor, UIColor.avatarViewBackground.cgColor)
}
func testSetBackground() {
XCTAssertEqual(avatarView.backgroundColor!.cgColor, UIColor.avatarViewBackground.cgColor)
avatarView.backgroundColor = UIColor.red
XCTAssertEqual(avatarView.backgroundColor!, UIColor.red)
}
func testGetImage() {
let image = UIImage()
let avatar = Avatar(image: image)
avatarView.set(avatar: avatar)
XCTAssertEqual(avatarView.image, image)
}
func testRoundedCorners() {
let avatar = Avatar(image: UIImage())
avatarView.set(avatar: avatar)
XCTAssertEqual(avatarView.layer.cornerRadius, 15.0)
avatarView.setCorner(radius: 2)
XCTAssertEqual(avatarView.layer.cornerRadius, 2.0)
}
}
| 36.886364 | 97 | 0.717807 |
33551fb0e77002bda92d5c8f1e0dde7cc6c5d91b | 313 | import XCTest
#if !canImport(ObjectiveC)
/// All tests for PallidorGenerator
/// - Returns: List of XCTestCaseEntries
public func allTests() -> [XCTestCaseEntry] {
[
testCase(PallidorGeneratorTests.allTests),
testCase(APITests.allTests),
testCase(SchemaTests.allTests)
]
}
#endif
| 22.357143 | 50 | 0.696486 |
eb06ea3c487178d90f07b49a79d30d96a67ca350 | 792 | //
// PreworkUITestsLaunchTests.swift
// PreworkUITests
//
// Created by Parker C. on 1/7/22.
//
import XCTest
class PreworkUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 24 | 88 | 0.669192 |
6476eddc7566ef31b6fe5c52458030d36afbccc9 | 7,991 | //
// ViewController.swift
// BatteryTester
//
// Created by Rocco Bowling on 6/10/20.
// Copyright © 2020 Rocco Bowling. All rights reserved.
//
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
// Benchmark Results:
// Performed on iPhone 8+
// Screen brightness to minimum
// 100% CPU usage on 2 Efficiency Cores: 100% -> 90% battery in 2884.95 seconds
// 100% CPU usage on 2 Performance Cores: 100% -> 90% battery in 1243.90 seconds
import UIKit
import PlanetSwift
import Anchorage
import Flynn
class ViewController: PlanetViewController {
@objc dynamic var countTotal: UILabel?
@objc dynamic var countPerTimeUnit: UILabel?
@objc dynamic var actorLabel: UILabel?
@objc dynamic var sleepLabel: UILabel?
@objc dynamic var actorSlider: UISlider?
@objc dynamic var sleepSlider: UISlider?
@objc dynamic var coreAffinity: UISegmentedControl?
@objc dynamic var benchButton: UIButton?
@objc dynamic var benchButtonLabel: UILabel?
@objc dynamic var benchResultsLabel: UILabel?
var benchmarkRunning = false
var benchmarkStartTime = ProcessInfo.processInfo.systemUptime
var benchmarkStartBattery = UIDevice.current.batteryLevel
var counters: [Counter] = []
func adjustCounters(_ num: Int) {
guard let sleepSlider = sleepSlider else { return }
guard let coreAffinity = coreAffinity else { return }
let sleepAmount = UInt32(sleepSlider.value)
let qos = Int32(coreAffinity.selectedSegmentIndex)
while counters.count < num {
counters.append(Counter(sleepAmount, qos))
}
while counters.count > num {
counters.removeFirst().beStop()
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Battery Tester"
UIDevice.current.isBatteryMonitoringEnabled = true
persistentViews = false
navigationBarHidden = true
mainBundlePath = "bundle://Assets/Main/Main.xml"
loadPlanetViews { (_, view, parent, prev, _, _) in
view.centerXAnchor == parent.centerXAnchor
switch view {
case self.coreAffinity:
view.centerXAnchor == parent.centerXAnchor
view.widthAnchor == parent.widthAnchor - 40
view.topAnchor == prev!.bottomAnchor + 80
view.heightAnchor == 60
case self.countTotal:
view.topAnchor == parent.topAnchor + 80
view.widthAnchor == parent.widthAnchor - 80
case self.actorLabel, self.sleepLabel:
view.topAnchor == prev!.bottomAnchor + 80
view.widthAnchor == parent.widthAnchor - 80
case self.countPerTimeUnit, self.actorSlider, self.sleepSlider:
view.topAnchor == prev!.bottomAnchor + 10
view.widthAnchor == parent.widthAnchor - 80
case self.benchButton:
view.topAnchor == prev!.bottomAnchor + 16
view.widthAnchor == 280
view.heightAnchor == 60
case self.benchResultsLabel:
view.topAnchor == prev!.bottomAnchor + 16
view.widthAnchor == parent.widthAnchor - 80
view.heightAnchor == 20
default:
view.sizeAnchors == parent.sizeAnchors
return
}
}
guard let countTotal = countTotal else { return }
guard let countPerTimeUnit = countPerTimeUnit else { return }
guard let coreAffinity = coreAffinity else { return }
guard let actorSlider = actorSlider else { return }
guard let sleepSlider = sleepSlider else { return }
guard let actorLabel = actorLabel else { return }
guard let sleepLabel = sleepLabel else { return }
guard let benchButton = benchButton else { return }
guard let benchButtonLabel = benchButtonLabel else { return }
guard let benchResultsLabel = benchResultsLabel else { return }
let updateFrequency = 1.0 / 60.0
var countsPerTime: Int = 0
var countPerTimeTimer: Double = 0
Timer.scheduledTimer(withTimeInterval: updateFrequency, repeats: true) { (_) in
let total = self.counters.reduce(0) { result, counter in result + counter.unsafeCount }
countTotal.text = String(total)
countPerTimeTimer += updateFrequency
if countPerTimeTimer > 1.0 {
countPerTimeUnit.text = "\( (total - countsPerTime)) per second"
countsPerTime = total
countPerTimeTimer -= 1.0
}
UIApplication.shared.isIdleTimerDisabled = self.benchmarkRunning
if self.benchmarkRunning == false {
benchButtonLabel.text = "Start Benchmark"
} else {
let runtime = ProcessInfo.processInfo.systemUptime - self.benchmarkStartTime
let batteryLost = self.benchmarkStartBattery - UIDevice.current.batteryLevel
let batteryLostPercent = self.toPerc(batteryLost)
benchButtonLabel.text = "Benchmark Running..."
benchResultsLabel.text = String(format: "Runtime: %0.2fs Battery Loss: %d%%",
runtime,
batteryLostPercent)
if batteryLostPercent >= 10 {
self.stopBenchmark()
}
}
}
UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0
coreAffinity.insertSegment(withTitle: "Prefer Efficiency", at: 0, animated: false)
coreAffinity.insertSegment(withTitle: "Prefer Performance", at: 1, animated: false)
coreAffinity.insertSegment(withTitle: "Only Efficiency", at: 2, animated: false)
coreAffinity.insertSegment(withTitle: "Only Performance", at: 3, animated: false)
coreAffinity.selectedSegmentIndex = 0
coreAffinity.add(for: .valueChanged) { [weak self] in
guard let self = self else { return }
let qos = Int32(coreAffinity.selectedSegmentIndex)
_ = self.counters.map { $0.beSetCoreAffinity(qos) }
}
actorSlider.add(for: .valueChanged) { [weak self] in
guard let self = self else { return }
let numActors = Int(actorSlider.value)
self.adjustCounters(numActors)
actorLabel.text = "\(numActors) actors"
}
sleepSlider.add(for: .valueChanged) { [weak self] in
guard let self = self else { return }
let sleepAmount = UInt32(sleepSlider.value)
_ = self.counters.map { $0.unsafeSleepAmount = sleepAmount }
sleepLabel.text = "\(sleepAmount) µs sleep"
}
benchButton.add(for: .touchUpInside) { [weak self] in
guard let self = self else { return }
self.toggleBenchmark()
}
}
func startBenchmark() {
benchmarkRunning = true
benchmarkStartTime = ProcessInfo.processInfo.systemUptime
benchmarkStartBattery = UIDevice.current.batteryLevel
}
func stopBenchmark() {
benchmarkRunning = false
print("Battery Benchmark Aborted")
print("=========================")
let runtime = ProcessInfo.processInfo.systemUptime - benchmarkStartTime
print("runtime: \(runtime) seconds")
let battery = UIDevice.current.batteryLevel
print("battery start: \( toPerc(benchmarkStartBattery) )%")
print("battery end: \( toPerc(battery) )%")
print("battery lost: \( toPerc(benchmarkStartBattery - battery) )%")
}
func toggleBenchmark() {
if benchmarkRunning {
stopBenchmark()
} else {
startBenchmark()
}
}
func toPerc(_ value: Float) -> Int {
return Int(value * 100)
}
}
| 36.158371 | 99 | 0.613816 |
e2e65108532f84633a1fab82224e875f328ad6d9 | 5,334 | import Foundation
@testable import ProjectDescription
extension Config {
public static func test(generationOptions: [Config.GenerationOptions] = []) -> Config {
Config(generationOptions: generationOptions)
}
}
extension Workspace {
public static func test(name: String = "Workspace",
projects: [Path] = [],
additionalFiles: [FileElement] = []) -> Workspace {
Workspace(name: name,
projects: projects,
additionalFiles: additionalFiles)
}
}
extension Project {
public static func test(name: String = "Project",
settings: Settings? = nil,
targets: [Target] = [],
additionalFiles: [FileElement] = []) -> Project {
Project(name: name,
settings: settings,
targets: targets,
additionalFiles: additionalFiles)
}
}
extension Target {
public static func test(name: String = "Target",
platform: Platform = .iOS,
product: Product = .framework,
productName: String? = nil,
bundleId: String = "com.some.bundle.id",
infoPlist: InfoPlist = .file(path: "Info.plist"),
sources: SourceFilesList = "Sources/**",
resources: [FileElement] = "Resources/**",
headers: Headers? = nil,
entitlements: Path? = Path("app.entitlements"),
actions: [TargetAction] = [],
dependencies: [TargetDependency] = [],
settings: Settings? = nil,
coreDataModels: [CoreDataModel] = [],
environment: [String: String] = [:]) -> Target {
Target(name: name,
platform: platform,
product: product,
productName: productName,
bundleId: bundleId,
infoPlist: infoPlist,
sources: sources,
resources: resources,
headers: headers,
entitlements: entitlements,
actions: actions,
dependencies: dependencies,
settings: settings,
coreDataModels: coreDataModels,
environment: environment)
}
}
extension TargetAction {
public static func test(name: String = "Action",
tool: String? = nil,
path: Path? = nil,
order: Order = .pre,
arguments: [String] = []) -> TargetAction {
TargetAction(name: name,
tool: tool,
path: path,
order: order,
arguments: arguments)
}
}
extension Scheme {
public static func test(name: String = "Scheme",
shared: Bool = false,
buildAction: BuildAction? = nil,
testAction: TestAction? = nil,
runAction: RunAction? = nil) -> Scheme {
Scheme(name: name,
shared: shared,
buildAction: buildAction,
testAction: testAction,
runAction: runAction)
}
}
extension BuildAction {
public static func test(targets: [TargetReference] = []) -> BuildAction {
BuildAction(targets: targets,
preActions: [ExecutionAction.test()],
postActions: [ExecutionAction.test()])
}
}
extension TestAction {
public static func test(targets: [TestableTarget] = [],
arguments: Arguments? = nil,
config: PresetBuildConfiguration = .debug,
coverage: Bool = true) -> TestAction {
TestAction(targets: targets,
arguments: arguments,
config: config,
coverage: coverage,
preActions: [ExecutionAction.test()],
postActions: [ExecutionAction.test()])
}
}
extension RunAction {
public static func test(config: PresetBuildConfiguration = .debug,
executable: TargetReference? = nil,
arguments: Arguments? = nil) -> RunAction {
RunAction(config: config,
executable: executable,
arguments: arguments)
}
}
extension ExecutionAction {
public static func test(title: String = "Test Script",
scriptText: String = "echo Test",
target: TargetReference? = TargetReference(projectPath: nil, target: "Target")) -> ExecutionAction {
ExecutionAction(title: title,
scriptText: scriptText,
target: target)
}
}
extension Arguments {
public static func test(environment: [String: String] = [:],
launch: [String: Bool] = [:]) -> Arguments {
Arguments(environment: environment,
launch: launch)
}
}
| 37.300699 | 128 | 0.486314 |
fb382f5a1994ade91a0a83c6a9e7e8e2593da660 | 693 | //
// BluetoothViewController.swift
// SwiftStudy
//
// Created by 杨祖亮 on 2020/6/19.
// Copyright © 2020 杨祖亮. All rights reserved.
//
import UIKit
class BluetoothViewController: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 22.354839 | 106 | 0.663781 |
5b2bf54c30b6724312a589edcf6ad6aae36d4d04 | 1,825 | //
// Handler.swift
//
//
// Created by Paul Schmiedmayer on 1/11/21.
//
import NIO
#if compiler(>=5.4) && $AsyncAwait
import _NIOConcurrency
#endif
/// A `Handler` is a `Component` which defines an endpoint and can handle requests.
public protocol Handler: Component {
/// The type that is returned from the `handle()` method when the component handles a request. The return type of the `handle` method is encoded into the response send out to the client.
associatedtype Response: ResponseTransformable
/// A function that is called when a request reaches the `Handler`
#if compiler(>=5.4) && $AsyncAwait
func handle() async throws -> Response
#else
func handle() throws -> Response
#endif
}
extension Handler {
/// By default, `Handler`s don't provide any further content
public var content: some Component {
EmptyComponent()
}
}
// This extensions provides a helper for evaluating the `Handler`'s `handle` function.
// The function hides the syntactic difference between the newly introduced `async`
// version of `handle()` and the traditional, `EventLoopFuture`-based one.
extension Handler {
#if compiler(>=5.4) && $AsyncAwait
internal func evaluate(using eventLoop: EventLoop) -> EventLoopFuture<Response> {
let promise: EventLoopPromise<Response> = eventLoop.makePromise()
promise.completeWithAsync(self.handle)
return promise.futureResult
}
#else
internal func evaluate(using eventLoop: EventLoop) -> EventLoopFuture<Response> {
let promise: EventLoopPromise<Response> = eventLoop.makePromise()
do {
let result = try self.handle()
promise.succeed(result)
} catch {
promise.fail(error)
}
return promise.futureResult
}
#endif
}
| 32.017544 | 190 | 0.681096 |
61b0ba539c34f73bdb1383c03b0978f11e5e56ec | 587 | //
// Coin+CoreDataProperties.swift
//
//
// Created by Somogyi Balázs on 2020. 04. 18..
//
//
import Foundation
import CoreData
extension Coin {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Coin> {
return NSFetchRequest<Coin>(entityName: "Coin")
}
@NSManaged public var collected: Bool
@NSManaged public var discount: Double
@NSManaged public var fileName: String?
@NSManaged public var image: URL?
@NSManaged public var location: String?
@NSManaged public var name: String?
@NSManaged public var project: Project?
}
| 20.964286 | 71 | 0.689949 |
092dff74a00f125c3e98482e531cfc5964621d47 | 2,732 | //
// ServiceScannerTests.swift
// SwiftIO
//
// Created by Jonathan Wight on 5/16/16.
// Copyright © 2016 schwa.io. All rights reserved.
//
import XCTest
@testable import SwiftIO
class ServiceScannerTests: XCTestCase {
func testIPV4Address1() {
let scanner = NSScanner(string: "255.255.255.255")
var address: String?
let result = scanner.scanIPV4Address(&address)
XCTAssertTrue(result)
XCTAssertTrue(scanner.atEnd)
XCTAssertEqual(address, "255.255.255.255")
}
func testIPV4Address2() {
let scanner = NSScanner(string: "X.255.255.255")
var address: String?
let result = scanner.scanIPV4Address(&address)
XCTAssertFalse(result)
XCTAssertNil(address)
}
func testDomain() {
let scanner = NSScanner(string: "test-domain.apple.com")
var address: String?
let result = scanner.scanDomain(&address)
XCTAssertTrue(result)
XCTAssertTrue(scanner.atEnd)
XCTAssertEqual(address, "test-domain.apple.com")
}
func testDomainLocal() {
let scanner = NSScanner(string: "domain.local.")
var address: String?
let result = scanner.scanDomain(&address)
XCTAssertTrue(result)
XCTAssertTrue(scanner.atEnd)
XCTAssertEqual(address, "domain.local.")
}
func testDomainBad() {
let scanner = NSScanner(string: ".apple.com")
var address: String?
let result = scanner.scanDomain(&address)
XCTAssertFalse(result)
XCTAssertNil(address)
}
func testScanAddressGood() {
let inputs:[(String, String?, String?)] = [
("[::ffff:0.0.0.0]:14550", "::ffff:0.0.0.0", "14550"),
("[::ffff:0.0.0.0]", "::ffff:0.0.0.0", nil),
("0.0.0.0:14550", "0.0.0.0", "14550"),
("0.0.0.0", "0.0.0.0", nil),
("localhost", "localhost", nil),
// ("localhost:14550", "localhost", "14550"),
]
for input in inputs {
var address: String?
var port: String?
let result = scanAddress(input.0, address: &address, port: &port)
XCTAssertTrue(result)
XCTAssertEqual(address, input.1)
XCTAssertEqual(port, input.2)
}
}
func testScanAddressBad() {
let inputs = [
"::ffff:0.0.0.0",
]
for input in inputs {
var address: String? = nil
var port: String? = nil
let result = scanAddress(input, address: &address, port: &port)
XCTAssertFalse(result)
XCTAssertNil(address)
XCTAssertNil(port)
}
}
}
| 27.59596 | 77 | 0.561859 |
61ca2d6b989976d029bdd207836448f5f16e7691 | 69 | public struct Assertion<Subject> {
public let subject: Subject
}
| 17.25 | 34 | 0.73913 |
abc9d5cc045471e48ff386f15f28ee94cbca218a | 2,469 | //
// SettingsPresenter.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2018 Stanwood GmbH (www.stanwood.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
protocol SettingsViewable: class {
}
class SettingsPresenter {
typealias DataSource = SettingsDataSource
typealias Delegate = SettingsDelegate
typealias Actionable = SettingsActionable
typealias Parameterable = SettingsParameterable
typealias Viewable = SettingsViewable
var dataSource: SettingsDataSource!
var delegate: SettingsDelegate!
var actions: SettingsActionable
var parameters: SettingsParameterable
weak var view: SettingsViewable?
required init(actions: SettingsActionable, parameters: SettingsParameterable, view: SettingsViewable, settingsData: SettingsData) {
self.actions = actions
self.parameters = parameters
self.view = view
dataSource = SettingsDataSource(modelCollection: settingsData)
delegate = SettingsDelegate(modelCollection: settingsData)
dataSource.presenter = self
delegate.presenter = self
}
func switchDidChange(to value: Bool, for type: SettingsData.Section.SettingType) {
actions.switchDidChange(to: value, for: type)
}
func didTapAction(_ type: SettingsData.Section.SettingType) {
actions.didTap(action: type)
}
}
| 35.782609 | 135 | 0.73066 |
16ab65aea61f19f684acc5620ab566881140d939 | 2,173 | //
// AppDelegate.swift
// NXDrawKit
//
// Created by Nicejinux on 2016. 7. 12..
// Copyright © 2016년 Nicejinux. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.234043 | 285 | 0.753336 |
2f251a570c960f2ea5fd6d547c74be8f461947d0 | 280 | let factoryOne = NumberAbstractFactory.numberFactoryType(.NextStep)
let numberOne = factoryOne.numberFromString("1")
numberOne.stringValue()
let factoryTwo = NumberAbstractFactory.numberFactoryType(.Swift)
let numberTwo = factoryTwo.numberFromString("2")
numberTwo.stringValue()
| 35 | 67 | 0.832143 |
d5dd8fbf0f4fe1ea6f4c580a3d414a45366ca314 | 3,907 | //
// FilteredImageView.swift
// Core Image Explorer
//
// Created by Warren Moore on 1/8/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
import GLKit
import OpenGLES
class FilteredImageView: GLKView, ParameterAdjustmentDelegate {
var ciContext: CIContext!
var filter: CIFilter! {
didSet {
setNeedsDisplay()
}
}
var inputImage: UIImage! {
didSet {
setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame, context: EAGLContext(api: .openGLES2))
clipsToBounds = true
ciContext = CIContext(eaglContext: context)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
clipsToBounds = true
self.context = EAGLContext(api: .openGLES2)
ciContext = CIContext(eaglContext: context)
}
override func draw(_ rect: CGRect) {
if ciContext != nil && inputImage != nil && filter != nil {
let inputCIImage = CIImage(image: inputImage)
filter.setValue(inputCIImage, forKey: kCIInputImageKey)
if filter.outputImage != nil {
clearBackground()
let inputBounds = inputCIImage!.extent
let drawableBounds = CGRect(x: 0, y: 0, width: self.drawableWidth, height: self.drawableHeight)
let targetBounds = imageBoundsForContentMode(inputBounds, toRect: drawableBounds)
ciContext.draw(filter.outputImage!, in: targetBounds, from: inputBounds)
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.setNeedsDisplay()
}
func clearBackground() {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
backgroundColor?.getRed(&r, green: &g, blue: &b, alpha: &a)
glClearColor(GLfloat(r), GLfloat(g), GLfloat(b), GLfloat(a))
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
}
func aspectFit(_ fromRect: CGRect, toRect: CGRect) -> CGRect {
let fromAspectRatio = fromRect.size.width / fromRect.size.height;
let toAspectRatio = toRect.size.width / toRect.size.height;
var fitRect = toRect
if (fromAspectRatio > toAspectRatio) {
fitRect.size.height = toRect.size.width / fromAspectRatio;
fitRect.origin.y += (toRect.size.height - fitRect.size.height) * 0.5;
} else {
fitRect.size.width = toRect.size.height * fromAspectRatio;
fitRect.origin.x += (toRect.size.width - fitRect.size.width) * 0.5;
}
return fitRect.integral
}
func aspectFill(_ fromRect: CGRect, toRect: CGRect) -> CGRect {
let fromAspectRatio = fromRect.size.width / fromRect.size.height;
let toAspectRatio = toRect.size.width / toRect.size.height;
var fitRect = toRect
if (fromAspectRatio > toAspectRatio) {
fitRect.size.width = toRect.size.height * fromAspectRatio;
fitRect.origin.x += (toRect.size.width - fitRect.size.width) * 0.5;
} else {
fitRect.size.height = toRect.size.width / fromAspectRatio;
fitRect.origin.y += (toRect.size.height - fitRect.size.height) * 0.5;
}
return fitRect.integral
}
func imageBoundsForContentMode(_ fromRect: CGRect, toRect: CGRect) -> CGRect {
switch contentMode {
case .scaleAspectFill:
return aspectFill(fromRect, toRect: toRect)
case .scaleAspectFit:
return aspectFit(fromRect, toRect: toRect)
default:
return fromRect
}
}
func parameterValueDidChange(_ parameter: ScalarFilterParameter) {
filter.setValue(parameter.currentValue, forKey: parameter.key)
setNeedsDisplay()
}
}
| 31.508065 | 111 | 0.616842 |
0178810860919a2464a6e19b501f6af4545b9708 | 908 | //
// jing_preworkTests.swift
// jing_preworkTests
//
// Created by WenJing on 1/15/21.
//
import XCTest
@testable import jing_prework
class jing_preworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.705882 | 111 | 0.668502 |
1dc5f4bf1012cd9c07fdc7175eeaf0a22c948e8a | 4,883 | //
// Cornucopia – (C) Dr. Lauer Information Technology
//
import YapDatabase
public extension CornucopiaDB {
class FilteredView<OT: Codable, MT>: View<OT, MT> {
//NOTE: This is - unfortunately - useless here, since subclasses "overriding" protocol typealiases does not work in Swift yet
public typealias TransactionType = YapDatabaseFilteredViewTransaction
public typealias GenericKeyToBool = (String) -> Bool
public typealias GenericObjectToBool<OT> = (OT) -> Bool
public typealias GenericKeyObjectToBool<OT> = (String, OT) -> Bool
public typealias GenericKeyMetaToBool<MT> = (String, MT) -> Bool
public typealias GenericRowToBool<OT, MT> = (String, OT, MT) -> Bool
public enum FilterFunction {
case byKey(closure: GenericKeyToBool)
case byObject(closure: GenericObjectToBool<OT>)
case byKeyObject(closure: GenericKeyObjectToBool<OT>)
case byKeyMeta(closure: GenericKeyMetaToBool<MT>)
case byRow(closure: GenericRowToBool<OT, MT>)
var filtering: YapDatabaseViewFiltering {
switch self {
case .byKey(closure: let closure):
let filtering = YapDatabaseViewFiltering.withKeyBlock { (_, _, _, key) -> Bool in
return closure(key)
}
return filtering
case .byObject(closure: let closure):
let filtering = YapDatabaseViewFiltering.withObjectBlock { (_, _, _, _, object: Any) -> Bool in
guard let object = object as? OT else { fatalError("Internal Error") }
return closure(object)
}
return filtering
case .byKeyObject(closure: let closure):
let filtering = YapDatabaseViewFiltering.withObjectBlock { (_, _, _, key, object: Any) -> Bool in
guard let object = object as? OT else { fatalError("Internal Error") }
return closure(key, object)
}
return filtering
case .byKeyMeta(closure: let closure):
let filtering = YapDatabaseViewFiltering.withMetadataBlock { (_, _, _, key, meta: Any) -> Bool in
guard let meta = meta as? MT else { fatalError("Internal Error") }
return closure(key, meta)
}
return filtering
case .byRow(closure: let closure):
let filtering = YapDatabaseViewFiltering.withRowBlock { (_, _, _, key, object: Any, meta: Any) -> Bool in
guard let object = object as? OT else { fatalError("Internal Error") }
guard let meta = meta as? MT else { fatalError("Internal Error") }
return closure(key, object, meta)
}
return filtering
}
}
}
internal init(name: String, sourceView: CornucopiaDB.View<OT, MT>, persistent: Bool = true, versionTag: String? = nil, filtering: FilterFunction) {
let options: YapDatabaseViewOptions = {
let o = YapDatabaseViewOptions()
o.isPersistent = persistent
return o
}()
let filtering = filtering.filtering
let dbView = YapDatabaseFilteredView(parentViewName: sourceView.name, filtering: filtering, versionTag: versionTag, options: options)
super.init(name: name, dbView: dbView)
}
public func updateFiltering(via connection: YapDatabaseConnection, filtering: FilterFunction) {
connection.readWrite { t in
//FIXME: Overriding typealias does not work, hence we need to explicitly state out transaction type here
guard let vt = self.viewTransaction(for: t) as? YapDatabaseFilteredViewTransaction else { fatalError() }
vt.setFiltering(filtering.filtering, versionTag: String("\(Date().timeIntervalSince1970)"))
}
}
public func updateFiltering(via connection: YapDatabaseConnection, filtering: FilterFunction, then: @escaping( ()->() )) {
connection.asyncReadWrite( { t in
guard let vt = self.viewTransaction(for: t) as? YapDatabaseFilteredViewTransaction else { fatalError() }
//FIXME: Overriding typealias does not work, hence we need to explicitly state out transaction type here
vt.setFiltering(filtering.filtering, versionTag: String("\(Date().timeIntervalSince1970)"))
}, completionBlock: then)
}
}
}
| 50.340206 | 155 | 0.572394 |
4a997d564966d051a75986cc2c67d6cfc53f5104 | 784 | import Foundation
protocol CoreDataControllerProtocol: AnyObject {
func saveContext()
func deleteEntry(entry: Drink)
func addDrinkForDay(beverage: Beverage, volume: Double, timeStamp: Date)
func getDayForDate(date: Date) -> Day?
func getDrinksForDate(date: Date) -> [Drink]
func fetchDays(from date: Date?) -> [Day]
func fetchDrinks(from date: Date?) -> [Drink]
func averageDrink(from date: Date?) -> Double
func averageDaily(from date: Date?) -> Double
func dailyDrinks(from date: Date?) -> Double
func bestDay(from date: Date?) -> Double
func worstDay(from date: Date?) -> Double
func fetchUnlockedAwards() -> [Award]
func unlockAwardWithId(id: Int)
func fetchDrinkCount() -> Int
func deleteAward(award: Award)
}
| 31.36 | 76 | 0.688776 |
62b579012cf8de29dd937222f4984f74f3639db1 | 1,603 | //
// UITableView+Swissors.swift
// Swissors
//
// Created by Ilya Kulebyakin on 8/3/16.
// Copyright © 2016 e-Legion. All rights reserved.
//
import UIKit
public extension UITableView {
func sw_register<Cell: UITableViewCell>(cellType: Cell.Type, bundle: Bundle = .main, tryNib: Bool = true) {
let reuseIdentifier = String(describing: cellType)
if tryNib, let nib = UINib(safeWithName: reuseIdentifier, bundle: bundle) {
register(nib, forCellReuseIdentifier: reuseIdentifier)
} else {
register(cellType, forCellReuseIdentifier: reuseIdentifier)
}
}
func sw_dequeueCell<Cell: UITableViewCell>(of cellType: Cell.Type, for indexPath: IndexPath) -> Cell {
return dequeueReusableCell(withIdentifier: String(describing: cellType), for: indexPath) as! Cell
}
func sw_register<HeaderFooter: UITableViewHeaderFooterView>(headerFooterType: HeaderFooter.Type, bundle: Bundle = .main, tryNib: Bool = true) {
let identifier = String(describing: headerFooterType)
if tryNib, let nib = UINib(safeWithName: identifier, bundle: bundle) {
register(nib, forHeaderFooterViewReuseIdentifier: identifier)
} else {
register(headerFooterType, forHeaderFooterViewReuseIdentifier: identifier)
}
}
func sw_dequeueHeaderFooter<HeaderFooter: UITableViewHeaderFooterView>(of viewType: HeaderFooter.Type) -> HeaderFooter {
return dequeueReusableHeaderFooterView(withIdentifier: String(describing: viewType)) as! HeaderFooter
}
}
| 39.097561 | 147 | 0.694947 |
9b305ac618cb9c082bb534173ebe57e73bed5ada | 1,165 | //
// AppDelegate.swift
// Space Pictures
//
// Created by John Clema on 9/4/18.
// Copyright © 2018 John Clema. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let dataStack = CoreDataStackManager(modelName: "Model")!
private func initialiseUI() {
let todayViewController = PictureOfTheDayViewController()
todayViewController.extendedLayoutIncludesOpaqueBars = true
todayViewController.navigationItem.largeTitleDisplayMode = .always
todayViewController.title = "Space Pictures"
let todayNavigationController = UINavigationController(rootViewController: todayViewController)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = todayNavigationController
self.window?.makeKeyAndVisible()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
initialiseUI()
return true
}
}
| 32.361111 | 144 | 0.734764 |
4830f08450917aeb2d7b1f7c4036f8431a623a93 | 2,373 | //
// MovieRow.swift
// MovieSwift
//
// Created by Thomas Ricouard on 06/06/2019.
// Copyright © 2019 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import SwiftUIFlux
import Backend
import UI
fileprivate let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
struct MovieRow: ConnectedView {
struct Props {
let movie: Movie
}
// MARK: - Init
let movieId: Int
var displayListImage = true
func map(state: AppState, dispatch: @escaping DispatchFunction) -> Props {
Props(movie: state.moviesState.movies[movieId]!)
}
func body(props: Props) -> some View {
HStack {
ZStack(alignment: .topLeading) {
MoviePosterImage(imageLoader: ImageLoaderCache.shared.loaderFor(path: props.movie.poster_path,
size: .medium),
posterSize: .medium)
if displayListImage {
ListImage(movieId: movieId)
}
}
.fixedSize()
.animation(.spring())
VStack(alignment: .leading, spacing: 8) {
Text(props.movie.userTitle)
.titleStyle()
.foregroundColor(.steam_gold)
.lineLimit(2)
HStack {
PopularityBadge(score: Int(props.movie.vote_average * 10))
Text(formatter.string(from: props.movie.releaseDate ?? Date()))
.font(.subheadline)
.foregroundColor(.primary)
.lineLimit(1)
}
Text(props.movie.overview)
.foregroundColor(.secondary)
.lineLimit(3)
.truncationMode(.tail)
}.padding(.leading, 8)
}
.padding(.top, 8)
.padding(.bottom, 8)
.contextMenu{ MovieContextMenu(movieId: self.movieId) }
.redacted(reason: movieId == 0 ? .placeholder : [])
}
}
#if DEBUG
struct MovieRow_Previews : PreviewProvider {
static var previews: some View {
List {
MovieRow(movieId: sampleMovie.id).environmentObject(sampleStore)
}
}
}
#endif
| 29.6625 | 110 | 0.525074 |
200870c84c803973afe07f79dfb39ede78baa81f | 15,872 | //
// MessageDb.swift
// ios
//
// Copyright © 2019 Tinode. All rights reserved.
//
import Foundation
import SQLite
import TinodeSDK
enum MessageDbError: Error {
case dataError(String)
case dbError(String)
}
// The table contains:
// * messages (both synchronized and not yet synchronized with the server).
// * message deletion markers (synchronized and not yet synchronized).
public class MessageDb {
private static let kTableName = "messages"
private let db: SQLite.Connection
public var table: Table
public let id: Expression<Int64>
// Topic ID, references topics.id
public let topicId: Expression<Int64?>
// Id of the originator of the message, references users.id
public let userId: Expression<Int64?>
public let status: Expression<Int?>
public let sender: Expression<String?>
public let ts: Expression<Date?>
public let seq: Expression<Int?>
public let high: Expression<Int?>
public let delId: Expression<Int?>
public let head: Expression<String?>
public let content: Expression<String?>
private let baseDb: BaseDb!
init(_ database: SQLite.Connection, baseDb: BaseDb) {
self.db = database
self.baseDb = baseDb
self.table = Table(MessageDb.kTableName)
self.id = Expression<Int64>("id")
self.topicId = Expression<Int64?>("topic_id")
self.userId = Expression<Int64?>("user_id")
self.status = Expression<Int?>("status")
self.sender = Expression<String?>("sender")
self.ts = Expression<Date?>("ts")
self.seq = Expression<Int?>("seq")
self.high = Expression<Int?>("high")
self.delId = Expression<Int?>("del_id")
self.head = Expression<String?>("head")
self.content = Expression<String?>("content")
}
func destroyTable() {
try! self.db.run(self.table.dropIndex(topicId, ts, ifExists: true))
try! self.db.run(self.table.drop(ifExists: true))
}
func createTable() {
let userDb = baseDb.userDb!
let topicDb = baseDb.topicDb!
// Must succeed.
try! self.db.run(self.table.create(ifNotExists: true) { t in
t.column(id, primaryKey: .autoincrement)
t.column(topicId, references: topicDb.table, topicDb.id)
t.column(userId, references: userDb.table, userDb.id)
t.column(status)
t.column(sender)
t.column(ts)
t.column(seq)
t.column(high)
t.column(delId)
t.column(head)
t.column(content)
})
try! self.db.run(self.table.createIndex(topicId, ts, ifNotExists: true))
}
func insert(topic: TopicProto?, msg: StoredMessage?) -> Int64 {
guard let topic = topic, let msg = msg else {
return -1
}
if msg.msgId > 0 {
// Already saved.
return msg.msgId
}
do {
try db.savepoint("MessageDb.insert") {
guard let tdb = baseDb.topicDb else {
throw MessageDbError.dbError("no topicDb in messageDb insert")
}
if (msg.topicId ?? -1) <= 0 {
msg.topicId = tdb.getId(topic: msg.topic)
}
guard let udb = baseDb.userDb else {
throw MessageDbError.dbError("no userDb in messageDb insert")
}
if (msg.userId ?? -1) <= 0 {
msg.userId = udb.getId(for: msg.from)
}
guard let topicId = msg.topicId, let userId = msg.userId, topicId >= 0, userId >= 0 else {
throw MessageDbError.dataError("Failed to insert row into MessageDb: topicId = \(String(describing: msg.topicId)), userId = \(String(describing: msg.userId))")
}
var status: Int = BaseDb.kStatusUndefined
if let seq = msg.seq, seq > 0 {
status = BaseDb.kStatusSynced
} else {
msg.seq = tdb.getNextUnusedSeq(topic: topic)
status = (msg.status == nil || msg.status == BaseDb.kStatusUndefined) ? BaseDb.kStatusQueued : msg.status!
}
var setters = [Setter]()
setters.append(self.topicId <- topicId)
setters.append(self.userId <- userId)
setters.append(self.status <- status)
setters.append(self.sender <- msg.from)
setters.append(self.ts <- msg.ts)
setters.append(self.seq <- msg.seq)
if let h = msg.head {
setters.append(self.head <- Tinode.serializeObject(h))
}
setters.append(self.content <- msg.content?.serialize())
msg.msgId = try db.run(self.table.insert(setters))
}
return msg.msgId
} catch {
BaseDb.log.error("MessageDb - insert operation failed: %@", error.localizedDescription)
return -1
}
}
func updateStatusAndContent(msgId: Int64, status: Int?, content: Drafty?) -> Bool {
let record = self.table.filter(self.id == msgId)
var setters = [Setter]()
if status != BaseDb.kStatusUndefined {
setters.append(self.status <- status!)
}
if content != nil {
setters.append(self.content <- content!.serialize())
}
if !setters.isEmpty {
do {
return try self.db.run(record.update(setters)) > 0
} catch {
BaseDb.log.error("MessageDb - update status operation failed: msgId = %lld, error = %@", msgId, error.localizedDescription)
}
}
return false
}
func delivered(msgId: Int64, ts: Date?, seq: Int?) -> Bool {
let record = self.table.filter(self.id == msgId)
do {
return try self.db.run(record.update(
self.status <- BaseDb.kStatusSynced,
self.ts <- ts,
self.seq <- seq)) > 0
} catch {
BaseDb.log.error("MessageDb - update delivery operation failed: msgId = %lld, error = %@", msgId, error.localizedDescription)
return false
}
}
// Deletes all messages in a given topic, no exceptions. Use only when deleting the topic.
@discardableResult
func deleteAll(topicId: Int64) -> Bool {
// Delete from messages where topic_id = topicId.
let rows = self.table.filter(self.topicId == topicId)
do {
return try self.db.run(rows.delete()) > 0
} catch {
BaseDb.log.error("MessageDb - deleteAll operation failed: topicId = %lld, error = %@", topicId, error.localizedDescription)
return false
}
}
@discardableResult
func delete(topicId: Int64, deleteId delId: Int?, from loId: Int, to hiId: Int?) -> Bool {
return deleteOrMarkDeleted(topicId: topicId, delId: delId, from: loId, to: hiId, hard: false)
}
@discardableResult
func deleteOrMarkDeleted(topicId: Int64, delId: Int?, inRanges ranges: [MsgRange], hard: Bool) -> Bool {
var success = false
do {
try db.savepoint("MessageDb.deleteOrMarkDeleted-ranges") {
for r in ranges {
if !deleteOrMarkDeleted(topicId: topicId, delId: delId, from: r.lower, to: r.upper, hard: hard) {
throw MessageDbError.dbError("Failed to process: delId \(delId ?? -1) range: \(r)")
}
}
}
success = true
} catch {
BaseDb.log.error("MessageDb - deleteOrMarkDeleted2 with ranges failed: topicId = %lld, error = %@", topicId, error.localizedDescription)
}
return success
}
@discardableResult
func deleteOrMarkDeleted(topicId: Int64, delId: Int?, from loId: Int, to hiId: Int?, hard: Bool) -> Bool {
let delId = delId ?? 0
var startId = loId
var endId = hiId ?? Int.max
if endId == 0 {
endId = startId + 1
}
// 1. Delete all messages in the range.
do {
var updateResult = false
try db.savepoint("MessageDb.deleteOrMarkDeleted-plain") {
// Message selector: all messages in a given topic with seq between fromId and toId [inclusive, exclusive).
let messageSelector = self.table.filter(
self.topicId == topicId && startId <= self.seq && self.seq < endId && self.status <= BaseDb.kStatusSynced)
// Selector of ranges which are fully within the new range.
let rangeDeleteSelector = self.table.filter(
self.topicId == topicId && startId <= self.seq && self.seq < endId && self.status >= BaseDb.kStatusDeletedHard)
// Selector of partially overlapping deletion ranges. Find bounds of existing deletion ranges of the same type
// which partially overlap with the new deletion range.
let statusToConsume =
delId > 0 ? BaseDb.kStatusDeletedSynced :
hard ? BaseDb.kStatusDeletedHard : BaseDb.kStatusDeletedSoft
var rangeConsumeSelector = self.table.filter(
self.topicId == topicId && self.status == statusToConsume
)
if delId > 0 {
rangeConsumeSelector = rangeConsumeSelector.filter(self.delId < delId)
}
let overlapSelector = rangeConsumeSelector.filter(
self.high >= startId && self.seq <= endId
)
try self.db.run(messageSelector.delete())
try self.db.run(rangeDeleteSelector.delete())
// Find the maximum continuous range which overlaps with the current range.
let fullRange = overlapSelector.select([self.seq.min, self.high.max])
if let row = try? db.pluck(fullRange) {
if let newStartId = row[self.seq.min], newStartId < startId {
startId = newStartId
}
if let newEndId = row[self.high.max], newEndId > endId {
endId = newEndId
}
}
// 3. Consume partially overlapped ranges. They will be replaced with the new expanded range.
let overlapSelector2 = rangeConsumeSelector.filter(
self.high >= startId && self.seq <= endId
)
try self.db.run(overlapSelector2.delete())
// 4. Insert new range.
var setters = [Setter]()
setters.append(self.topicId <- topicId)
setters.append(self.delId <- delId)
setters.append(self.seq <- startId)
setters.append(self.high <- endId)
setters.append(self.status <- statusToConsume)
updateResult = try db.run(self.table.insert(setters)) > 0
}
return updateResult
} catch {
BaseDb.log.error("MessageDb - markDeleted operation failed: topicId = %lld, error = %@", topicId, error.localizedDescription)
return false
}
}
func delete(msgId: Int64) -> Bool {
let record = self.table.filter(self.id == msgId)
do {
return try self.db.run(record.delete()) > 0
} catch {
BaseDb.log.error("MessageDb - delete operation failed: msgId = %lld, error = %@", msgId, error.localizedDescription)
return false
}
}
private func readOne(r: Row) -> StoredMessage {
let sm = StoredMessage()
sm.msgId = r[self.id]
sm.topicId = r[self.topicId]
sm.userId = r[self.userId]
sm.status = r[self.status]
sm.from = r[self.sender]
sm.ts = r[self.ts]
sm.seq = r[self.seq]
sm.head = Tinode.deserializeObject(from: r[self.head])
sm.content = Drafty.deserialize(from: r[self.content])
return sm
}
public func query(topicId: Int64?, pageCount: Int, pageSize: Int, descending: Bool = true) -> [StoredMessage]? {
let queryTable = self.table
.filter(self.topicId == topicId)
.order(descending ? self.seq.desc : self.seq.asc)
.limit(pageCount * pageSize)
do {
var messages = [StoredMessage]()
for row in try db.prepare(queryTable) {
let sm = self.readOne(r: row)
messages.append(sm)
}
return messages
} catch {
BaseDb.log.error("MessageDb - query operation failed: topicId = %lld, error = %@", topicId ?? -1, error.localizedDescription)
return nil
}
}
func query(msgId: Int64?) -> StoredMessage? {
guard let msgId = msgId else { return nil }
let record = self.table.filter(self.id == msgId)
if let row = try? db.pluck(record) {
return self.readOne(r: row)
}
return nil
}
func queryDeleted(topicId: Int64?, hard: Bool) -> [MsgRange]? {
guard let topicId = topicId else { return nil }
let status = hard ? BaseDb.kStatusDeletedHard : BaseDb.kStatusDeletedSoft
let queryTable = self.table
.filter(
self.topicId == topicId &&
self.status == status)
.select(self.delId, self.seq, self.high)
.order(self.seq)
do {
var ranges = [MsgRange]()
for row in try db.prepare(queryTable) {
if let low = row[self.seq] {
ranges.append(MsgRange(low: low, hi: row[self.high]))
}
}
return ranges
} catch {
BaseDb.log.error("MessageDb - queryDeleted operation failed: topicId = %lld, error = %@", topicId, error.localizedDescription)
return nil
}
}
func queryUnsent(topicId: Int64?) -> [Message]? {
let queryTable = self.table
.filter(
self.topicId == topicId &&
self.status == BaseDb.kStatusQueued)
.order(self.ts)
do {
var messages = [StoredMessage]()
for row in try db.prepare(queryTable) {
let sm = self.readOne(r: row)
messages.append(sm)
}
return messages
} catch {
BaseDb.log.error("MessageDb - queryUnsent operation failed: topicId = %lld, error = %@", topicId ?? -1, error.localizedDescription)
return nil
}
}
func fetchNextMissingRange(topicId: Int64) -> MsgRange? {
let messages2 = self.table.alias("m2")
let hiQuery = self.table
.join(.leftOuter, messages2,
on: self.table[self.seq] == (messages2[self.high] ?? messages2[self.seq] + 1) && messages2[self.topicId] == topicId)
.filter(self.table[self.topicId] == topicId &&
self.table[self.seq] > 1 &&
messages2[self.seq] == nil)
guard let hi = try? db.scalar(hiQuery.select(self.table[self.seq].max)) else {
// No gap is found.
return nil
}
// Find the first present message with ID less than the 'hi'.
let seqExpr = (self.high - 1) ?? self.seq
let lowQuery = self.table
.filter(self.topicId == topicId && self.seq < hi)
let low: Int
if let low2 = try? db.scalar(lowQuery.select(seqExpr.max)) {
// Low is inclusive thus +1.
low = low2 + 1
} else {
low = 1
}
return MsgRange(low: low, hi: hi)
}
}
| 41.333333 | 179 | 0.55223 |
e6024c5890ca4cbc1143219183777effc302633c | 7,272 | //
// PortalTableView.swift
// PortalView
//
// Created by Guido Marucci Blas on 2/14/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import UIKit
public final class PortalTableView<
MessageType,
RouteType,
CustomComponentRendererType: UIKitCustomComponentRenderer
>: UITableView, UITableViewDataSource, UITableViewDelegate, PullToRefreshable
where CustomComponentRendererType.MessageType == MessageType, CustomComponentRendererType.RouteType == RouteType {
public typealias ComponentRenderer = UIKitComponentRenderer<MessageType, RouteType, CustomComponentRendererType>
public typealias ActionType = Action<RouteType, MessageType>
public let mailbox = Mailbox<ActionType>()
fileprivate let renderer: ComponentRenderer
fileprivate var items: [TableItemProperties<ActionType>] = []
// Used to cache cell actual height after rendering table
// item component. Caching cell height is usefull when
// cells have dynamic height.
fileprivate var cellHeights: [CGFloat?] = []
public init(renderer: ComponentRenderer) {
self.renderer = renderer
super.init(frame: .zero, style: .plain)
self.dataSource = self
self.delegate = self
self.rowHeight = UITableView.automaticDimension
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func setItems(items: [TableItemProperties<ActionType>]) {
self.items = items
self.cellHeights = Array(repeating: .none, count: items.count)
self.estimatedRowHeight = CGFloat(mostProbableItemHeight())
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
let cellRender = itemRender(at: indexPath)
let cellComponent = cellRender.component
let cell = reusableCell(for: cellRender.typeIdentifier)
let componentHeight = cellComponent.layout.height
if componentHeight?.value == .none && componentHeight?.maximum == .none {
print( "WARNING: Table item component with identifier '\(cellRender.typeIdentifier)' does not " +
"specify layout height! You need to either set layout.height.value or layout.height.maximum")
}
// For some reason the first page loads its cells with smaller bounds.
// This forces the cell to have the width of its parent view.
if let width = self.superview?.bounds.width {
let baseHeight = itemBaseHeight(at: indexPath)
cell.bounds.size.width = width
cell.bounds.size.height = baseHeight
cell.contentView.bounds.size.width = width
cell.contentView.bounds.size.height = baseHeight
}
cell.selectionStyle = item.onTap.map { _ in item.selectionStyle.asUITableViewCellSelectionStyle } ?? .none
_ = renderer.render(component: cellComponent, into: cell.contentView)
// After rendering the cell, the parent view returned by rendering the
// item component has the actual height calculated after applying layout.
// This height needs to be cached in order to be returned in the
// UITableViewCellDelegate's method tableView(_,heightForRowAt:)
let actualCellHeight = cell.contentView.subviews[0].bounds.height
cellHeights[indexPath.row] = actualCellHeight
cell.bounds.size.height = actualCellHeight
cell.contentView.bounds.size.height = actualCellHeight
// This is needed to avoid a visual bug
// If the user sets the container's backgroundColor as clear inside a PortalTableViewCell
// the user will see a white background because this class has a default background (.white),
// that is why we need to the the table view cell's background to clear.
cell.backgroundColor = .clear
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return itemBaseHeight(at: indexPath)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = items[indexPath.row]
item.onTap |> { mailbox.dispatch(message: $0) }
}
}
fileprivate extension PortalTableView {
fileprivate func reusableCell(for identifier: String) -> UITableViewCell {
if let cell = dequeueReusableCell(withIdentifier: identifier) {
return cell
} else {
let cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
cell.contentView.getMailbox().forward(to: mailbox)
return cell
}
}
fileprivate func itemRender(at indexPath: IndexPath) -> TableItemRender<ActionType> {
// TODO cache the result of calling renderer. Once the diff algorithm is implemented find a way to only
// replace items that have changed.
// IGListKit uses some library or algorithm to diff array. Maybe that can be used to make the array diff
// more efficient.
//
// https://github.com/Instagram/IGListKit
//
// Check the video of the talk that presents IGListKit to find the array diff algorithm.
// Also there is Dwifft which seems to be based in the same algorithm:
//
// https://github.com/jflinter/Dwifft
//
let item = items[indexPath.row]
return item.renderer(item.height)
}
fileprivate func itemMaxHeight(at indexPath: IndexPath) -> CGFloat {
return CGFloat(items[indexPath.row].height)
}
/// Returns the cached actual height for the item at the given `indexPath`.
/// Actual heights are cached using the `cellHeights` instance variable and
/// are calculated after rending the item component inside the table view cell.
/// This is usefull when cells have dynamic height.
///
/// - Parameter indexPath: The item's index path.
/// - Returns: The cached actual item height.
fileprivate func itemActualHeight(at indexPath: IndexPath) -> CGFloat? {
return cellHeights[indexPath.row]
}
/// Returns the item's cached actual height if available. Otherwise it
/// returns the item's max height.
///
/// - Parameter indexPath: The item's index path.
/// - Returns: the item's cached actual height or its max height.
fileprivate func itemBaseHeight(at indexPath: IndexPath) -> CGFloat {
return itemActualHeight(at: indexPath) ?? itemMaxHeight(at: indexPath)
}
fileprivate func mostProbableItemHeight() -> UInt {
let heightsWithOccurrencies = items.reduce(into: [:]) { counters, item in
counters[item.height, default: 0] += 1
}
if let (maxHeight, _) = heightsWithOccurrencies.max(by: { $0.value < $1.value }) {
return maxHeight
} else {
return 0
}
}
}
| 41.084746 | 116 | 0.665017 |
ac9f7280e2a07b83d8927b7daa5ccd95d8414475 | 1,349 | final class AuthorizationTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
private let isPresentation: Bool
init(isPresentation: Bool) {
self.isPresentation = isPresentation
super.init()
}
func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return kDefaultAnimationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to) else { return }
let animatingVC = isPresentation ? toVC : fromVC
guard let animatingView = animatingVC.view else { return }
let finalFrameForVC = transitionContext.finalFrame(for: animatingVC)
var initialFrameForVC = finalFrameForVC
initialFrameForVC.origin.y += initialFrameForVC.size.height
let initialFrame = isPresentation ? initialFrameForVC : finalFrameForVC
let finalFrame = isPresentation ? finalFrameForVC : initialFrameForVC
animatingView.frame = initialFrame
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: { animatingView.frame = finalFrame },
completion: { _ in
transitionContext.completeTransition(true)
})
}
}
| 37.472222 | 91 | 0.743514 |
569cf341d18bee4db34eca989d9af2700090d814 | 6,542 | //
// ShadowControlView.swift
// iOSDemo
//
// Created by Stan Hu on 2018/5/21.
// Copyright © 2018 Stan Hu. All rights reserved.
//
import UIKit
protocol ShadowVideoControlViewDelegate:class {
func controlView(view:ShadowVideoControlView,pointSliderLocationWithCurrentValue:Float)
func controlView(view:ShadowVideoControlView,draggedPositionWithSlider:UISlider)
func controlView(view:ShadowVideoControlView,draggedPositionExitWithSlider:UISlider)
func controlView(view:ShadowVideoControlView,withLargeButton:UIButton)
}
class ShadowVideoControlView: UIView {
let btnLarge = UIButton(type: UIButton.ButtonType.custom)
var config:[ShadowUIConfig:Any]!
var value:Float{
set{
slider.value = newValue
}
get{
return slider.value
}
}
var minValue:Float{
set{
slider.minimumValue = newValue
}
get{
return slider.minimumValue
}
}
var maxValue:Float{
set{
slider.maximumValue = newValue
}
get{
return slider.maximumValue
}
}
var currentTime:String{
set{
lblTime.text = newValue
}
get{
return lblTime.text!
}
}
var totalTime:String{
set{
lblTotalTime.text = newValue
}
get{
return lblTotalTime.text!
}
}
var bufferValue:Float {
get{
return sliderBuffer.value
}
set{
sliderBuffer.value = newValue
}
}
var tapGesture:UITapGestureRecognizer?
weak var delegate:ShadowVideoControlViewDelegate?
private let lblTime = UILabel()
private let lblTotalTime = UILabel()
private let slider = UISlider() // show the play process
private let sliderBuffer = UISlider() //use to buffer the internet video
var padding = 8
init(frame: CGRect,config:[ShadowUIConfig:Any] = [ShadowUIConfig:Any]()) {
super.init(frame: frame)
self.config = config
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initUI() {
lblTime.textAlignment = .right
lblTime.font = UIFont.systemFont(ofSize: 12)
lblTime.textColor = UIColor.white
addSubview(lblTime)
lblTotalTime.textAlignment = .left
lblTotalTime.font = UIFont.systemFont(ofSize: 12)
lblTotalTime.textColor = UIColor.white
addSubview(lblTotalTime)
sliderBuffer.setThumbImage(UIImage(), for: .normal)
sliderBuffer.isContinuous = true
sliderBuffer.minimumTrackTintColor = UIColor.red
sliderBuffer.minimumValue = 0
sliderBuffer.maximumValue = 1
sliderBuffer.isUserInteractionEnabled = false
addSubview(sliderBuffer)
slider.setThumbImage(#imageLiteral(resourceName: "knob"), for: .normal)
slider.isContinuous = true
tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(ges:)))
slider.addTarget(self, action: #selector(handleSliderPosition(sender:)), for: .valueChanged)
slider.addTarget(self, action: #selector(handleSliderPositionExit(sender:)), for: UIControl.Event.touchUpInside)
slider.addGestureRecognizer(tapGesture!)
slider.maximumTrackTintColor = UIColor.clear
slider.minimumTrackTintColor = UIColor.white
addSubview(slider)
btnLarge.contentMode = .scaleAspectFill
btnLarge.setImage(#imageLiteral(resourceName: "full_screen"), for: .normal)
btnLarge.addTarget(self, action: #selector(hanleFullScreen(sender:)), for: .touchUpInside)
addSubview(btnLarge)
addConstraintsForSubviews()
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil)
}
func addConstraintsForSubviews() {
lblTime.snp.makeConstraints { (m) in
m.left.equalTo(0)
m.bottom.equalTo(-padding)
m.width.equalTo(50)
}
slider.snp.makeConstraints { (m) in
m.left.equalTo(lblTime.snp.right).offset(padding)
m.right.equalTo(lblTotalTime.snp.left).offset(-padding)
m.centerY.equalTo(lblTime)
m.height.equalTo(20)
// if ScreenWidth < ScreenWidth{
// m.width.equalTo(ScreenWidth - padding * 3 - 50 - 50 - 30)
// }
}
lblTotalTime.snp.makeConstraints { (m) in
m.right.equalTo(btnLarge.snp.left).offset(-padding)
m.centerY.equalTo(lblTime)
m.width.equalTo(50)
}
var needHideBtnLarge = false
if config.keys.contains(ShadowUIConfig.HideFullScreenButton){
if let item = config[ShadowUIConfig.HideFullScreenButton] as? Bool{
needHideBtnLarge = item
}
}
btnLarge.snp.makeConstraints { (m) in
m.centerY.equalTo(lblTime)
m.width.height.equalTo(needHideBtnLarge ? 0 : 30)
m.right.equalTo( needHideBtnLarge ? 0 : -padding)
}
sliderBuffer.snp.makeConstraints { (m) in
m.edges.equalTo(slider)
}
layoutIfNeeded()
}
@objc func handleTap(ges:UIGestureRecognizer) {
let point = ges.location(in: slider)
let currentValue = point.x / slider.frame.size.width * CGFloat(slider.maximumValue)
delegate?.controlView(view: self, pointSliderLocationWithCurrentValue: Float(currentValue))
}
@objc func handleSliderPositionExit(sender:UISlider){
print("exit")
delegate?.controlView(view: self, draggedPositionExitWithSlider: slider)
}
@objc func handleSliderPosition(sender:UISlider) {
print(sender.value)
delegate?.controlView(view: self, draggedPositionWithSlider: slider)
}
@objc func hanleFullScreen(sender:UIButton) {
delegate?.controlView(view: self, withLargeButton: sender)
}
@objc func deviceOrientationDidChange() {
addConstraintsForSubviews()
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
}
| 32.226601 | 163 | 0.623051 |
7903a54528daa2e1f1565fe2adb23f5e68baa011 | 2,863 | //
// TrafficCounter.swift
// TrafficPolice
//
// Created by 刘栋 on 2016/11/17.
// Copyright © 2016年 anotheren.com. All rights reserved.
//
import Foundation
//import ifaddrs
public struct TrafficCounter {
public init() { }
public var usage: TrafficPackage {
var result: TrafficPackage = .zero
var addrsPointer: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&addrsPointer) == 0 {
var pointer = addrsPointer
while pointer != nil {
if let addrs = pointer?.pointee {
let name = String(cString: addrs.ifa_name)
if addrs.ifa_addr.pointee.sa_family == UInt8(AF_LINK) {
if name.hasPrefix("en") { // Wifi
let networkData = unsafeBitCast(addrs.ifa_data, to: UnsafeMutablePointer<if_data>.self)
result.wifi.received += networkData.pointee.ifi_ibytes
result.wifi.sent += networkData.pointee.ifi_obytes
} else if name.hasPrefix("pdp_ip") { // WWAN
let networkData = unsafeBitCast(addrs.ifa_data, to: UnsafeMutablePointer<if_data>.self)
result.wwan.received += networkData.pointee.ifi_ibytes
result.wwan.sent += networkData.pointee.ifi_obytes
}
}
}
pointer = pointer?.pointee.ifa_next
}
freeifaddrs(addrsPointer)
}
return result
}
public var allUsage: [String: TrafficData] {
var result = [String: TrafficData]()
var addrsPointer: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&addrsPointer) == 0 {
var pointer = addrsPointer
while pointer != nil {
if let addrs = pointer?.pointee {
let name = String(cString: addrs.ifa_name)
if addrs.ifa_addr.pointee.sa_family == UInt8(AF_LINK) {
let networkData = unsafeBitCast(addrs.ifa_data, to: UnsafeMutablePointer<if_data>.self)
if var addr = result[name] {
addr.received += networkData.pointee.ifi_ibytes
addr.sent += networkData.pointee.ifi_obytes
result[name] = addr
} else {
let addr = TrafficData(received: networkData.pointee.ifi_ibytes, sent: networkData.pointee.ifi_obytes)
result[name] = addr
}
}
}
pointer = pointer?.pointee.ifa_next
}
freeifaddrs(addrsPointer)
}
return result
}
}
| 40.323944 | 130 | 0.515543 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.