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
|
---|---|---|---|---|---|
1e8a7135869999d87fc16697767ced31b5fec41b | 2,069 | // Copyright 2017 IBM RESEARCH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import Foundation
/**
Qubits Register
*/
public struct QuantumRegister: Register, Equatable {
public private(set) var name:String = ""
public private(set) var size:Int = 0
public init(_ name: String, _ size: Int) throws {
self.name = name
self.size = size
try self.checkProperties()
}
private init() {
}
public subscript(index: Int) -> QuantumRegisterTuple {
get {
if index < 0 || index >= self.size {
fatalError("Index out of range")
}
return QuantumRegisterTuple(self, index)
}
}
public var description: String {
return "qreg \(self.name)[\(self.size)]"
}
public static func ==(lhs: QuantumRegister, rhs: QuantumRegister) -> Bool {
return lhs.name == rhs.name && lhs.size == rhs.size
}
}
public struct QuantumRegisterTuple: RegisterArgument, Equatable {
public let register: QuantumRegister
public let index: Int
init(_ register: QuantumRegister, _ index: Int) {
self.register = register
self.index = index
}
public var identifier: String {
return "\(self.register.name)[\(self.index)]"
}
public static func ==(lhs: QuantumRegisterTuple, rhs: QuantumRegisterTuple) -> Bool {
return lhs.register == rhs.register && lhs.index == rhs.index
}
}
| 29.557143 | 89 | 0.623973 |
db44c594377ee69fa9e69dfa18760b211857dc36 | 248 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class b<U{{}class a{class B:a{let Q{var h{class c{class B{enum S{class a<T:T.a
| 41.333333 | 87 | 0.745968 |
8f1edb159486949f57d2bd23ad049ddbcb32751f | 955 | //
// ChatPosition.swift
// tl2swift
//
// Generated automatically. Any changes will be lost!
// Based on TDLib 1.8.0-fa8feefe
// https://github.com/tdlib/td/tree/fa8feefe
//
import Foundation
/// Describes a position of a chat in a chat list
public struct ChatPosition: Codable, Equatable {
/// True, if the chat is pinned in the chat list
public let isPinned: Bool
/// The chat list
public let list: ChatList
/// A parameter used to determine order of the chat in the chat list. Chats must be sorted by the pair (order, chat.id) in descending order
public let order: TdInt64
/// Source of the chat in the chat list; may be null
public let source: ChatSource?
public init(
isPinned: Bool,
list: ChatList,
order: TdInt64,
source: ChatSource?
) {
self.isPinned = isPinned
self.list = list
self.order = order
self.source = source
}
}
| 22.738095 | 143 | 0.643979 |
08714505503566a449dce93a7f7678022ac9e34e | 572 | // swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Interplate",
products: [
.library(name: "Interplate", targets: ["Interplate"])
],
dependencies: [
.package(url: "https://github.com/ilyapuchka/common-parsers.git", .branch("master"))
],
targets: [
.target(name: "Interplate", dependencies: ["CommonParsers"]),
.testTarget(name: "InterplateTests", dependencies: ["Interplate"])
]
)
| 30.105263 | 96 | 0.655594 |
4ba0418e74a18c260e68c6396504de6f6f034c09 | 1,163 | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import MotionTransitioning
final class FallbackTransition: NSObject, Transition, TransitionWithFallback {
let fallbackTo: Transition?
init(to: Transition) {
self.fallbackTo = to
}
override init() {
self.fallbackTo = nil
}
func fallbackTransition(with context: TransitionContext) -> Transition {
if let fallbackTo = fallbackTo {
return fallbackTo
}
return self
}
var startWasInvoked = false
func start(with context: TransitionContext) {
startWasInvoked = true
context.transitionDidEnd()
}
}
| 25.844444 | 78 | 0.745486 |
5daf45df144cd950775f54117b15574b2f8a566c | 5,107 | //
// Copyright © 2021 osy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
@available(macOS 11, *)
struct SavePanel: NSViewRepresentable {
@EnvironmentObject private var data: UTMData
@Binding var isPresented: Bool
var shareItem: VMShareItemModifier.ShareItem?
func makeNSView(context: Context) -> some NSView {
return NSView()
}
func updateNSView(_ nsView: NSViewType, context: Context) {
if isPresented {
guard let shareItem = shareItem else {
return
}
guard let window = nsView.window else {
return
}
// Initializing the SavePanel and setting its properties
let savePanel = NSSavePanel()
if let downloadsUrl = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first {
savePanel.directoryURL = downloadsUrl
}
switch shareItem {
case .debugLog:
savePanel.title = "Select where to save debug log:"
savePanel.nameFieldStringValue = "debug"
savePanel.allowedContentTypes = [.appleLog]
case .utmCopy(let vm), .utmMove(let vm):
savePanel.title = "Select where to save UTM Virtual Machine:"
savePanel.nameFieldStringValue = vm.path!.lastPathComponent
savePanel.allowedContentTypes = [.UTM]
case .qemuCommand:
savePanel.title = "Select where to export QEMU command:"
savePanel.nameFieldStringValue = "command"
savePanel.allowedContentTypes = [.plainText]
}
// Calling savePanel.begin with the appropriate completion handlers
// SwiftUI BUG: if we don't wait, there is a crash due to an access issue
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
switch shareItem {
case .debugLog(let sourceUrl):
savePanel.beginSheetModal(for: window) { result in
if result == .OK {
if let destUrl = savePanel.url {
data.busyWorkAsync {
let fileManager = FileManager.default
// All this mess is because FileManager.replaceItemAt deletes the source item
let tempUrl = fileManager.temporaryDirectory.appendingPathComponent(sourceUrl.lastPathComponent)
if fileManager.fileExists(atPath: tempUrl.path) {
try fileManager.removeItem(at: tempUrl)
}
try fileManager.copyItem(at: sourceUrl, to: tempUrl)
_ = try fileManager.replaceItemAt(destUrl, withItemAt: tempUrl)
}
}
}
isPresented = false
}
case .utmCopy(let vm), .utmMove(let vm):
savePanel.beginSheetModal(for: window) { result in
if result == .OK {
if let destUrl = savePanel.url {
data.busyWorkAsync {
if case .utmMove(_) = shareItem {
try await data.move(vm: vm, to: destUrl)
} else {
try await data.export(vm: vm, to: destUrl)
}
}
}
}
isPresented = false
}
case .qemuCommand(let command):
savePanel.beginSheetModal(for: window) { result in
if result == .OK {
if let destUrl = savePanel.url {
data.busyWork {
try command.write(to: destUrl, atomically: true, encoding: .utf8)
}
}
}
isPresented = false
}
}
}
}
}
}
| 44.408696 | 132 | 0.483454 |
38b270afd94073bd52d9b498a73c8f6baaf97092 | 16,052 | //
// KarhooBookingPresenter.swift
// Karhoo
//
//
// Copyright © 2020 Karhoo All rights reserved.
//
import CoreLocation
import KarhooSDK
final class KarhooBookingPresenter {
private weak var view: BookingView?
private let bookingStatus: BookingStatus
private let userService: UserService
private let analyticsProvider: Analytics
private let phoneNumberCaller: PhoneNumberCallerProtocol
private let callback: ScreenResultCallback<BookingScreenResult>?
private let tripScreenBuilder: TripScreenBuilder
private let rideDetailsScreenBuilder: RideDetailsScreenBuilder
private let checkoutScreenBuilder: CheckoutScreenBuilder
private let prebookConfirmationScreenBuilder: PrebookConfirmationScreenBuilder
private let addressScreenBuilder: AddressScreenBuilder
private let datePickerScreenBuilder: DatePickerScreenBuilder
private let ridesScreenBuilder: RidesScreenBuilder
private let tripRatingCache: TripRatingCache
private let urlOpener: URLOpener
private let paymentService: PaymentService
init(bookingStatus: BookingStatus = KarhooBookingStatus.shared,
userService: UserService = Karhoo.getUserService(),
analyticsProvider: Analytics = KarhooAnalytics(),
phoneNumberCaller: PhoneNumberCallerProtocol = PhoneNumberCaller(),
callback: ScreenResultCallback<BookingScreenResult>? = nil,
tripScreenBuilder: TripScreenBuilder = UISDKScreenRouting.default.tripScreen(),
rideDetailsScreenBuilder: RideDetailsScreenBuilder = UISDKScreenRouting.default.rideDetails(),
ridesScreenBuilder: RidesScreenBuilder = UISDKScreenRouting.default.rides(),
checkoutScreenBuilder: CheckoutScreenBuilder = UISDKScreenRouting.default.bookingRequest(),
prebookConfirmationScreenBuilder: PrebookConfirmationScreenBuilder = UISDKScreenRouting.default.prebookConfirmation(),
addressScreenBuilder: AddressScreenBuilder = UISDKScreenRouting.default.address(),
datePickerScreenBuilder: DatePickerScreenBuilder = UISDKScreenRouting.default.datePicker(),
tripRatingCache: TripRatingCache = KarhooTripRatingCache(),
urlOpener: URLOpener = KarhooURLOpener(),
paymentService: PaymentService = Karhoo.getPaymentService()) {
self.userService = userService
self.analyticsProvider = analyticsProvider
self.bookingStatus = bookingStatus
self.phoneNumberCaller = phoneNumberCaller
self.callback = callback
self.tripScreenBuilder = tripScreenBuilder
self.rideDetailsScreenBuilder = rideDetailsScreenBuilder
self.checkoutScreenBuilder = checkoutScreenBuilder
self.prebookConfirmationScreenBuilder = prebookConfirmationScreenBuilder
self.addressScreenBuilder = addressScreenBuilder
self.datePickerScreenBuilder = datePickerScreenBuilder
self.ridesScreenBuilder = ridesScreenBuilder
self.tripRatingCache = tripRatingCache
self.urlOpener = urlOpener
self.paymentService = paymentService
userService.add(observer: self)
bookingStatus.add(observer: self)
}
// swiftlint:enable line_length
deinit {
userService.remove(observer: self)
bookingStatus.remove(observer: self)
}
private func showCheckoutView(quote: Quote,
bookingDetails: BookingDetails,
bookingMetadata: [String: Any]? = KarhooUISDKConfigurationProvider.configuration.bookingMetadata) {
let checkoutView = checkoutScreenBuilder
.buildCheckoutScreen(quote: quote,
bookingDetails: bookingDetails,
bookingMetadata: bookingMetadata,
callback: { [weak self] result in
self?.view?.presentedViewController?.dismiss(animated: false, completion: {
self?.bookingRequestCompleted(result: result,
quote: quote,
details: bookingDetails)
})
})
view?.showAsOverlay(item: checkoutView, animated: false)
}
private func bookingRequestCompleted(result: ScreenResult<TripInfo>, quote: Quote, details: BookingDetails) {
if let trip = result.completedValue() {
handleNewlyBooked(trip: trip,
quote: quote,
bookingDetails: details)
return
}
if let error = result.errorValue() {
view?.show(error: error)
}
view?.showQuoteList()
}
private func rebookTrip(_ trip: TripInfo) {
var bookingDetails = BookingDetails(originLocationDetails: trip.origin.toLocationInfo())
bookingDetails.destinationLocationDetails = trip.destination?.toLocationInfo()
populate(with: bookingDetails)
setViewMapPadding()
}
private func handleNewlyBooked(trip: TripInfo,
quote: Quote,
bookingDetails: BookingDetails) {
switch trip.state {
case .noDriversAvailable:
view?.reset()
view?.showAlert(title: UITexts.Trip.noDriversAvailableTitle,
message: String(format: UITexts.Trip.noDriversAvailableMessage,
trip.fleetInfo.name),
error: nil)
case .karhooCancelled:
view?.reset()
view?.showAlert(title: UITexts.Trip.karhooCancelledAlertTitle,
message: UITexts.Trip.karhooCancelledAlertMessage,
error: nil)
default:
if bookingDetails.isScheduled {
view?.reset()
showPrebookConfirmation(quote: quote,
trip: trip,
bookingDetails: bookingDetails)
} else {
view?.showAllocationScreen(trip: trip)
}
}
}
}
extension KarhooBookingPresenter: BookingDetailsObserver {
func bookingStateChanged(details: BookingDetails?) {
if details?.originLocationDetails != nil,
details?.destinationLocationDetails != nil {
view?.showQuoteList()
} else {
view?.hideQuoteList()
view?.setMapPadding(bottomPaddingEnabled: false)
}
view?.quotesAvailabilityDidUpdate(availability: true)
}
}
extension KarhooBookingPresenter: UserStateObserver {
func userStateUpdated(user: UserInfo?) {
if user == nil {
resetBookingStatus()
tripRatingCache.clearTripRatings()
}
}
}
extension KarhooBookingPresenter: BookingPresenter {
func load(view: BookingView?) {
self.view = view
fetchPaymentProvider()
}
private func fetchPaymentProvider() {
if !Karhoo.configuration.authenticationMethod().isGuest() {
return
}
paymentService.getPaymentProvider().execute(callback: { _ in})
}
func resetBookingStatus() {
bookingStatus.reset()
}
func bookingDetails() -> BookingDetails? {
return bookingStatus.getBookingDetails()
}
func populate(with bookingDetails: BookingDetails) {
bookingStatus.reset(with: bookingDetails)
}
func tripCancelledBySystem(trip: TripInfo) {
resetBookingStatus()
switch trip.state {
case .karhooCancelled:
view?.showAlert(title: UITexts.Trip.karhooCancelledAlertTitle,
message: UITexts.Trip.karhooCancelledAlertMessage,
error: nil)
default:
view?.showAlert(title: UITexts.Trip.noDriversAvailableTitle,
message: String(format: UITexts.Trip.noDriversAvailableMessage, trip.fleetInfo.name),
error: nil)
}
view?.hideAllocationScreen()
var bookingDetails = BookingDetails(originLocationDetails: trip.origin.toLocationInfo())
bookingDetails.destinationLocationDetails = trip.destination?.toLocationInfo()
populate(with: bookingDetails)
}
func tripCancellationFailed(trip: TripInfo) {
let callFleet = UITexts.Trip.tripCancelBookingFailedAlertCallFleetButton
view?.showAlert(title: UITexts.Trip.tripCancelBookingFailedAlertTitle,
message: UITexts.Trip.tripCancelBookingFailedAlertMessage,
error: nil,
actions: [
AlertAction(title: UITexts.Generic.cancel, style: .default, handler: nil),
AlertAction(title: callFleet, style: .default, handler: { [weak self] _ in
self?.phoneNumberCaller.call(number: trip.fleetInfo.phoneNumber)
})
])
}
func tripDriverAllocationDelayed(trip: TripInfo) {
view?.showAlert(title: UITexts.GenericTripStatus.driverAllocationDelayTitle,
message: UITexts.GenericTripStatus.driverAllocationDelayMessage,
error: nil,
actions: [
AlertAction(title: UITexts.Generic.ok, style: .default, handler: { [weak self] _ in
self?.tripWaitOnRideDetails(trip: trip)
})
])
}
func tripWaitOnRideDetails(trip: TripInfo) {
view?.resetAndLocate()
view?.hideAllocationScreen()
showRideDetails(trip: trip)
}
func tripSuccessfullyCancelled() {
resetBookingStatus()
view?.hideAllocationScreen()
view?.showAlert(title: UITexts.Bookings.cancellationSuccessAlertTitle,
message: UITexts.Bookings.cancellationSuccessAlertMessage,
error: nil)
}
func didSelectQuote(quote: Quote) {
view?.hideQuoteList()
guard let bookingDetails = bookingDetails() else {
return
}
showCheckoutView(quote: quote, bookingDetails: bookingDetails)
}
func showRidesList(presentationStyle: UIModalPresentationStyle?) {
let ridesList = ridesScreenBuilder.buildRidesScreen(completion: { [weak self] result in
self?.view?.dismiss(animated: true, completion: {
ridesListCompleted(result: result)
})
})
if let presStyle = presentationStyle {
ridesList.modalPresentationStyle = presStyle
}
self.view?.present(ridesList, animated: true, completion: nil)
func ridesListCompleted(result: ScreenResult<RidesListAction>) {
guard let action = result.completedValue() else {
return
}
switch action {
case .trackTrip(let trip):
goToTripView(trip: trip)
case .bookNewTrip:
view?.resetAndLocate()
case .rebookTrip(let trip):
rebookTrip(trip)
}
}
}
func viewWillAppear() {
setViewMapPadding()
}
func tripAllocated(trip: TripInfo) {
view?.reset()
view?.hideAllocationScreen()
finishWithResult(.completed(result: .tripAllocated(tripInfo: trip)))
}
func exitPressed() {
bookingStatus.reset()
view?.dismiss(animated: true, completion: { [weak self] in
self?.callback?(ScreenResult.cancelled(byUser: true))
})
}
func goToTripView(trip: TripInfo) {
if Karhoo.configuration.authenticationMethod().isGuest() {
let dismissTrackingAction = AlertAction(title: UITexts.Trip.trackTripAlertDismissAction, style: .cancel)
let trackTripAction = AlertAction(title: UITexts.Trip.trackTripAlertAction, style: .default) { _ in
self.urlOpener.openAgentPortalTracker(followCode: trip.followCode)
}
view?.showAlert(title: UITexts.Trip.trackTripAlertTitle,
message: UITexts.Trip.trackTripAlertMessage,
error: .none,
actions: [dismissTrackingAction, trackTripAction])
} else {
let tripView = tripScreenBuilder.buildTripScreen(trip: trip,
callback: tripViewCallback)
view?.present(tripView, animated: true, completion: nil)
}
}
func showPrebookConfirmation(quote: Quote, trip: TripInfo, bookingDetails: BookingDetails) {
let prebookConfirmation = prebookConfirmationScreenBuilder
.buildPrebookConfirmationScreen(quote: quote,
bookingDetails: bookingDetails,
confirmationCallback: { [weak self] result in
self?.view?.dismiss(animated: true, completion: nil)
self?.prebookConfirmationCompleted(result: result, trip: trip)
})
prebookConfirmation.modalTransitionStyle = .crossDissolve
view?.showAsOverlay(item: prebookConfirmation, animated: true)
}
func prebookConfirmationCompleted(result: ScreenResult<PrebookConfirmationAction>, trip: TripInfo) {
guard let action = result.completedValue() else {
return
}
finishWithResult(.completed(result: .prebookConfirmed(tripInfo: trip, prebookConfirmationAction: action)))
}
func finishWithResult(_ result: ScreenResult<BookingScreenResult>) {
guard let callback = self.callback else {
switch result.completedValue() {
case .tripAllocated(let trip)?:
goToTripView(trip: trip)
case .prebookConfirmed(let trip, let action)?:
if case .rideDetails = action {
showRideDetails(trip: trip)
}
default:
break
}
return
}
callback(result)
}
func showRideDetails(trip: TripInfo) {
let rideDetailsViewController = rideDetailsScreenBuilder
.buildOverlayRideDetailsScreen(trip: trip,
callback: { [weak self] result in
self?.view?.dismiss(animated: true, completion: { [weak self] in
self?.rideDetailsScreenCompleted(result: result)
})
})
view?.present(rideDetailsViewController, animated: true, completion: nil)
}
func rideDetailsScreenCompleted(result: ScreenResult<RideDetailsAction>) {
guard let action = result.completedValue() else {
return
}
switch action {
case .trackTrip(let trip):
goToTripView(trip: trip)
case .rebookTrip(let trip):
rebookTrip(trip)
}
}
func tripViewCallback(result: ScreenResult<TripScreenResult>) {
view?.dismiss(animated: true, completion: nil)
switch result.completedValue() {
case .some(.rebookTrip(let details)):
populate(with: details)
default: break
}
}
func setViewMapPadding() {
let bookingDetails = bookingStatus.getBookingDetails()
if bookingDetails?.originLocationDetails != nil,
bookingDetails?.destinationLocationDetails != nil {
view?.setMapPadding(bottomPaddingEnabled: true)
} else {
view?.setMapPadding(bottomPaddingEnabled: false)
}
}
}
| 39.246944 | 133 | 0.605407 |
48ee4fddbb908cdd7cc22549652a8874d6f01fbc | 792 | //
// TopicPath+Extensions.swift
// FlintCore
//
// Created by Marc Palmer on 03/01/2018.
// Copyright © 2018 Montana Floss Co. Ltd. All rights reserved.
//
import Foundation
/// Feature-specific extensions as a convenience for creating TopicPath instances
public extension TopicPath {
init(feature: FeatureDefinition.Type) {
self.init([String(describing: feature)])
}
init<FeatureType, ActionType>(actionBinding: StaticActionBinding<FeatureType, ActionType>) {
self.init(FeatureType.identifier.path + ["#\(String(describing: ActionType.self))"])
}
init<FeatureType, ActionType>(actionBinding: ConditionalActionBinding<FeatureType, ActionType>) {
self.init(FeatureType.identifier.path + ["#\(String(describing: ActionType.self))"])
}
}
| 31.68 | 101 | 0.715909 |
d7329487b614b23a55a27c92755c7df9c77f36a5 | 4,485 | /// Copyright (c) 2020 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.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import SwiftUI
struct ContentView: View {
@State private var selectedGenre = Genre.list.first
var body: some View {
NavigationView {
ScrollView { //pinnedViews를 제대로 사용하려면 ScrollView를 추가한다.
ScrollViewReader { scrollProxy in
LazyVStack(pinnedViews: .sectionHeaders) {
//일반 VStack은 pinnedViews를 지원하지 않는다.
ForEach(Genre.list) { genre in
Section(header: genre.header.id(genre)) {
LazyVGrid(
columns: [.init(.adaptive(minimum: 150))]
) {
ForEach(genre.subgenres, content: \.view)
//key-value mapping으로 ForEach에서 view를 가져올 수 있다.
}
.padding(.horizontal)
}
}
}
.onChange(of: selectedGenre) { genre in
scrollProxy.scrollTo(selectedGenre, anchor: .top)
selectedGenre = nil
}
}
}
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem {
Menu("Genre") {
ForEach(Genre.list) { genre in
Button(genre.name) {
selectedGenre = genre
}
}
}
}
}
}
}
}
//현재 Xcode 최신 버전에서는 Genre에서 멀리 있는 것을 선택하면, 정확한 위치로 스크롤이 되지 않는 버그가 있다.
private extension Genre {
var header: some SwiftUI.View {
HStack {
Text(name)
.font(.title2)
.fontWeight(.bold)
.padding(.leading)
.padding(.vertical, 8)
Spacer()
}
.background(UIBlurEffect.View(blurStyle: .systemThinMaterial))
.frame(maxWidth: .infinity)
}
}
//⌘ + ⇧ + L 로, Library를 열어 View와 Modifier를 끌어와 추가할 수 있다.
private extension Genre.Subgenre {
var view: some View {
RoundedRectangle(cornerRadius: 8)
.fill(
LinearGradient(
gradient: .init(
colors: AnyIterator { } .prefix(2).map {
.random(saturation: 2 / 3, value: 0.85)
}
),
startPoint: .topLeading, endPoint: .bottomTrailing
)
)
.frame(height: 125)
.overlay(
Image("Genre/\(Int.random(in: 1...92))")
.resizable()
.saturation(0)
.blendMode(.multiply)
.scaledToFit()
)
.overlay(
Text(name)
.foregroundColor(.white)
.fontWeight(.bold)
.padding(10)
.frame(alignment: .bottomLeading),
alignment: .bottomLeading
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 33.222222 | 83 | 0.625418 |
ef1a9ff4eb19286122908c280e3a04fc1997fb2d | 3,842 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: bitsong/fantoken/v1beta1/genesis.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// GenesisState defines the fantoken module's genesis state
struct Bitsong_Fantoken_V1beta1_GenesisState {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var params: Bitsong_Fantoken_V1beta1_Params {
get {return _params ?? Bitsong_Fantoken_V1beta1_Params()}
set {_params = newValue}
}
/// Returns true if `params` has been explicitly set.
var hasParams: Bool {return self._params != nil}
/// Clears the value of `params`. Subsequent reads from it will return its default value.
mutating func clearParams() {self._params = nil}
var tokens: [Bitsong_Fantoken_V1beta1_FanToken] = []
var burnedCoins: [Cosmos_Base_V1beta1_Coin] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _params: Bitsong_Fantoken_V1beta1_Params? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "bitsong.fantoken.v1beta1"
extension Bitsong_Fantoken_V1beta1_GenesisState: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GenesisState"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "params"),
2: .same(proto: "tokens"),
3: .standard(proto: "burned_coins"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._params) }()
case 2: try { try decoder.decodeRepeatedMessageField(value: &self.tokens) }()
case 3: try { try decoder.decodeRepeatedMessageField(value: &self.burnedCoins) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._params {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if !self.tokens.isEmpty {
try visitor.visitRepeatedMessageField(value: self.tokens, fieldNumber: 2)
}
if !self.burnedCoins.isEmpty {
try visitor.visitRepeatedMessageField(value: self.burnedCoins, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Bitsong_Fantoken_V1beta1_GenesisState, rhs: Bitsong_Fantoken_V1beta1_GenesisState) -> Bool {
if lhs._params != rhs._params {return false}
if lhs.tokens != rhs.tokens {return false}
if lhs.burnedCoins != rhs.burnedCoins {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 40.020833 | 149 | 0.742322 |
1d681e430bcbd1bdb2619e18456068f1254bc02a | 8,692 | import Foundation
import JSONUtilities
import PathKit
import Swagger
import Yams
struct Enum {
let name: String
let cases: [Any]
let schema: Schema
let description: String?
let metadata: Metadata
let names: [String]?
}
struct ResponseFormatter {
let response: Response
let successful: Bool
let name: String?
let statusCode: Int?
}
extension SwaggerSpec {
var operationsByTag: [String: [Swagger.Operation]] {
var dictionary: [String: [Swagger.Operation]] = [:]
// add operations with no tag at ""
let operationsWithoutTag = operations
.filter { $0.tags.isEmpty }
.sorted { $0.generatedIdentifier < $1.generatedIdentifier }
if !operationsWithoutTag.isEmpty {
dictionary[""] = operationsWithoutTag
}
for tag in tags {
dictionary[tag] = operations
.filter { $0.tags.contains(tag) }
.sorted { $0.generatedIdentifier < $1.generatedIdentifier }
}
return dictionary
}
var enums: [Enum] {
return components.parameters.compactMap { $0.value.getEnum(name: $0.name, description: $0.value.description) }
}
}
extension Metadata {
func getEnum(name: String, schema: Schema, description: String?) -> Enum? {
if let enumValues = enumValues {
return Enum(name: name, cases: enumValues.compactMap { $0 }, schema: schema, description: description ?? self.description, metadata: self, names: enumNames)
}
return nil
}
}
extension Schema {
var parent: ComponentObject<Schema>? {
if case let .group(group) = type, group.type == .all {
for schema in group.schemas {
if case let .reference(reference) = schema.type {
return reference.component
}
}
}
return nil
}
var properties: [Property] {
return requiredProperties + optionalProperties
}
var requiredProperties: [Property] {
switch type {
case let .object(objectSchema): return objectSchema.requiredProperties
case let .group(groupSchema) where groupSchema.type == .all:
for schema in groupSchema.schemas {
if case let .object(objectSchema) = schema.type {
return objectSchema.requiredProperties
}
}
return []
default: return []
}
}
var optionalProperties: [Property] {
switch type {
case let .object(objectSchema): return objectSchema.optionalProperties
case let .group(groupSchema) where groupSchema.type == .all:
for schema in groupSchema.schemas {
if case let .object(objectSchema) = schema.type {
return objectSchema.optionalProperties
}
}
default: break
}
return []
}
var inheritedProperties: [Property] {
return inheritedRequiredProperties + inheritedOptionalProperties
}
var inheritedRequiredProperties: [Property] {
return (parent?.value.inheritedRequiredProperties ?? []) + requiredProperties
}
var inheritedOptionalProperties: [Property] {
return (parent?.value.inheritedOptionalProperties ?? []) + optionalProperties
}
func getEnum(name: String, description: String?) -> Enum? {
switch type {
case let .object(objectSchema):
if let schema = objectSchema.additionalProperties {
return schema.getEnum(name: name, description: description)
}
case .string, .integer, .number:
return metadata.getEnum(name: name, schema: self, description: description)
case let .array(array):
if case let .single(schema) = array.items {
return schema.getEnum(name: name, description: description)
}
default: break
}
return nil
}
var enums: [Enum] {
var enums = properties.compactMap { $0.schema.getEnum(name: $0.name, description: $0.schema.metadata.description) }
if case let .object(objectSchema) = type, let schema = objectSchema.additionalProperties {
enums += schema.enums
}
return enums
}
var inheritedEnums: [Enum] {
return (parent?.value.inheritedEnums ?? []) + enums
}
var inlineSchema: Schema? {
switch type {
case let .object(schema) where schema.additionalProperties == nil && !schema.properties.isEmpty:
return self
case let .array(arraySchema):
switch arraySchema.items {
case let .single(schema):
return schema.inlineSchema
case .multiple:
break
}
case let .group(group):
switch group.type {
case .any, .one:
if group.discriminator != nil {
return self
}
case .all:
break
}
default: break
}
return nil
}
}
extension Swagger.Operation {
func getParameters(type: ParameterLocation) -> [Parameter] {
return parameters.map { $0.value }.filter { $0.location == type }
}
var enums: [Enum] {
return requestEnums + responseEnums
}
var requestEnums: [Enum] {
let paramEnums = parameters.compactMap { $0.value.enumValue }
let bodyEnums = requestBody?.value.content.defaultSchema?.enums ?? []
return paramEnums + bodyEnums
}
var responseEnums: [Enum] {
return responses.compactMap { $0.enumValue }
}
}
extension ObjectSchema {
var enums: [Enum] {
var enums: [Enum] = []
for property in properties {
if let enumValue = property.schema.getEnum(name: property.name, description: property.schema.metadata.description) {
enums.append(enumValue)
}
}
if let schema = additionalProperties {
if let enumValue = schema.getEnum(name: schema.metadata.title ?? "UNNKNOWN_ENUM", description: schema.metadata.description) {
enums.append(enumValue)
}
}
return enums
}
}
extension OperationResponse {
public var successful: Bool {
return statusCode?.description.hasPrefix("2") ?? false
}
public var name: String {
if let statusCode = statusCode {
return "Status\(statusCode.description)"
} else {
return "DefaultResponse"
}
}
var isEnum: Bool {
return enumValue != nil
}
var enumValue: Enum? {
return response.value.schema?.getEnum(name: name, description: response.value.description)
}
}
extension Response {
var schema: Schema? {
return content?.defaultSchema
}
}
extension Property {
var isEnum: Bool {
return enumValue != nil
}
var enumValue: Enum? {
return schema.getEnum(name: name, description: schema.metadata.description)
}
}
extension Parameter {
func getEnum(name: String, description: String?) -> Enum? {
switch type {
case let .schema(schema): return schema.schema.getEnum(name: name, description: description)
case let .content(content): return content.defaultSchema?.getEnum(name: name, description: description)
}
}
var isEnum: Bool {
return enumValue != nil
}
var enumValue: Enum? {
return getEnum(name: name, description: description)
}
var schema: Schema? {
switch type {
case let .content(content): return content.defaultSchema
case let .schema(schema): return schema.schema
}
}
}
extension Schema {
var canBeEnum: Bool {
switch type {
case .string, .integer, .number:
return true
default: return false
}
}
var isFile: Bool {
switch type {
case let .string(format):
switch format.format {
case let .format(format)?:
switch format {
case .binary: return true
case .byte: return true
default: return false
}
default: return false
}
default: return false
}
}
}
extension Content {
var defaultSchema: Schema? {
return getMediaItem(.json)?.schema ?? mediaItems.values.first?.schema
}
var containsFile: Bool {
return mediaItems.values.contains { $0.schema.properties.contains { $0.schema.isFile } }
}
}
| 27.769968 | 168 | 0.584215 |
4a32eb6ebd0b1dc4635f33de7cc51fbc9fbeeb25 | 262 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b{func a<let a<a
enum T{func b{enum S<T:a
| 29.111111 | 87 | 0.740458 |
184a06176fc47832aa51d62a2596394dc51e658f | 1,180 | //
// CharactersWireframe.swift
// RickAndMorty
//
// Created by Patrick VONGPRASEUTH on 05/04/2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
final class CharactersWireframe: BaseWireframe<CharactersViewController> {
// MARK: - Private properties -
private let storyboard = UIStoryboard(name: "Characters", bundle: nil)
// MARK: - Module setup -
init() {
let moduleViewController = storyboard.instantiateViewController(withIdentifier: "CharactersViewController") as! CharactersViewController
super.init(viewController: moduleViewController)
let interactor = CharactersInteractor(services: ApiService.getInstance())
let presenter = CharactersPresenter(view: moduleViewController, interactor: interactor, wireframe: self)
moduleViewController.presenter = presenter
}
}
// MARK: - Extensions -
extension CharactersWireframe: CharactersWireframeInterface {
func pushToCharacterDetail(character : Character){
navigationController?.pushWireframe(CharacterDetailWireframe(character: character))
}
}
| 30.25641 | 144 | 0.744915 |
e5a2ca39247cea5392569ee1af600f956bed6c42 | 12,902 | //
// JsonValue.swift
//
// Copyright © 2017-2020 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
/// Protocol for converting an object to a dictionary representation. This is included for reverse-compatiblility to
/// older implementations that are not Swift `Codable` and instead use a dictionary representation.
public protocol DictionaryRepresentable {
/// Return the dictionary representation for this object.
func dictionaryRepresentation() -> [String : JsonSerializable]
}
/// Protocol for converting objects to JSON serializable objects.
public protocol JsonValue {
/// Return a JSON-type object. Elements may be any one of the JSON types.
func jsonObject() -> JsonSerializable
/// Encode the object.
func encode(to encoder: Encoder) throws
}
extension NSString : JsonValue {
public func jsonObject() -> JsonSerializable {
return String(self)
}
public func encode(to encoder: Encoder) throws {
try (self as String).encode(to: encoder)
}
}
extension String : JsonValue {
public func jsonObject() -> JsonSerializable {
return String(self)
}
}
extension NSNumber : JsonValue {
public func jsonObject() -> JsonSerializable {
return self.copy() as! NSNumber
}
}
extension Int : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Int8 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Int16 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Int32 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Int64 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension UInt : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension UInt8 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension UInt16 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension UInt32 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension UInt64 : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Bool : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Double : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension Float : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension NSNull : JsonValue {
public func jsonObject() -> JsonSerializable {
return self
}
}
extension NSDate : JsonValue {
public func jsonObject() -> JsonSerializable {
return (self as Date).jsonObject()
}
public func encode(to encoder: Encoder) throws {
try (self as Date).encode(to: encoder)
}
}
extension Date : JsonValue {
public func jsonObject() -> JsonSerializable {
return SerializationFactory.shared.timestampFormatter.string(from: self)
}
}
extension DateComponents : JsonValue {
public func jsonObject() -> JsonSerializable {
guard let date = self.date ?? Calendar(identifier: .iso8601).date(from: self) else { return NSNull() }
return defaultFormatter().string(from: date)
}
public func defaultFormatter() -> DateFormatter {
if ((year == nil) || (year == 0)) && ((month == nil) || (month == 0)) && ((day == nil) || (day == 0)) {
return SerializationFactory.shared.timeOnlyFormatter
}
else if ((hour == nil) || (hour == 0)) && ((minute == nil) || (minute == 0)) {
if let year = year, year > 0, let month = month, month > 0, let day = day, day > 0 {
return SerializationFactory.shared.dateOnlyFormatter
}
// Build the format string if not all components are included
var formatString = ""
if let year = year, year > 0 {
formatString = "yyyy"
}
if let month = month, month > 0 {
if formatString.count > 0 {
formatString.append("-")
}
formatString.append("MM")
if let day = day, day > 0 {
formatString.append("-")
formatString.append("dd")
}
}
let formatter = DateFormatter()
formatter.dateFormat = formatString
return formatter
}
return SerializationFactory.shared.timestampFormatter
}
}
extension NSDateComponents : JsonValue {
public func jsonObject() -> JsonSerializable {
return (self as DateComponents).jsonObject()
}
public func encode(to encoder: Encoder) throws {
try (self as DateComponents).encode(to: encoder)
}
}
extension Data : JsonValue {
public func jsonObject() -> JsonSerializable {
return self.base64EncodedString()
}
}
extension NSData : JsonValue {
public func jsonObject() -> JsonSerializable {
return (self as Data).jsonObject()
}
public func encode(to encoder: Encoder) throws {
try (self as Data).encode(to: encoder)
}
}
extension NSUUID : JsonValue {
public func jsonObject() -> JsonSerializable {
return self.uuidString
}
public func encode(to encoder: Encoder) throws {
try (self as UUID).encode(to: encoder)
}
}
extension UUID : JsonValue {
public func jsonObject() -> JsonSerializable {
return self.uuidString
}
}
extension NSURL : JsonValue {
public func jsonObject() -> JsonSerializable {
return self.absoluteString ?? NSNull()
}
public func encode(to encoder: Encoder) throws {
try (self as URL).encode(to: encoder)
}
}
extension URL : JsonValue {
public func jsonObject() -> JsonSerializable {
return self.absoluteString
}
}
fileprivate func _convertToJSONValue(from object: Any) -> JsonSerializable {
if let obj = object as? JsonValue {
return obj.jsonObject()
}
else if let obj = object as? DictionaryRepresentable {
return obj.dictionaryRepresentation()
}
else if let obj = object as? NSObjectProtocol {
return obj.description
}
else {
return NSNull()
}
}
fileprivate func _encode(value: Any, to nestedEncoder:Encoder) throws {
// Note: need to special-case encoding a Date, Data type, or NonConformingNumber since these
// are not encoding correctly unless cast to a nested container that can handle
// custom encoding strategies.
if let date = value as? Date {
var container = nestedEncoder.singleValueContainer()
try container.encode(date)
} else if let data = value as? Data {
var container = nestedEncoder.singleValueContainer()
try container.encode(data)
} else if let nestedArray = value as? [JsonSerializable] {
let encodable = AnyCodableArray(nestedArray)
try encodable.encode(to: nestedEncoder)
} else if let nestedDictionary = value as? Dictionary<String, JsonSerializable> {
let encodable = AnyCodableDictionary(nestedDictionary)
try encodable.encode(to: nestedEncoder)
} else if let number = (value as? JsonNumber)?.jsonNumber() {
var container = nestedEncoder.singleValueContainer()
try container.encode(number)
} else if let encodable = value as? JsonValue {
try encodable.encode(to: nestedEncoder)
} else if let encodable = value as? Encodable {
try encodable.encode(to: nestedEncoder)
} else {
let context = EncodingError.Context(codingPath: nestedEncoder.codingPath, debugDescription: "Could not encode value \(value).")
throw EncodingError.invalidValue(value, context)
}
}
extension NSDictionary : JsonValue, Encodable {
public func jsonDictionary() -> [String : JsonSerializable] {
var dictionary : [String : JsonSerializable] = [:]
for (key, value) in self {
let strKey = "\(key)"
dictionary[strKey] = _convertToJSONValue(from: value)
}
return dictionary
}
public func jsonObject() -> JsonSerializable {
return jsonDictionary()
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: AnyCodingKey.self)
for (key, value) in self {
let strKey = "\(key)"
let codingKey = AnyCodingKey(stringValue: strKey)!
let nestedEncoder = container.superEncoder(forKey: codingKey)
try _encode(value: value, to: nestedEncoder)
}
}
}
extension Dictionary : JsonValue {
public func jsonDictionary() -> [String : JsonSerializable] {
return (self as NSDictionary).jsonDictionary()
}
public func jsonObject() -> JsonSerializable {
return (self as NSDictionary).jsonObject()
}
}
extension Dictionary where Value : Any {
public func encode(to encoder: Encoder) throws {
try (self as NSDictionary).encode(to: encoder)
}
}
extension NSArray : JsonValue {
public func jsonArray() -> [JsonSerializable] {
return self.map { _convertToJSONValue(from: $0) }
}
public func jsonObject() -> JsonSerializable {
return jsonArray()
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for value in self {
let nestedEncoder = container.superEncoder()
try _encode(value: value, to: nestedEncoder)
}
}
}
extension Array : JsonValue {
public func jsonArray() -> [JsonSerializable] {
return (self as NSArray).jsonArray()
}
public func jsonObject() -> JsonSerializable {
return (self as NSArray).jsonObject()
}
}
extension Array where Element : Any {
public func encode(to encoder: Encoder) throws {
try (self as NSArray).encode(to: encoder)
}
}
extension Set : JsonValue {
public func jsonObject() -> JsonSerializable {
return Array(self).jsonObject()
}
}
extension Set where Element : Any {
public func encode(to encoder: Encoder) throws {
try Array(self).encode(to: encoder)
}
}
extension NSNull : Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
extension NSNumber : Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if self === kCFBooleanTrue as NSNumber {
try container.encode(true)
} else if self === kCFBooleanFalse as NSNumber {
try container.encode(false)
} else if NSNumber(value: self.intValue) == self {
try container.encode(self.intValue)
} else {
try container.encode(self.doubleValue)
}
}
}
| 29.796767 | 135 | 0.646799 |
5d302dee29071534cc55e951a9a8a6ea8bca9e4f | 88 | import Foundation
public extension Substring {
var string: String { String(self) }
}
| 14.666667 | 37 | 0.738636 |
288ca4fefe99d0189da32f0fb78e37c4d325ec48 | 1,195 | //
// TESTFeedbackViewController.swift
// DemoSwiftyCam
//
// Created by Tesla on 2019/10/16.
// Copyright © 2019 Cappsule. All rights reserved.
//
import UIKit
class TESTFeedbackViewController: UIViewController,SwiftyCamButtonDelegate {
func buttonWasTapped() {
UISelectionFeedbackGenerator().selectionChanged()
}
func buttonDidBeginLongPress() {
}
func buttonDidEndLongPress() {
}
func longPressDidReachMaximumDuration() {
}
func setMaxiumVideoDuration() -> Double {
return 10
}
@IBOutlet weak var clickAction: SwiftyCamButton!
override func viewDidLoad() {
super.viewDidLoad()
clickAction.delegate = self
// 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.
}
*/
}
| 21.339286 | 106 | 0.633473 |
71a2ac6b6a22cb4c3cec39ebd968da9f0c30fca9 | 3,390 | import Foundation
import Postbox
import TelegramApi
import SyncCore
protocol TelegramCloudMediaResource: TelegramMediaResource {
func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation?
}
protocol TelegramMultipartFetchableResource: TelegramMediaResource {
var datacenterId: Int { get }
}
public protocol TelegramCloudMediaResourceWithFileReference {
var fileReference: Data? { get }
}
extension CloudFileMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference {
func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? {
return Api.InputFileLocation.inputFileLocation(volumeId: self.volumeId, localId: self.localId, secret: self.secret, fileReference: Buffer(data: fileReference ?? Data()))
}
}
extension CloudPhotoSizeMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference {
func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? {
return Api.InputFileLocation.inputPhotoFileLocation(id: self.photoId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: self.sizeSpec)
}
}
extension CloudDocumentSizeMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference {
func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? {
return Api.InputFileLocation.inputDocumentFileLocation(id: self.documentId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: self.sizeSpec)
}
}
extension CloudPeerPhotoSizeMediaResource: TelegramMultipartFetchableResource {
func apiInputLocation(peerReference: PeerReference) -> Api.InputFileLocation? {
let flags: Int32
switch self.sizeSpec {
case .small:
flags = 0
case .fullSize:
flags = 1 << 0
}
return Api.InputFileLocation.inputPeerPhotoFileLocation(flags: flags, peer: peerReference.inputPeer, volumeId: self.volumeId, localId: self.localId)
}
}
extension CloudStickerPackThumbnailMediaResource: TelegramMultipartFetchableResource {
func apiInputLocation(packReference: StickerPackReference) -> Api.InputFileLocation? {
return Api.InputFileLocation.inputStickerSetThumb(stickerset: packReference.apiInputStickerSet, volumeId: self.volumeId, localId: self.localId)
}
}
extension CloudDocumentMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource, TelegramCloudMediaResourceWithFileReference {
func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? {
return Api.InputFileLocation.inputDocumentFileLocation(id: self.fileId, accessHash: self.accessHash, fileReference: Buffer(data: fileReference ?? Data()), thumbSize: "")
}
}
extension SecretFileMediaResource: TelegramCloudMediaResource, TelegramMultipartFetchableResource {
func apiInputLocation(fileReference: Data?) -> Api.InputFileLocation? {
return .inputEncryptedFileLocation(id: self.fileId, accessHash: self.accessHash)
}
}
extension WebFileReferenceMediaResource {
var apiInputLocation: Api.InputWebFileLocation {
return .inputWebFileLocation(url: self.url, accessHash: self.accessHash)
}
}
| 46.438356 | 192 | 0.783186 |
dd096e172cd00cb761d28e185e44afc93f9e18aa | 6,564 | //
// Constants.swift
// KeysForSketch
//
// Created by Vyacheslav Dubovitsky on 19/04/2017.
// Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved.
//
public struct Const {
/// Image names.
public struct Image {
public static let keysIcon = "KeysIcon.icns"
static let disclosureVertiacal = "disclosure-vertical"
static let disclosureHorizontal = "disclosure-horizontal"
}
struct Menu {
/// Sketch's mainMenu.
static let main = NSApplication.shared.mainMenu!
/// A dictionary where keys is titles of Tool Menu Items and the objects is a Sketch action class names associated with it.
static let toolsClassNames = [
"Vector" : "MSInsertVectorAction",
"Pencil" : "MSPencilAction",
"Text" : "MSInsertTextLayerAction",
"Artboard" : "MSInsertArtboardAction",
"Slice" : "MSInsertSliceAction",
// Shape Submenu items
"Line" : "MSInsertLineAction",
"Arrow" : "MSInsertArrowAction",
"Rectangle" : "MSRectangleShapeAction",
"Oval" : "MSOvalShapeAction",
"Rounded" : "MSRoundedRectangleShapeAction",
"Star" : "MSStarShapeAction",
"Polygon" : "MSPolygonShapeAction",
"Triangle": "MSTriangleShapeAction"
]
}
struct MenuItem {
/// An array of manually defined tuples describing a menuItems that shouldn't be customized by Keys.
static let customizableShortcutExceptions: [(title: String, parentItem: String)] = [
// Sketch
// Dynamic system menu. Better to manage through System Preferences
("Services", Const.Menu.main.items[0].title),
// File
// A group of dynamic items
("New from Template", "File"),
// Hidden by Sketch from the main menu
("New from Template…", "File"),
// A group of dynamic items
("Open Recent", "File"),
// A group of dynamic items
("Revert To", "File"),
// A group of dynamic items
("Print", "File"),
// Edit
// Since "Start Dictation" has`fn fn` shortcut by default which we cant easily reassign, skip it too.
("Start Dictation", "Edit"),
// Insert
// Layer
// A group of dynamic items
("Replace With", "Layer")
// Text
// Arrange
// Share
// Plugins
// View
// Window
// Help
]
}
struct Cell {
// OutlineView cells
static let height: CGFloat = 33.0
static let separatorHeight: CGFloat = 8.0
static let dividerHeight: CGFloat = 0.5
}
struct KeyCodeTransformer {
/// A map of non-printed characters Key Codes to its String representations. Values presented in array to match KeyCodeTransformer mapping dictionary data representation.
static let specialKeyCodesMap : [UInt : [String]] = [
UInt(kVK_F1) : [String(unicodeInt: NSF1FunctionKey)],
UInt(kVK_F2) : [String(unicodeInt: NSF2FunctionKey)],
UInt(kVK_F3) : [String(unicodeInt: NSF3FunctionKey)],
UInt(kVK_F4) : [String(unicodeInt: NSF4FunctionKey)],
UInt(kVK_F5) : [String(unicodeInt: NSF5FunctionKey)],
UInt(kVK_F6) : [String(unicodeInt: NSF6FunctionKey)],
UInt(kVK_F7) : [String(unicodeInt: NSF7FunctionKey)],
UInt(kVK_F8) : [String(unicodeInt: NSF8FunctionKey)],
UInt(kVK_F9) : [String(unicodeInt: NSF9FunctionKey)],
UInt(kVK_F10) : [String(unicodeInt: NSF10FunctionKey)],
UInt(kVK_F11) : [String(unicodeInt: NSF11FunctionKey)],
UInt(kVK_F12) : [String(unicodeInt: NSF12FunctionKey)],
UInt(kVK_F13) : [String(unicodeInt: NSF13FunctionKey)],
UInt(kVK_F14) : [String(unicodeInt: NSF14FunctionKey)],
UInt(kVK_F15) : [String(unicodeInt: NSF15FunctionKey)],
UInt(kVK_F16) : [String(unicodeInt: NSF16FunctionKey)],
UInt(kVK_F17) : [String(unicodeInt: NSF17FunctionKey)],
UInt(kVK_F18) : [String(unicodeInt: NSF18FunctionKey)],
UInt(kVK_F19) : [String(unicodeInt: NSF19FunctionKey)],
UInt(kVK_F20) : [String(unicodeInt: NSF20FunctionKey)],
UInt(kVK_Space) : ["\u{20}"],
UInt(kVK_Delete) : [String(unicodeInt: NSBackspaceCharacter)],
UInt(kVK_ForwardDelete) : [String(unicodeInt: NSDeleteCharacter)],
UInt(kVK_ANSI_KeypadClear) : [String(unicodeInt: NSClearLineFunctionKey)],
UInt(kVK_LeftArrow) : [String(unicodeInt: NSLeftArrowFunctionKey), "\u{2190}"],
UInt(kVK_RightArrow) : [String(unicodeInt: NSRightArrowFunctionKey), "\u{2192}"],
UInt(kVK_UpArrow) : [String(unicodeInt: NSUpArrowFunctionKey), "\u{2191}"],
UInt(kVK_DownArrow) : [String(unicodeInt: NSDownArrowFunctionKey), "\u{2193}"],
UInt(kVK_End) : [String(unicodeInt: NSEndFunctionKey)],
UInt(kVK_Home) : [String(unicodeInt: NSHomeFunctionKey)],
UInt(kVK_Escape) : ["\u{1b}"],
UInt(kVK_PageDown) : [String(unicodeInt: NSPageDownFunctionKey)],
UInt(kVK_PageUp) : [String(unicodeInt: NSPageUpFunctionKey)],
UInt(kVK_Return) : [String(unicodeInt: NSCarriageReturnCharacter)],
UInt(kVK_ANSI_KeypadEnter) : [String(unicodeInt: NSEnterCharacter)],
UInt(kVK_Tab) : [String(unicodeInt: NSTabCharacter)],
UInt(kVK_Help) : [String(unicodeInt: NSHelpFunctionKey)],
UInt(kVK_Function) : ["\u{F747}"]
]
}
struct Preferences {
// Identifier used to present Keys in Preferences window.
static let keysIdentifier = NSToolbarItem.Identifier(rawValue: "keysForSketch")
// Keys used to store settings in Preferences
static let kUserKeyEquivalents = "NSUserKeyEquivalents" as CFString
static let kCustomMenuApps = "com.apple.custommenu.apps" as CFString
static let kUniversalAccess = "com.apple.universalaccess" as CFString
}
struct Licensing {
/// Key for local storing of Licensing Info in UserDefaults.
static let kLicensingInfoDefaultsDict = "VDKLicensingInfo"
}
}
fileprivate extension String {
/// Init with unicode int value.
init(unicodeInt: Int) {
self = String(format: "%C", unicodeInt)
}
}
| 44.653061 | 178 | 0.609689 |
9cef4fd5ed76cc89138c15a09c7105cdc3ccec69 | 8,558 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !os(watchOS)
import UIKit
/// Displays a `OCKMultiGraphableView` above an axis. The initializer takes an enum `PlotType` that allows you to choose from
/// several common graph types.
///
/// +-------------------------------------------------------+
/// | |
/// | [title] |
/// | [detail] |
/// | |
/// | [graph] |
/// | |
/// +-------------------------------------------------------+
///
open class OCKCartesianGraphView: OCKView, OCKMultiPlotable {
/// An enumerator specifying the types of plots this view can display.
public enum PlotType: String, CaseIterable {
case line
case scatter
case bar
}
// MARK: Properties
/// The data points displayed in the graph.
public var dataSeries: [OCKDataSeries] {
get { return plotView.dataSeries }
set {
updateScaling(for: newValue)
plotView.dataSeries = newValue
legend.setDataSeries(newValue)
}
}
/// The labels for the horizontal axis.
public var horizontalAxisMarkers: [String] = [] {
didSet { axisView.axisMarkers = horizontalAxisMarkers }
}
/// A number formatter used for the vertical axis values
public var numberFormatter: NumberFormatter {
get { gridView.numberFormatter }
set { gridView.numberFormatter = newValue }
}
/// Get the bounds of the graph.
///
/// - Returns: The bounds of the graph.
public func graphBounds() -> CGRect {
return plotView.graphBounds()
}
/// The minimum x value in the graph.
public var xMinimum: CGFloat? {
get { return plotView.xMinimum }
set {
plotView.xMinimum = newValue
gridView.xMinimum = newValue
}
}
/// The maximum x value in the graph.
public var xMaximum: CGFloat? {
get { return plotView.xMaximum }
set {
plotView.xMaximum = newValue
gridView.xMaximum = newValue
}
}
/// The minimum y value in the graph.
public var yMinimum: CGFloat? {
get { return plotView.yMinimum }
set {
plotView.yMinimum = newValue
gridView.yMinimum = newValue
}
}
/// The maximum y value in the graph.
public var yMaximum: CGFloat? {
get { return plotView.yMaximum }
set {
plotView.yMaximum = newValue
gridView.yMaximum = newValue
}
}
/// The index of the selected label in the x-axis.
public var selectedIndex: Int? {
get { return axisView.selectedIndex }
set { axisView.selectedIndex = newValue }
}
private let gridView: OCKGridView
private let plotView: UIView & OCKMultiPlotable
private let axisView: OCKGraphAxisView
private let axisHeight: CGFloat = 44
private let horizontalPlotPadding: CGFloat = 50
private let legend = OCKGraphLegendView()
// MARK: - Life Cycle
/// Create a graph view with the specified style.
///
/// - Parameter plotType: The style of the graph view.
public init(type: PlotType) {
self.gridView = OCKGridView()
self.axisView = OCKGraphAxisView()
self.plotView = {
switch type {
case .line:
return OCKLinePlotView()
case .scatter:
return OCKScatterPlotView()
case .bar:
return OCKBarPlotView()
}
}()
super.init()
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Methods
override open func tintColorDidChange() {
super.tintColorDidChange()
applyTintColor()
}
private func updateScaling(for dataSeries: [OCKDataSeries]) {
let maxValue = max(CGFloat(gridView.numberOfDivisions), dataSeries.flatMap { $0.dataPoints }.map { $0.y }.max() ?? 0)
let chartMax = ceil(maxValue / CGFloat(gridView.numberOfDivisions)) * CGFloat(gridView.numberOfDivisions)
plotView.yMaximum = chartMax
gridView.yMaximum = chartMax
}
override func setup() {
super.setup()
[gridView, plotView, axisView, legend].forEach { addSubview($0) }
gridView.xMinimum = plotView.xMinimum
gridView.xMaximum = plotView.xMaximum
gridView.yMinimum = plotView.yMinimum
gridView.yMaximum = plotView.yMaximum
[gridView, plotView, axisView, legend].forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
let gridConstraints = [
gridView.topAnchor.constraint(equalTo: plotView.topAnchor),
gridView.leadingAnchor.constraint(equalTo: leadingAnchor),
gridView.trailingAnchor.constraint(equalTo: trailingAnchor),
gridView.bottomAnchor.constraint(equalTo: plotView.bottomAnchor)
]
let plotTrailing = plotView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -horizontalPlotPadding)
plotTrailing.priority -= 1
let plotBottom = plotView.bottomAnchor.constraint(equalTo: axisView.topAnchor)
plotBottom.priority -= 1
let plotConstraints = [
plotView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: horizontalPlotPadding),
plotTrailing,
plotView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
plotBottom
]
let axisTrailing = axisView.trailingAnchor.constraint(equalTo: plotView.trailingAnchor)
axisTrailing.priority -= 1
let axisBottom = axisView.bottomAnchor.constraint(equalTo: legend.topAnchor)
axisBottom.priority -= 1
let axisConstraints = [
axisView.leadingAnchor.constraint(equalTo: plotView.leadingAnchor),
axisTrailing,
axisView.heightAnchor.constraint(equalToConstant: axisHeight),
axisBottom
]
let legendWidth = legend.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor)
legendWidth.priority -= 1
let legendConstraints = [
legendWidth,
legend.centerXAnchor.constraint(equalTo: centerXAnchor),
legend.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
]
NSLayoutConstraint.activate(gridConstraints + plotConstraints + axisConstraints + legendConstraints)
applyTintColor()
}
private func applyTintColor() {
axisView.tintColor = tintColor
}
}
#endif
| 36.109705 | 140 | 0.63169 |
501174e669a6bbfde87ec737529577c520f3d30b | 25,801 | //
// ChatRoom.swift
// FireAlarm
//
// Created by NobodyNada on 8/27/16.
// Copyright © 2016 NobodyNada. All rights reserved.
//
import Foundation
import Dispatch
import Clibwebsockets
///A ChatRoom represents a Stack Exchange chat room.
open class ChatRoom: NSObject {
//MARK: - Instance variables
///A type of event from the chat room.
public enum ChatEvent: Int {
///Caused when a message is posted in the chat room
case messagePosted = 1
///Caused when a message is edited in the chat room
case messageEdited = 2
///Caused when a user entered the chat room
case userEntered = 3
///Caused when a user leaves the chat room
case userLeft = 4
///Caused when the name of the room is changed
case roomNameChanged = 5
///Caused when a message is stsrred in the chat room
case messageStarred = 6
case debugMessage = 7
///Caused when a user is mentioned in the chat room
case userMentioned = 8
///Caused when a message is flagged in the chat room
case messageFlagged = 9
///Caused when a message is deleted in the chat room
case messageDeleted = 10
///Caused when a file is uploaded in the chat room
case fileAdded = 11
///Caused when a message is mod flagged in the chat room
case moderatorFlag = 12
case userSettingsChanged = 13
case globalNotification = 14
case accessLevelChanged = 15
case userNotification = 16
///Caused when a user is invited to a chat room
case invitation = 17
///Caused when a message is replied to in a chat room
case messageReply = 18
///Caused when a Room Owner moves a message to another room
case messageMovedOut = 19
///Caused when a Room Owner moves a message to the room
case messageMovedIn = 20
///Caused when the room is placed in timeout
case timeBreak = 21
case feedTicker = 22
///Caused when a user is suspended
case userSuspended = 29
///Caused when a user is merged
case userMerged = 30
///Caused when a user's username has changed
case usernameChanged = 34
};
///The host the bot is running on.
public enum Host: Int {
///Used when the bot is running on 'stackoverflow.com'
case stackOverflow
///Used when the bot is running on 'stackexchange.com'
case stackExchange
///Used when the bot is running on 'meta.stackexchange.com'
case metaStackExchange
///Returns the domain for the specified host
public var domain: String {
switch self {
case .stackOverflow:
return "stackoverflow.com"
case .stackExchange:
return "stackexchange.com"
case .metaStackExchange:
return "meta.stackexchange.com"
}
}
///Returns the chat domain for the specified host
public var chatDomain: String {
return "chat." + domain
}
///Returns the domain URL for the host
public var url: URL {
return URL(string: "https://" + domain)!
}
///Returns the URL for the chat host
public var chatHostURL: URL {
return URL(string: "https://" + chatDomain)!
}
}
///The Client to use.
open let client: Client
///The ID of this room.
open let roomID: Int
///The Host of this room.
open let host: Host
///The list of known users.
open var userDB = [ChatUser]()
///The fkey used to authorize actions in chat.
open var fkey: String! {
if _fkey == nil {
//Get the chat fkey.
let joinFavorites: String = try! client.get("https://\(host.chatDomain)/chats/join/favorite")
guard let inputIndex = joinFavorites.range(of: "type=\"hidden\"")?.upperBound else {
fatalError("Could not find fkey")
}
let input = String(joinFavorites[inputIndex...])
guard let fkeyStartIndex = input.range(of: "value=\"")?.upperBound else {
fatalError("Could not find fkey")
}
let fkeyStart = String(input[fkeyStartIndex...])
guard let fkeyEnd = fkeyStart.range(of: "\"")?.lowerBound else {
fatalError("Could not find fkey")
}
_fkey = String(fkeyStart[..<fkeyEnd])
}
return _fkey
}
///The closure to run when a message is posted or edited.
open var messageHandler: (ChatMessage, Bool) -> () = {message, isEdit in}
///Runs a closure when a message is posted or edited.
open func onMessage(_ handler: @escaping (ChatMessage, Bool) -> ()) {
messageHandler = handler
}
///Whether the bot is currently in the chat room.
open private(set) var inRoom = false
///Messages that are waiting to be posted & their completion handlers.
open var messageQueue = [(String, ((Int?) -> Void)?)]()
///Custom per-room persistent storage. Must be serializable by JSONSerialization!
open var info: [String:Any] = [:]
private var _fkey: String!
private var ws: WebSocket!
private var wsRetries = 0
private let wsMaxRetries = 10
private var timestamp: Int = 0
private var lastEvent: Date?
private var pendingLookup = [ChatUser]()
private let defaultUserDBFilename: String
//MARK: - User management
internal func lookupUserInformation() {
do {
if pendingLookup.isEmpty {
return
}
print("Looking up \(pendingLookup.count) user\(pendingLookup.count == 1 ? "" : "s")...")
let ids = pendingLookup.map {user in
String(user.id)
}
let postData = [
"ids" : ids.joined(separator: ","),
"roomID" : "\(roomID)"
]
var data: Data, response: HTTPURLResponse
repeat {
(data, response) = try client.post(
"https://\(host.chatDomain)/user/info",
postData
)
} while response.statusCode == 400
let json = String(data: data, encoding: .utf8)!
do {
guard let results = try client.parseJSON(json) as? [String:Any] else {
throw EventError.jsonParsingFailed(json: json)
}
guard let users = results["users"] as? [Any] else {
throw EventError.jsonParsingFailed(json: json)
}
for obj in users {
guard let user = obj as? [String:Any] else {
throw EventError.jsonParsingFailed(json: json)
}
guard let id = user["id"] as? Int else {
throw EventError.jsonParsingFailed(json: json)
}
guard let name = user["name"] as? String else {
throw EventError.jsonParsingFailed(json: json)
}
let isMod = (user["is_moderator"] as? Bool) ?? false
//if user["is_owner"] is an NSNull, the user is NOT an owner.
let isRO = (user["is_owner"] as? NSNull) == nil ? true : false
let chatUser = userWithID(id)
chatUser.name = name
chatUser.isMod = isMod
chatUser.isRO = isRO
}
} catch {
handleError(error, "while looking up \(pendingLookup.count) users (json: \(json), request: \(String(urlParameters: postData)))")
}
pendingLookup.removeAll()
}
catch {
handleError(error, "while looking up \(pendingLookup)")
}
}
///Looks up a user by ID. If the user is not in the database, they are added.
open func userWithID(_ id: Int) -> ChatUser {
for user in userDB {
if user.id == id {
return user
}
}
let user = ChatUser(room: self, id: id)
userDB.append(user)
if id == 0 {
user.name = "Console"
}
else {
pendingLookup.append(user)
}
return user
}
///Looks up a user by name. The user must already exist in the database!
open func userNamed(_ name: String) -> [ChatUser] {
var users = [ChatUser]()
for user in userDB {
if user.name == name {
users.append(user)
}
}
return users
}
///Loads the user database from disk.
///- parameter filename: The filename to load the user databse from.
///The default value is `users_roomID_host.json`, for example `users_11347_stackoverflow.com.json` for SOBotics.
open func loadUserDB(filename: String? = nil) throws {
let file = filename ?? defaultUserDBFilename
guard let data = try? Data(contentsOf: saveFileNamed(file)) else {
return
}
guard let db = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] else {
return
}
info = (db["info"] as? [String:Any]) ?? [:]
guard let dbUsers = db["users"] as? [Any] else {
return
}
userDB = []
var users = userDB
for item in dbUsers {
guard let info = (item as? [String:Any]) else {
continue
}
guard let id = info["id"] as? Int else {
continue
}
let user = userWithID(id)
user.info = (info["info"] as? [String:Any]) ?? [:]
user.privileges = (info["privileges"] as? Int).map { ChatUser.Privileges(rawValue: UInt($0)) } ?? []
users.append(user)
}
userDB = users
}
///Saves the user database to disk.
///- parameter filename: The filename to save the user databse to.
///The default value is `users_roomID_host.json`, for example `users_11347_stackoverflow.com.json` for SOBotics.
open func saveUserDB(filename: String? = nil) throws {
let file = filename ?? defaultUserDBFilename
let db: Any
db = userDB.map {
[
"id":$0.id,
"info":$0.info,
"privileges":$0.privileges.rawValue
]
}
let data = try JSONSerialization.data(withJSONObject: ["info":info, "users":db], options: .prettyPrinted)
try data.write(to: saveFileNamed(file), options: [.atomic])
}
///Initializes a ChatRoom.
///- parameter client: The Client to use.
///- parameter roomID: The ID of the chat room.
public init(client: Client, host: Host, roomID: Int) {
self.client = client
self.host = host
self.roomID = roomID
defaultUserDBFilename = "room_\(roomID)_\(host.domain).json"
}
fileprivate func messageQueueHandler() {
while messageQueue.count != 0 {
var result: String? = nil
let text = messageQueue[0].0
let completion = messageQueue[0].1
do {
let (data, response) = try client.post(
"https://\(host.chatDomain)/chats/\(roomID)/messages/new",
["text":text, "fkey":fkey]
)
if response.statusCode == 400 {
print("Server error while posting message")
}
else {
result = String(data: data, encoding: .utf8)
}
}
catch {
handleError(error)
}
do {
if let json = result {
if let data = try client.parseJSON(json) as? [String:Any] {
if let id = data["id"] as? Int {
messageQueue.removeFirst()
completion?(id)
}
else {
print("Could not post duplicate message")
if !messageQueue.isEmpty {
messageQueue.removeFirst()
completion?(nil)
}
}
}
else {
print(json)
}
}
}
catch {
if let r = result {
print(r)
}
else {
handleError(error)
}
}
sleep(1)
}
}
///Posts a message to the ChatRoom.
///- paramter message: The content of the message to post, in Markdown.
///- parameter completion: The completion handler to call when the message is posted.
///The message ID will be passed to the completion handler.
open func postMessage(_ message: String, completion: ((Int?) -> Void)? = nil) {
if message.count == 0 {
return
}
messageQueue.append((message, completion))
if messageQueue.count == 1 {
DispatchQueue.global().async {
self.messageQueueHandler()
}
}
}
///Replies to a ChatMessage.
///- paramter reply: The content of the message to post, in Markdown.
///- parameter to: The message ID to reply to.
///- parameter username: The name of the user who posted the message to reply to.
/// If present, will be used as a fallback if the message ID is not present.
///
///- parameter completion: The completion handler to call when the message is posted.
///The message ID will be passed to the completion handler.
open func postReply(_ reply: String, to messageID: Int?, username: String? = nil, completion: ((Int?) -> Void)? = nil) {
if let id = messageID {
postMessage(":\(id) \(reply)", completion: completion)
} else if let name = username {
postMessage("@\(name) \(reply)", completion: completion)
} else {
postMessage(reply)
}
}
///Replies to a ChatMessage.
///- paramter reply: The content of the message to post, in Markdown.
///- parameter to: The ChatMessage to reply to.
///- parameter completion: The completion handler to call when the message is posted.
///The message ID will be passed to the completion handler.
open func postReply(_ reply: String, to: ChatMessage, completion: ((Int?) -> Void)? = nil) {
postReply(reply, to: to.id, username: to.user.name, completion: completion)
}
///An error that can occur while deleting a message
enum DeletionError: Error {
///The ChatMessage's ID was nil.
case noMessageID
///This user is not allowed to delete this message.
case notAllowed
///It is past the 2-minute deadline for deleting messages.
case tooLate
///An unknown error was returned.
case unknownError(result: String)
}
open func delete(_ messageID: Int) throws {
var retry = false
repeat {
if retry { sleep(1) }
let result: String = try client.post("https://\(host.chatDomain)/messages/\(messageID)/delete", ["fkey":fkey])
switch result.trimmingCharacters(in: CharacterSet(charactersIn: "\"")) {
case "ok":
break
case "It is too late to delete this message":
throw DeletionError.tooLate
case "You can only delete your own messages":
throw DeletionError.notAllowed
default:
if result.hasPrefix("You can perform this action again in") {
retry = true
} else {
throw DeletionError.unknownError(result: result)
}
}
} while retry
}
///Deletes a `ChatMessage`.
open func delete(_ message: ChatMessage) throws {
guard let id = message.id else { throw DeletionError.noMessageID }
try delete(id)
}
///Joins the chat room.
open func join() throws {
print("Joining chat room \(roomID)...")
try connectWS()
let _ = userWithID(0) //add the Console to the database
let json: String = try client.get("https://\(host.chatDomain)/rooms/pingable/\(roomID)")
guard let users = try client.parseJSON(json) as? [Any] else {
throw EventError.jsonParsingFailed(json: json)
}
for userObj in users {
guard let user = userObj as? [Any] else {
throw EventError.jsonParsingFailed(json: json)
}
guard let userID = user[0] as? Int else {
throw EventError.jsonParsingFailed(json: json)
}
let _ = userWithID(userID)
}
print("Users in database: \((userDB.map {$0.description}).joined(separator: ", "))")
inRoom = true
}
///Leaves the chat room.
open func leave() {
//we don't really care if this fails
//...right?
//Checking if the bot has already left the room
guard inRoom else { return }
inRoom = false
let _ = try? client.post("https://\(host.chatDomain)/chats/leave/\(roomID)", ["quiet":"true","fkey":fkey]) as String
ws.disconnect()
for _ in 0..<10 {
if ws.state == .disconnecting {
sleep(1)
}
}
}
///The errors which can be caused while the bot joins the room.
public enum RoomJoinError: Error {
///When the retrieval of information for a room failed.
case roomInfoRetrievalFailed
}
fileprivate func connectWS() throws {
//get the timestamp
guard let time = (try client.parseJSON(client.post("https://\(host.chatDomain)/chats/\(roomID)/events", [
"roomid" : String(roomID),
"fkey": fkey
])) as? [String:Any])?["time"] as? Int else {
throw RoomJoinError.roomInfoRetrievalFailed
}
timestamp = time
//get the auth code
let wsAuth = try client.parseJSON(
client.post("https://\(host.chatDomain)/ws-auth", ["roomid":String(roomID), "fkey":fkey]
)
) as! [String:Any]
let wsURL = (wsAuth["url"] as! String)
let url = URL(string: "\(wsURL)?l=\(timestamp)")!
//var request = URLRequest(url: url)
//request.setValue("https://chat.\(client.host.rawValue)", forHTTPHeaderField: "Origin")
//for (header, value) in client.cookieHeaders(forURL: url) {
// request.setValue(value, forHTTPHeaderField: header)
//}
//ws = WebSocket(request: request)
var headers = ""
for (header, value) in client.cookieHeaders(forURL: url) {
headers += "\(header): \(value)\u{0d}\u{0a}"
}
ws = try WebSocket(url, origin: host.chatDomain, headers: headers)
//ws.eventQueue = client.queue
//ws.delegate = self
//ws.open()
ws.onOpen {socket in
self.webSocketOpen()
}
ws.onText {socekt, text in
self.webSocketMessageText(text)
}
ws.onBinary {socket, data in
self.webSocketMessageData(data)
}
ws.onClose {socket in
self.webSocketEnd(0, reason: "", wasClean: true, error: socket.error)
}
ws.onError {socket in
self.webSocketEnd(0, reason: "", wasClean: true, error: socket.error)
}
try ws.connect()
}
///An error which happened while the bot was processing a chat event.
public enum EventError: Error {
///This is caused when the library cannot parse the specified json.
case jsonParsingFailed(json: String)
///This is caused when the chat room event type is invalid.
case invalidEventType(type: Int)
}
func handleEvents(_ events: [Any]) throws {
for e in events {
guard let event = e as? [String:Any] else {
throw EventError.jsonParsingFailed(json: String(describing: events))
}
guard let typeCode = event["event_type"] as? Int else {
throw EventError.jsonParsingFailed(json: String(describing: events))
}
guard let type = ChatEvent(rawValue: typeCode) else {
throw EventError.invalidEventType(type: typeCode)
}
switch type {
case .messagePosted, .messageEdited:
guard
let userID = event["user_id"] as? Int,
let messageID = event["message_id"] as? Int,
let rendered = (event["content"] as? String)?.stringByDecodingHTMLEntities else {
throw EventError.jsonParsingFailed(json: String(describing: events))
}
var replyID: Int? = nil
var content: String = try client.get("https://\(host.chatDomain)/message/\(messageID)?plain=true")
if let parent = event["parent_id"] as? Int {
replyID = parent
//replace the reply markdown with the rendered ping
var components = content.components(separatedBy: .whitespaces)
let renderedComponents = rendered.components(separatedBy: .whitespaces)
if !components.isEmpty && !rendered.isEmpty {
components[0] = renderedComponents[0]
content = components.joined(separator: " ")
}
}
//look up the user instead of getting their name to make sure they're in the DB
let user = userWithID(userID)
print("\(roomID): \(user): \(content)")
let message = ChatMessage(room: self, user: user, content: content, id: messageID, replyID: replyID)
messageHandler(message, type == .messageEdited)
default:
break
}
}
}
//MARK: - WebSocket methods
private func webSocketOpen() {
print("Websocket opened!")
//let _ = try? ws.write("hello")
wsRetries = 0
DispatchQueue.global().async {
sleep(5) //asyncAfter doesn't seem to work on Linux
if self.lastEvent == nil {
self.ws.disconnect()
return
}
while true {
sleep(600)
if Date().timeIntervalSinceReferenceDate - self.lastEvent!.timeIntervalSince1970 > 600 {
self.ws.disconnect()
return
}
}
}
}
private func webSocketMessageText(_ text: String) {
lastEvent = Date()
do {
guard let json = try client.parseJSON(text) as? [String:Any] else {
throw EventError.jsonParsingFailed(json: text)
}
if (json["action"] as? String) == "hb" {
//heartbeat
ws.write("{\"action\":\"hb\",\"data\":\"hb\"}")
return
}
let roomKey = "r\(roomID)"
guard let events = (json[roomKey] as? [String:Any])?["e"] as? [Any] else {
return //no events
}
try handleEvents(events)
}
catch {
handleError(error, "while parsing events")
}
}
private func webSocketMessageData(_ data: Data) {
print("Recieved binary data: \(data)")
}
private func attemptReconnect() {
var done = false
repeat {
do {
if wsRetries >= wsMaxRetries {
fatalError("Failed to reconnect websocket!")
}
wsRetries += 1
try connectWS()
done = true
} catch {
done = false
}
} while !done
}
private func webSocketEnd(_ code: Int, reason: String, wasClean: Bool, error: Error?) {
if let e = error {
print("Websocket error:\n\(e)")
}
else {
print("Websocket closed")
}
if inRoom {
print("Trying to reconnect...")
attemptReconnect()
}
}
}
| 34.447263 | 144 | 0.513895 |
0325a99424b78bea92775a25de4e1bf34ba678bb | 7,711 | import EUDCC
import Foundation
// MARK: - Constant
public extension EUDCC.ValidationRule {
/// Constant ValidationRule that will always return the given Bool result value
/// - Parameter result: The Bool resul value
static func constant(
_ result: Bool
) -> Self {
.init(tag: "\(result)") { _ in result }
}
}
// MARK: - EUDCC Content Type
public extension EUDCC.ValidationRule {
/// Has vaccination content ValidationRule
static var isVaccination: Self {
self.compare(
value: .keyPath(\.vaccination),
to: .constant(nil),
operator: !=,
tag: "isVaccination"
)
}
/// Has test content ValidationRule
static var isTest: Self {
self.compare(
value: .keyPath(\.test),
to: .constant(nil),
operator: !=,
tag: "isTest"
)
}
/// Has recover content ValidationRule
static var isRecovery: Self {
self.compare(
value: .keyPath(\.recovery),
to: .constant(nil),
operator: !=,
tag: "isRecovery"
)
}
}
// MARK: - EUDCC Vaccination
public extension EUDCC.ValidationRule {
/// Has received all vaccination doses
static var isVaccinationComplete: Self {
.isVaccination
&& .compare(
value: .keyPath(\.vaccination?.doseNumber),
to: .keyPath(\.vaccination?.totalSeriesOfDoses),
operator: ==,
tag: "isVaccinationComplete"
)
}
/// Vaccination can be considered as fully immunized
/// - Parameters:
/// - minimumDaysPast: The amount of minimum days past since the last vaccination. Default value `15`
/// - calendar: The Calendar that should be used. Default value `.current`
static func isFullyImmunized(
minimumDaysPast: Int = 15,
using calendar: Calendar = .current
) -> Self {
.isVaccinationComplete
&& .compare(
lhsDate: .currentDate,
rhsDate: .init(
.keyPath(\.vaccination?.dateOfVaccination),
adding: (.day, minimumDaysPast)
),
operator: >,
using: calendar,
tag: "isFullyImmunized-after-\(minimumDaysPast)-days"
)
}
/// Validates if the vaccination expired by comparing if the current Date
/// is greater than the date of vaccination added by the `maximumDaysSinceVaccinationDate`
/// - Parameters:
/// - maximumDaysSinceVaccinationDate: The maximum days since date of vaccination. Default value `365`
/// - calendar: The Calendar. Default value `.current`
static func isVaccinationExpired(
maximumDaysSinceVaccinationDate: Int = 365,
using calendar: Calendar = .current
) -> Self {
.isVaccination
&& .compare(
lhsDate: .currentDate,
rhsDate: .init(
.keyPath(\.vaccination?.dateOfVaccination),
adding: (.day, maximumDaysSinceVaccinationDate)
),
operator: >,
using: calendar,
tag: "is-vaccination-expired-\(maximumDaysSinceVaccinationDate)-days"
)
}
/// Validates if EUDCC contains a Vaccination and the `VaccineMedicinalProduct` value
/// is contained in the `WellKnownValue`enumeration
static var isWellKnownVaccineMedicinalProduct: Self {
.vaccineMedicinalProductIsOneOf(
EUDCC.Vaccination.VaccineMedicinalProduct.WellKnownValue.allCases
)
}
/// Validates if the `VaccineMedicinalProduct` is contained in the given Sequence of VaccineMedicinalProduct WellKnownValues
/// - Parameter validVaccineMedicinalProducts: The VaccineMedicinalProduct WellKnownValue Sequence
static func vaccineMedicinalProductIsOneOf<Vaccines: Sequence>(
_ validVaccineMedicinalProducts: Vaccines
) -> Self where Vaccines.Element == EUDCC.Vaccination.VaccineMedicinalProduct.WellKnownValue {
.isVaccination
&& .init(
tag: "isVaccineMedicinalProduct-one-of-\(validVaccineMedicinalProducts)"
) { eudcc in
// Verify WellKnownValue of VaccineMedicinalProduct is available
guard let vaccineMedicinalProductWellKnownValue = eudcc.vaccination?.vaccineMedicinalProduct.wellKnownValue else {
// Otherwise return false
return false
}
// Return result if VaccineMedicinalProduct WellKnownValue is contained in the given Sequence
return validVaccineMedicinalProducts.contains(vaccineMedicinalProductWellKnownValue)
}
}
}
// MARK: - EUDCC Test
public extension EUDCC.ValidationRule {
/// TestResult of Test is positive
static var isTestedPositive: Self {
.isTest
&& .compare(
value: .keyPath(\.test?.testResult.value),
to: .constant(EUDCC.Test.TestResult.WellKnownValue.positive.rawValue),
operator: ==,
tag: "isTestedPositive"
)
}
/// TestResult of Test is negative
static var isTestedNegative: Self {
.isTest
&& .compare(
value: .keyPath(\.test?.testResult.value),
to: .constant(EUDCC.Test.TestResult.WellKnownValue.negative.rawValue),
operator: ==,
tag: "isTestedNegative"
)
}
/// Is Test valid
/// - Parameters:
/// - maximumHoursPast: The maximum hours past since date of sample collection. Default value `PCR: 72 | RAPID: 48`
/// - calendar: The Calendar that should be used. Default value `.current`
static func isTestValid(
maximumHoursPast: @escaping (EUDCC.Test.TestType.WellKnownValue) -> Int = { $0 == .pcr ? 72 : 48 },
using calendar: Calendar = .current
) -> Self {
.isTest
&& .compare(
lhsDate: .currentDate,
rhsDate: .init(
.keyPath(\.test?.dateOfSampleCollection),
adding: { eudcc in
// Verify TestType WellKnownValue is available
guard let testTypeWellKnownValue = eudcc.test?.typeOfTest.wellKnownValue else {
// Otherwise return nil
return nil
}
// Return adding hour with maximum hours past for TestType WellKnownValue
return (.hour, maximumHoursPast(testTypeWellKnownValue))
}
),
operator: <=,
using: calendar,
tag: "isTestValid"
)
}
}
// MARK: - EUDCC Recovery
public extension EUDCC.ValidationRule {
/// Is Recovery valid
static var isRecoveryValid: Self {
.isRecovery
&& .init(tag: "isRecoveryValid") { eudcc in
// Verify Recovery is available
guard let recovery = eudcc.recovery else {
// Otherwise return false
return false
}
// Initialize valid Date Range
let validDateRange = recovery.certificateValidFrom...recovery.certificateValidUntil
// Return Bool value if current Date is contained in valid Date Range
return validDateRange.contains(.init())
}
}
}
| 35.210046 | 130 | 0.570354 |
01932fac179f8d295c87011933f79ebb6c1daea9 | 4,859 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
public protocol BeagleDependenciesProtocol: DependencyDecoder,
DependencyAnalyticsExecutor,
DependencyUrlBuilder,
DependencyNetworkClient,
DependencyDeepLinkScreenManaging,
DependencyNavigation,
DependencyViewConfigurator,
DependencyStyleViewConfigurator,
DependencyTheme,
DependencyPreFetching,
DependencyAppBundle,
DependencyViewClient,
DependencyImageDownloader,
DependencyLogger,
DependencyWindowManager,
DependencyURLOpener,
DependencyRenderer,
DependencyGlobalContext,
DependencyOperationsProvider {
}
open class BeagleDependencies: BeagleDependenciesProtocol {
public var decoder: ComponentDecoding
public var urlBuilder: UrlBuilderProtocol
public var networkClient: NetworkClient?
public var appBundle: Bundle
public var theme: Theme
public var deepLinkHandler: DeepLinkScreenManaging?
public var viewClient: ViewClient
public var imageDownloader: ImageDownloader
public var analyticsProvider: AnalyticsProvider?
public var navigation: BeagleNavigation
public var preFetchHelper: BeaglePrefetchHelping
public var windowManager: WindowManager
public var opener: URLOpener
public var globalContext: GlobalContext
public var operationsProvider: OperationsProvider
public var logger: BeagleLoggerType {
didSet {
logger = BeagleLoggerProxy(logger: logger)
}
}
// MARK: Builders
public var renderer: (BeagleController) -> BeagleRenderer = {
return BeagleRenderer(controller: $0)
}
public var style: (UIView) -> StyleViewConfiguratorProtocol = {
return StyleViewConfigurator(view: $0)
}
public var viewConfigurator: (UIView) -> ViewConfiguratorProtocol = {
return ViewConfigurator(view: $0)
}
private let resolver: InnerDependenciesResolver
public init(networkClient: NetworkClient? = nil, logger: BeagleLoggerType? = nil) {
let resolver = InnerDependenciesResolver()
self.resolver = resolver
self.urlBuilder = UrlBuilder()
self.preFetchHelper = BeaglePreFetchHelper(dependencies: resolver)
self.appBundle = Bundle.main
self.theme = AppTheme(styles: [:])
self.logger = BeagleLoggerProxy(logger: logger)
self.operationsProvider = OperationsDefault(dependencies: resolver)
self.decoder = ComponentDecoder()
self.windowManager = WindowManagerDefault()
self.navigation = BeagleNavigator()
self.globalContext = DefaultGlobalContext()
self.networkClient = networkClient
self.viewClient = ViewClientDefault(dependencies: resolver)
self.imageDownloader = ImageDownloaderDefault(dependencies: resolver)
self.opener = URLOpenerDefault(dependencies: resolver)
self.resolver.container = { [unowned self] in self }
}
}
// MARK: Resolver
/// This class helps solving the problem of using the same dependency container to resolve
/// dependencies within dependencies.
/// The problem happened because we needed to pass `self` as dependency before `init` has concluded.
/// - Example: see where `resolver` is being used in the `BeagleDependencies` `init`.
private class InnerDependenciesResolver: ViewClientDefault.Dependencies,
DependencyDeepLinkScreenManaging,
DependencyViewClient,
DependencyWindowManager,
DependencyURLOpener {
var container: () -> BeagleDependenciesProtocol = {
fatalError("You should set this closure to get the dependencies container")
}
var decoder: ComponentDecoding { return container().decoder }
var urlBuilder: UrlBuilderProtocol { return container().urlBuilder }
var networkClient: NetworkClient? { return container().networkClient }
var navigation: BeagleNavigation { return container().navigation }
var deepLinkHandler: DeepLinkScreenManaging? { return container().deepLinkHandler }
var logger: BeagleLoggerType { return container().logger }
var viewClient: ViewClient { return container().viewClient }
var windowManager: WindowManager { return container().windowManager }
var opener: URLOpener { return container().opener }
}
| 37.091603 | 100 | 0.735542 |
d937aebaf11d4746b025a4a76c6515f2baecac99 | 2,528 | //
// Graph.swift
// aoc
//
// Created by Paul Uhn on 12/20/18.
// Copyright © 2018 Rightpoint. All rights reserved.
//
import Foundation
class Graph<T: Hashable> {
struct GraphNode<T: Hashable>: Hashable {
let value: T
let index: Int
init(_ v: T, _ i: Int) { value = v; index = i }
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func == (lhs: GraphNode, rhs: GraphNode) -> Bool {
return lhs.value == rhs.value
}
}
typealias Node = GraphNode<T>
struct GraphLink {
let from: Node
let to: Node
let weight: Double?
}
private class GraphLinkList {
let node: Node
var edges = [GraphLink]()
init(_ n: Node) { node = n }
func add(_ e: GraphLink) { edges.append(e) }
}
private var list = [GraphLinkList]()
var nodes: [Node] {
return list.map { $0.node }
}
var links: [GraphLink] {
return list.flatMap { $0.edges }
}
func create(_ value: T) -> Node {
if let matching = list.first(where: { $0.node.value == value }) {
return matching.node
}
let node = Node(value, list.count)
list.append(GraphLinkList(node))
return node
}
func link(_ from: Node, to: Node, weight: Double? = nil) {
list[from.index].add(GraphLink(from: from, to: to, weight: weight))
}
func weight(_ from: Node, to: Node) -> Double? {
return list[from.index].edges.first { $0.to == to }?.weight
}
func links(_ from: Node) -> [GraphLink] {
return list[from.index].edges
}
func unlink(_ from: Node, to: Node) {
guard let index = list[from.index].edges.firstIndex(where: { $0.to == to }) else { return }
list[from.index].edges.remove(at: index)
}
}
extension Graph.GraphNode: CustomStringConvertible {
var description: String {
return "\(value)"
}
}
extension Graph.GraphLink: CustomStringConvertible {
var description: String {
return "\(to.value)\(weight != nil ? ":\(weight!)" : "")"
}
}
extension Graph: CustomStringConvertible {
var description: String {
return list.reduce("") { $0 + "\($1.node) -> \($1.edges)\n" }
}
}
extension Graph where T == Point { // for a_star
func data(initial: Int) -> [Point: Int] {
return nodes.reduce(into: [Point: Int]()) {
$0[$1.value] = initial
}
}
}
| 26.893617 | 99 | 0.550633 |
0addbfcc389248219b7947e4fb806c4fd09dbdef | 4,153 | //
// CourseDetailsViewController.swift
// RedRoster
//
// Created by Daniel Li on 3/30/16.
// Copyright © 2016 dantheli. All rights reserved.
//
import UIKit
class CourseDetailsViewController: UIViewController {
var tableView: UITableView!
var course: Course!
var sections: [String] = []
var sectionsDict: [String : [NSMutableAttributedString]] = [:]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.rosterBackgroundColor()
setupData()
setupTableView()
}
func setupData() {
if !course.courseDescription.isEmpty {
let title = "Course Description"
sectionsDict[title] = [NSMutableAttributedString(string: course.courseDescription)]
sections.append(title)
}
if !course.crosslistings.isEmpty {
let title = "Cross Listings"
sectionsDict[title] = course.crosslistings.map { NSMutableAttributedString(string: $0.shortHand) }
sections.append(title)
}
if !course.prerequisitesString.isEmpty {
let title = "Prerequisites"
sectionsDict[title] = [NSMutableAttributedString(string: course.prerequisitesString)]
sections.append(title)
}
// if let instructors = course.availableSections
// .flatMap({ $0.instructors })
// .flatMap({ $0 })
// where !instructors.isEmpty {
// let title = "Instructors"
// var instructorSet: [Instructor] = []
//
// for instructor in instructors {
// if !instructorSet.contains({ $0.netID == instructor.netID }) {
// instructorSet.append(instructor)
// }
// }
//
// sectionsDict[title] = instructorSet.map {
// let string = NSMutableAttributedString(string: $0.name, attributes: [NSForegroundColorAttributeName : UIColor.rosterCellTitleColor()])
// string.appendAttributedString(NSMutableAttributedString(string: " " + $0.netID, attributes: [NSForegroundColorAttributeName : UIColor.rosterCellSubtitleColor()]))
// return string
// }
//
// sections.append(title)
// }
}
func setupTableView() {
tableView = UITableView(frame: view.frame, style: .grouped)
tableView.autoresizingMask = .flexibleHeight
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: "CourseDetailCell", bundle: nil), forCellReuseIdentifier: "CourseDetailCell")
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
tableView.allowsSelection = false
tableView.backgroundColor = UIColor.clear
tableView.separatorColor = UIColor.rosterCellSeparatorColor()
view.addSubview(tableView)
}
}
extension CourseDetailsViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionsDict[sections[section]]?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CourseDetailCell", for: indexPath) as! CourseDetailCell
let attributedText = sectionsDict[sections[indexPath.section]]![indexPath.row]
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.rosterCellTitleColor(), range: NSRange(location: 0, length: attributedText.length))
cell.contentLabel.attributedText = attributedText
cell.backgroundColor = UIColor.rosterCellBackgroundColor()
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
}
| 37.754545 | 180 | 0.637852 |
1e747dba41c84e5503c2ca74ef95e216f561f58c | 840 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "PINOperation",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(name: "PINOperation", targets: ["PINOperation"]),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(name: "PINOperation", path: "Source", publicHeadersPath: "."),
.testTarget(name: "PINOperationTests", dependencies: ["PINOperation"], path: "Tests")
]
)
| 44.210526 | 122 | 0.694048 |
50dfba8b30566159429e95bbfca64f37ca54da59 | 15,896 | //
// ImagingStudy.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/ImagingStudy) on 2019-11-19.
// 2019, SMART Health IT.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/**
A set of images produced in single study (one or more series of references images).
Representation of the content produced in a DICOM imaging study. A study comprises a set of series, each of which
includes a set of Service-Object Pair Instances (SOP Instances - images or other data) acquired or produced in a common
context. A series is of only one modality (e.g. X-ray, CT, MR, ultrasound), but a study may have multiple series of
different modalities.
*/
open class ImagingStudy: DomainResource {
override open class var resourceType: String {
get { return "ImagingStudy" }
}
/// Request fulfilled.
public var basedOn: [Reference]?
/// Institution-generated description.
public var description_fhir: FHIRString?
/// Encounter with which this imaging study is associated.
public var encounter: Reference?
/// Study access endpoint.
public var endpoint: [Reference]?
/// Identifiers for the whole study.
public var identifier: [Identifier]?
/// Who interpreted images.
public var interpreter: [Reference]?
/// Where ImagingStudy occurred.
public var location: Reference?
/// All series modality if actual acquisition modalities.
public var modality: [Coding]?
/// User-defined comments.
public var note: [Annotation]?
/// Number of Study Related Instances.
public var numberOfInstances: FHIRInteger?
/// Number of Study Related Series.
public var numberOfSeries: FHIRInteger?
/// The performed procedure code.
public var procedureCode: [CodeableConcept]?
/// The performed Procedure reference.
public var procedureReference: Reference?
/// Why the study was requested.
public var reasonCode: [CodeableConcept]?
/// Why was study performed.
public var reasonReference: [Reference]?
/// Referring physician.
public var referrer: Reference?
/// Each study has one or more series of instances.
public var series: [ImagingStudySeries]?
/// When the study was started.
public var started: DateTime?
/// The current state of the ImagingStudy.
public var status: ImagingStudyStatus?
/// Who or what is the subject of the study.
public var subject: Reference?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(status: ImagingStudyStatus, subject: Reference) {
self.init()
self.status = status
self.subject = subject
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
basedOn = createInstances(of: Reference.self, for: "basedOn", in: json, context: &instCtx, owner: self) ?? basedOn
description_fhir = createInstance(type: FHIRString.self, for: "description", in: json, context: &instCtx, owner: self) ?? description_fhir
encounter = createInstance(type: Reference.self, for: "encounter", in: json, context: &instCtx, owner: self) ?? encounter
endpoint = createInstances(of: Reference.self, for: "endpoint", in: json, context: &instCtx, owner: self) ?? endpoint
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
interpreter = createInstances(of: Reference.self, for: "interpreter", in: json, context: &instCtx, owner: self) ?? interpreter
location = createInstance(type: Reference.self, for: "location", in: json, context: &instCtx, owner: self) ?? location
modality = createInstances(of: Coding.self, for: "modality", in: json, context: &instCtx, owner: self) ?? modality
note = createInstances(of: Annotation.self, for: "note", in: json, context: &instCtx, owner: self) ?? note
numberOfInstances = createInstance(type: FHIRInteger.self, for: "numberOfInstances", in: json, context: &instCtx, owner: self) ?? numberOfInstances
numberOfSeries = createInstance(type: FHIRInteger.self, for: "numberOfSeries", in: json, context: &instCtx, owner: self) ?? numberOfSeries
procedureCode = createInstances(of: CodeableConcept.self, for: "procedureCode", in: json, context: &instCtx, owner: self) ?? procedureCode
procedureReference = createInstance(type: Reference.self, for: "procedureReference", in: json, context: &instCtx, owner: self) ?? procedureReference
reasonCode = createInstances(of: CodeableConcept.self, for: "reasonCode", in: json, context: &instCtx, owner: self) ?? reasonCode
reasonReference = createInstances(of: Reference.self, for: "reasonReference", in: json, context: &instCtx, owner: self) ?? reasonReference
referrer = createInstance(type: Reference.self, for: "referrer", in: json, context: &instCtx, owner: self) ?? referrer
series = createInstances(of: ImagingStudySeries.self, for: "series", in: json, context: &instCtx, owner: self) ?? series
started = createInstance(type: DateTime.self, for: "started", in: json, context: &instCtx, owner: self) ?? started
status = createEnum(type: ImagingStudyStatus.self, for: "status", in: json, context: &instCtx) ?? status
if nil == status && !instCtx.containsKey("status") {
instCtx.addError(FHIRValidationError(missing: "status"))
}
subject = createInstance(type: Reference.self, for: "subject", in: json, context: &instCtx, owner: self) ?? subject
if nil == subject && !instCtx.containsKey("subject") {
instCtx.addError(FHIRValidationError(missing: "subject"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "basedOn", using: self.basedOn, errors: &errors)
self.description_fhir?.decorate(json: &json, withKey: "description", errors: &errors)
self.encounter?.decorate(json: &json, withKey: "encounter", errors: &errors)
arrayDecorate(json: &json, withKey: "endpoint", using: self.endpoint, errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
arrayDecorate(json: &json, withKey: "interpreter", using: self.interpreter, errors: &errors)
self.location?.decorate(json: &json, withKey: "location", errors: &errors)
arrayDecorate(json: &json, withKey: "modality", using: self.modality, errors: &errors)
arrayDecorate(json: &json, withKey: "note", using: self.note, errors: &errors)
self.numberOfInstances?.decorate(json: &json, withKey: "numberOfInstances", errors: &errors)
self.numberOfSeries?.decorate(json: &json, withKey: "numberOfSeries", errors: &errors)
arrayDecorate(json: &json, withKey: "procedureCode", using: self.procedureCode, errors: &errors)
self.procedureReference?.decorate(json: &json, withKey: "procedureReference", errors: &errors)
arrayDecorate(json: &json, withKey: "reasonCode", using: self.reasonCode, errors: &errors)
arrayDecorate(json: &json, withKey: "reasonReference", using: self.reasonReference, errors: &errors)
self.referrer?.decorate(json: &json, withKey: "referrer", errors: &errors)
arrayDecorate(json: &json, withKey: "series", using: self.series, errors: &errors)
self.started?.decorate(json: &json, withKey: "started", errors: &errors)
self.status?.decorate(json: &json, withKey: "status", errors: &errors)
if nil == self.status {
errors.append(FHIRValidationError(missing: "status"))
}
self.subject?.decorate(json: &json, withKey: "subject", errors: &errors)
if nil == self.subject {
errors.append(FHIRValidationError(missing: "subject"))
}
}
}
/**
Each study has one or more series of instances.
Each study has one or more series of images or other content.
*/
open class ImagingStudySeries: BackboneElement {
override open class var resourceType: String {
get { return "ImagingStudySeries" }
}
/// Body part examined.
public var bodySite: Coding?
/// A short human readable summary of the series.
public var description_fhir: FHIRString?
/// Series access endpoint.
public var endpoint: [Reference]?
/// A single SOP instance from the series.
public var instance: [ImagingStudySeriesInstance]?
/// Body part laterality.
public var laterality: Coding?
/// The modality of the instances in the series.
public var modality: Coding?
/// Numeric identifier of this series.
public var number: FHIRInteger?
/// Number of Series Related Instances.
public var numberOfInstances: FHIRInteger?
/// Who performed the series.
public var performer: [ImagingStudySeriesPerformer]?
/// Specimen imaged.
public var specimen: [Reference]?
/// When the series started.
public var started: DateTime?
/// DICOM Series Instance UID for the series.
public var uid: FHIRString?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(modality: Coding, uid: FHIRString) {
self.init()
self.modality = modality
self.uid = uid
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
bodySite = createInstance(type: Coding.self, for: "bodySite", in: json, context: &instCtx, owner: self) ?? bodySite
description_fhir = createInstance(type: FHIRString.self, for: "description", in: json, context: &instCtx, owner: self) ?? description_fhir
endpoint = createInstances(of: Reference.self, for: "endpoint", in: json, context: &instCtx, owner: self) ?? endpoint
instance = createInstances(of: ImagingStudySeriesInstance.self, for: "instance", in: json, context: &instCtx, owner: self) ?? instance
laterality = createInstance(type: Coding.self, for: "laterality", in: json, context: &instCtx, owner: self) ?? laterality
modality = createInstance(type: Coding.self, for: "modality", in: json, context: &instCtx, owner: self) ?? modality
if nil == modality && !instCtx.containsKey("modality") {
instCtx.addError(FHIRValidationError(missing: "modality"))
}
number = createInstance(type: FHIRInteger.self, for: "number", in: json, context: &instCtx, owner: self) ?? number
numberOfInstances = createInstance(type: FHIRInteger.self, for: "numberOfInstances", in: json, context: &instCtx, owner: self) ?? numberOfInstances
performer = createInstances(of: ImagingStudySeriesPerformer.self, for: "performer", in: json, context: &instCtx, owner: self) ?? performer
specimen = createInstances(of: Reference.self, for: "specimen", in: json, context: &instCtx, owner: self) ?? specimen
started = createInstance(type: DateTime.self, for: "started", in: json, context: &instCtx, owner: self) ?? started
uid = createInstance(type: FHIRString.self, for: "uid", in: json, context: &instCtx, owner: self) ?? uid
if nil == uid && !instCtx.containsKey("uid") {
instCtx.addError(FHIRValidationError(missing: "uid"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.bodySite?.decorate(json: &json, withKey: "bodySite", errors: &errors)
self.description_fhir?.decorate(json: &json, withKey: "description", errors: &errors)
arrayDecorate(json: &json, withKey: "endpoint", using: self.endpoint, errors: &errors)
arrayDecorate(json: &json, withKey: "instance", using: self.instance, errors: &errors)
self.laterality?.decorate(json: &json, withKey: "laterality", errors: &errors)
self.modality?.decorate(json: &json, withKey: "modality", errors: &errors)
if nil == self.modality {
errors.append(FHIRValidationError(missing: "modality"))
}
self.number?.decorate(json: &json, withKey: "number", errors: &errors)
self.numberOfInstances?.decorate(json: &json, withKey: "numberOfInstances", errors: &errors)
arrayDecorate(json: &json, withKey: "performer", using: self.performer, errors: &errors)
arrayDecorate(json: &json, withKey: "specimen", using: self.specimen, errors: &errors)
self.started?.decorate(json: &json, withKey: "started", errors: &errors)
self.uid?.decorate(json: &json, withKey: "uid", errors: &errors)
if nil == self.uid {
errors.append(FHIRValidationError(missing: "uid"))
}
}
}
/**
A single SOP instance from the series.
A single SOP instance within the series, e.g. an image, or presentation state.
*/
open class ImagingStudySeriesInstance: BackboneElement {
override open class var resourceType: String {
get { return "ImagingStudySeriesInstance" }
}
/// The number of this instance in the series.
public var number: FHIRInteger?
/// DICOM class type.
public var sopClass: Coding?
/// Description of instance.
public var title: FHIRString?
/// DICOM SOP Instance UID.
public var uid: FHIRString?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(sopClass: Coding, uid: FHIRString) {
self.init()
self.sopClass = sopClass
self.uid = uid
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
number = createInstance(type: FHIRInteger.self, for: "number", in: json, context: &instCtx, owner: self) ?? number
sopClass = createInstance(type: Coding.self, for: "sopClass", in: json, context: &instCtx, owner: self) ?? sopClass
if nil == sopClass && !instCtx.containsKey("sopClass") {
instCtx.addError(FHIRValidationError(missing: "sopClass"))
}
title = createInstance(type: FHIRString.self, for: "title", in: json, context: &instCtx, owner: self) ?? title
uid = createInstance(type: FHIRString.self, for: "uid", in: json, context: &instCtx, owner: self) ?? uid
if nil == uid && !instCtx.containsKey("uid") {
instCtx.addError(FHIRValidationError(missing: "uid"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.number?.decorate(json: &json, withKey: "number", errors: &errors)
self.sopClass?.decorate(json: &json, withKey: "sopClass", errors: &errors)
if nil == self.sopClass {
errors.append(FHIRValidationError(missing: "sopClass"))
}
self.title?.decorate(json: &json, withKey: "title", errors: &errors)
self.uid?.decorate(json: &json, withKey: "uid", errors: &errors)
if nil == self.uid {
errors.append(FHIRValidationError(missing: "uid"))
}
}
}
/**
Who performed the series.
Indicates who or what performed the series and how they were involved.
*/
open class ImagingStudySeriesPerformer: BackboneElement {
override open class var resourceType: String {
get { return "ImagingStudySeriesPerformer" }
}
/// Who performed the series.
public var actor: Reference?
/// Type of performance.
public var function: CodeableConcept?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(actor: Reference) {
self.init()
self.actor = actor
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
actor = createInstance(type: Reference.self, for: "actor", in: json, context: &instCtx, owner: self) ?? actor
if nil == actor && !instCtx.containsKey("actor") {
instCtx.addError(FHIRValidationError(missing: "actor"))
}
function = createInstance(type: CodeableConcept.self, for: "function", in: json, context: &instCtx, owner: self) ?? function
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.actor?.decorate(json: &json, withKey: "actor", errors: &errors)
if nil == self.actor {
errors.append(FHIRValidationError(missing: "actor"))
}
self.function?.decorate(json: &json, withKey: "function", errors: &errors)
}
}
| 42.731183 | 150 | 0.726472 |
d63d633b234c02169e228e66a1255824faeae371 | 4,544 | //
// GoalsLibraryPresenter.swift
// Emojical
//
// Created by Vladimir Svidersky on 2/6/21.
// Copyright © 2021 Vladimir Svidersky. All rights reserved.
//
import Foundation
import UIKit
class GoalsLibraryPresenter: GoalsLibraryPresenterProtocol {
// MARK: - DI
private let repository: DataRepository
private weak var view: GoalsLibraryView?
// MARK: - Built-in data
private let data: [GoalExampleData] = [
GoalExampleData(
category: "Health",
name: "Play Soccer",
description: "Record your soccer practices and try to get to 3 times per week.",
direction: .positive,
period: .week,
limit: 3,
stickers: [
StickerExampleData(emoji: "⚽️", name: "Soccer", color: UIColor(named: "emojiGreen")!)
],
extra: []
),
GoalExampleData(
category: "Health",
name: "Be Active",
description: "Record your activities - 🧘,⚽️,⛹🏻♀️,🚴🏻,🏓. Try to do this 5 times per week.",
direction: .positive,
period: .week,
limit: 5,
stickers: [
StickerExampleData(emoji: "🧘", name: "Yoga", color: UIColor(named: "emojiYellow")!),
StickerExampleData(emoji: "⚽️", name: "Soccer", color: UIColor(named: "emojiGreen")!),
StickerExampleData(emoji: "⛹🏻♀️", name: "Basketball", color: UIColor(named: "emojiLightGreen")!),
StickerExampleData(emoji: "🚴🏻", name: "Bike", color: UIColor(named: "emojiLightGreen")!),
StickerExampleData(emoji: "🏓", name: "Ping-pong", color: UIColor(named: "emojiGreen")!),
],
extra: []
),
GoalExampleData(
category: "Food",
name: "Eat Less Red Meat",
description: "Record food you eat - 🥩,🐣,🐟,🥦. And try to have 3 of fewer red meats per week.",
direction: .negative,
period: .week,
limit: 3,
stickers: [
StickerExampleData(emoji: "🥩", name: "Steak", color: UIColor(named: "emojiRed")!),
],
extra: [
StickerExampleData(emoji: "🐣", name: "Chicken", color: UIColor(named: "emojiGreen")!),
StickerExampleData(emoji: "🐟", name: "Fish", color: UIColor(named: "emojiGreen")!),
StickerExampleData(emoji: "🥦", name: "Veggies", color: UIColor(named: "emojiLightGreen")!),
]
)
]
// MARK: - Lifecycle
init(
repository: DataRepository,
view: GoalsLibraryView
) {
self.repository = repository
self.view = view
}
/// Called when view finished initial loading.
func onViewDidLoad() {
setupView()
}
/// Called when view about to appear on the screen
func onViewWillAppear() {
loadViewData()
}
// MARK: - Private helpers
private func setupView() {
view?.onGoalTapped = { [weak self] goalName in
self?.createGoal(goalName)
self?.view?.dismiss()
}
view?.onCancelTapped = { [weak self] in
self?.view?.dismiss()
}
}
private func loadViewData() {
view?.updateTitle("goals_library_title".localized)
let sections = Array(Set(data.map({ $0.category })))
view?.loadData(sections: sections, goals: data)
}
private func createSticker(_ data: StickerExampleData) -> Int64? {
if let found = repository.stampByLabel(label: data.emoji) {
return found.id
}
do {
let new = Stamp(
name: data.name,
label: data.emoji,
color: data.color
)
let saved = try repository.save(stamp: new)
return saved.id
}
catch {}
return nil
}
private func createGoal(_ name: String) {
guard let goal = data.first(where: { $0.name == name }) else { return }
let stickerIds = goal.stickers.compactMap({ createSticker($0) })
_ = goal.extra.map({ createSticker($0) })
do {
let new = Goal(
name: goal.name,
period: goal.period,
direction: goal.direction,
limit: goal.limit,
stamps: stickerIds
)
try repository.save(goal: new)
}
catch {}
}
}
| 31.555556 | 114 | 0.526188 |
16bda752a336d1fc1db08f1c1a00865813b41efa | 4,661 | /// MIT License
///
/// Copyright (c) 2020 Liam Nichols
///
/// 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 ListItemFormatter
class ListPatternBuilderTests: XCTestCase {
let patterns = Format.Patterns(listPatterns: [
"2": "{0} [2] {1}",
"6": "{5} {4} {3} {2} {1} {0}",
"7": "{0} {1} {2} {3} {4} {5} {6}",
"start": "{0} [START] {1}",
"middle": "{0} [MIDDLE] {1}",
"end": "{0} [END] {1}"
])!
func testNoItemsItems() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: [])
XCTAssertEqual(result.string, "")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, [])
}
func testSinguleItem() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["ONE"])
XCTAssertEqual(result.string, "ONE")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["ONE"])
}
func testFixedAmount2() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["ONE", "TWO"])
XCTAssertEqual(result.string, "ONE [2] TWO")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["ONE", "TWO"])
}
func testAllPatternsUsed() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["ONE", "TWO", "THREE", "FOUR"])
XCTAssertEqual(result.string, "ONE [START] TWO [MIDDLE] THREE [END] FOUR")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["ONE", "TWO", "THREE", "FOUR"])
}
func testMiddleUsedRepeatedly() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["ONE", "TWO", "THREE", "FOUR", "FIVE"])
XCTAssertEqual(result.string, "ONE [START] TWO [MIDDLE] THREE [MIDDLE] FOUR [END] FIVE")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["ONE", "TWO", "THREE", "FOUR", "FIVE"])
}
func testFormatArgumentOrdering() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX"])
XCTAssertEqual(result.string, "SIX FIVE FOUR THREE TWO ONE")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["SIX", "FIVE", "FOUR", "THREE", "TWO", "ONE"])
}
func testFormatArgumentWithNoOrdering() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN"])
XCTAssertEqual(result.string, "ONE TWO THREE FOUR FIVE SIX SEVEN")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN"])
}
func testFormatArgumentWithUnicodeWeirdness() {
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["👍🏽", "👍", "👍👎🏼", "👍👍🏽👍"])
XCTAssertEqual(result.string, "👍🏽 [START] 👍 [MIDDLE] 👍👎🏼 [END] 👍👍🏽👍")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["👍🏽", "👍", "👍👎🏼", "👍👍🏽👍"])
}
func testWithCombiningCharacters() {
// https://en.wikipedia.org/wiki/Combining_character
let builder = ListPatternBuilder(patterns: patterns)
let result = builder.build(from: ["A", "B", "َC", "َD"])
XCTAssertEqual(result.string, "A [START] B [MIDDLE] َC [END] َD")
XCTAssertEqual(result.itemRanges.map { result.string[$0] }, ["A", "B", "َC", "َD"])
}
}
| 42.372727 | 124 | 0.63141 |
0e596942869477361ced25fccfbd72c7711697aa | 1,504 | //
// RatingView.swift
// TechnicalTest
//
// Created by Alan Roldán Maillo on 02/03/2020.
// Copyright © 2020 Alan Roldán Maillo. All rights reserved.
//
import UIKit
class RatingView: UIView {
@IBOutlet weak var label: EdgeInsetLabel! {
didSet {
label.layer.masksToBounds = true
label.layer.cornerRadius = 5
}
}
@IBOutlet private var stars: [UIImageView]!
func update(with rating: Double, tint: UIColor? = nil) {
updateView(with: rating, tint: tint)
}
}
private extension RatingView {
enum Constants {
static let star = "star"
static let starFill = "star.fill"
static let starMiddle = "star.lefthalf.fill"
}
func updateView(with value: Double, tint: UIColor?) {
let ratingString = (String(format: "%.1f", value))
let ratinFloat = Float(ratingString) ?? 0
let mark = Int(ratinFloat)
for i in 0 ... stars.count-1 {
stars[i].image = UIImage(systemName: Constants.star)
if i <= mark {
if i == mark{
if ratinFloat > Float(mark) {
stars[i].image = UIImage(systemName: Constants.starMiddle)
}
} else {
stars[i].image = UIImage(systemName: Constants.starFill)
}
}
stars[i].tintColor = tint
}
label.text = ratingString
label.backgroundColor = tint
}
}
| 27.345455 | 82 | 0.550532 |
e5dc012b4d3d4b695aefa60e3ca20e05d37fa9fa | 14,562 |
// RUN: %target-swift-frontend -module-name let_properties_opts %s -O -enforce-exclusivity=checked -emit-sil | %FileCheck -check-prefix=CHECK-WMO %s
// RUN: %target-swift-frontend -module-name let_properties_opts -primary-file %s -O -emit-sil | %FileCheck %s
// Test propagation of non-static let properties with compile-time constant values.
// TODO: Once this optimization can remove the propagated fileprivate/internal let properties or
// mark them as ones without a storage, new tests should be added here to check for this
// functionality.
// FIXME: This test is written in Swift instead of SIL, because there are some problems
// with SIL deserialization (rdar://22636911)
// Check that initializers do not contain a code to initialize fileprivate or
// internal (if used with WMO) properties, because their values are propagated into
// their uses and they cannot be accessed from other modules. Therefore the
// initialization code could be removed.
// Specifically, the initialization code for Prop1, Prop2 and Prop3 can be removed.
// CHECK-WMO-LABEL: sil @$S19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int32, @owned Foo) -> @owned Foo
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: return
// CHECK-WMO-LABEL: sil @$S19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int64, @owned Foo) -> @owned Foo
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO-NOT: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK-WMO: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK-WMO: return
// Check that initializers do not contain a code to initialize fileprivate properties,
// because their values are propagated into their uses and they cannot be accessed
// from other modules. Therefore the initialization code could be removed.
// Specifically, the initialization code for Prop2 can be removed.
// CHECK-LABEL: sil @$S19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int32, @owned Foo) -> @owned Foo
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK: return
// CHECK-LABEL: sil @$S19let_properties_opts3FooC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int64, @owned Foo) -> @owned Foo
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop1
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop2
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo, #Foo.Prop3
// CHECK: return
public class Foo {
public let Prop0: Int32 = 1
let Prop1: Int32 = 1 + 4/2 + 8
fileprivate let Prop2: Int32 = 3*7
internal let Prop3: Int32 = 4*8
public init(i:Int32) {}
public init(i:Int64) {}
}
public class Foo1 {
let Prop1: Int32
fileprivate let Prop2: Int32 = 3*7
internal let Prop3: Int32 = 4*8
public init(i:Int32) {
Prop1 = 11
}
public init(i:Int64) {
Prop1 = 1111
}
}
public struct Boo {
public let Prop0: Int32 = 1
let Prop1: Int32 = 1 + 4/2 + 8
fileprivate let Prop2: Int32 = 3*7
internal let Prop3: Int32 = 4*8
public init(i:Int32) {}
public init(i:Int64) {}
}
public class Foo2 {
internal let x: Int32
@inline(never)
init(count: Int32) {
if count < 2 {
x = 5
} else {
x = 10
}
}
}
public class C {}
struct Boo3 {
//public
let Prop0: Int32
let Prop1: Int32
fileprivate let Prop2: Int32
internal let Prop3: Int32
@inline(__always)
init(_ f1: C, _ f2: C) {
self.Prop0 = 0
self.Prop1 = 1
self.Prop2 = 2
self.Prop3 = 3
}
init(_ v: C) {
self.Prop0 = 10
self.Prop1 = 11
self.Prop2 = 12
self.Prop3 = 13
}
}
// The initializer of this struct can be defined elsewhere,
// e.g. in an extension of this struct in a different module.
public struct StructWithOnlyPublicLetProperties {
public let Prop0: Int32
public let Prop1: Int32
init(_ v: Int32, _ u: Int32) {
Prop0 = 10
Prop1 = 11
}
}
// The initializer of this struct cannot be defined outside
// of the current module, because it contains an internal stored
// property, which is impossible to initialize outside of this module.
public struct StructWithPublicAndInternalLetProperties {
public let Prop0: Int32
internal let Prop1: Int32
init(_ v: Int32, _ u: Int32) {
Prop0 = 10
Prop1 = 11
}
}
// The initializer of this struct cannot be defined elsewhere,
// because it contains a fileprivate stored property, which is
// impossible to initialize outside of this file.
public struct StructWithPublicAndInternalAndPrivateLetProperties {
public let Prop0: Int32
internal let Prop1: Int32
fileprivate let Prop2: Int32
init(_ v: Int32, _ u: Int32) {
Prop0 = 10
Prop1 = 11
Prop2 = 12
}
}
// Check that Foo1.Prop1 is not constant-folded, because its value is unknown, since it is initialized differently
// by Foo1 initializers.
// CHECK-LABEL: sil @$S19let_properties_opts13testClassLet1ys5Int32VAA4Foo1CF : $@convention(thin) (@guaranteed Foo1) -> Int32
// bb0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop1
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop2
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop3
// CHECK: return
public func testClassLet1(_ f: Foo1) -> Int32 {
return f.Prop1 + f.Prop2 + f.Prop3
}
// Check that Foo1.Prop1 is not constant-folded, because its value is unknown, since it is initialized differently
// by Foo1 initializers.
// CHECK-LABEL: sil @$S19let_properties_opts13testClassLet1ys5Int32VAA4Foo1CzF : $@convention(thin) (@inout Foo1) -> Int32
// bb0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop1
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop2
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop3
// CHECK: return
public func testClassLet1(_ f: inout Foo1) -> Int32 {
return f.Prop1 + f.Prop2 + f.Prop3
}
// Check that return expressions in all subsequent functions can be constant folded, because the values of let properties
// are known to be constants of simple types.
// CHECK: sil @$S19let_properties_opts12testClassLetys5Int32VAA3FooCF : $@convention(thin) (@guaranteed Foo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testClassLet(_ f: Foo) -> Int32 {
return f.Prop1 + f.Prop1 + f.Prop2 + f.Prop3
}
// CHECK-LABEL: sil @$S19let_properties_opts12testClassLetys5Int32VAA3FooCzF : $@convention(thin) (@inout Foo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testClassLet(_ f: inout Foo) -> Int32 {
return f.Prop1 + f.Prop1 + f.Prop2 + f.Prop3
}
// CHECK-LABEL: sil @$S19let_properties_opts18testClassPublicLetys5Int32VAA3FooCF : $@convention(thin) (@guaranteed Foo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 1
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testClassPublicLet(_ f: Foo) -> Int32 {
return f.Prop0
}
// CHECK-LABEL: sil @$S19let_properties_opts13testStructLetys5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testStructLet(_ b: Boo) -> Int32 {
return b.Prop1 + b.Prop1 + b.Prop2 + b.Prop3
}
// CHECK-LABEL: sil @$S19let_properties_opts13testStructLetys5Int32VAA3BooVzF : $@convention(thin) (@inout Boo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 75
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testStructLet(_ b: inout Boo) -> Int32 {
return b.Prop1 + b.Prop1 + b.Prop2 + b.Prop3
}
// CHECK-LABEL: sil @$S19let_properties_opts19testStructPublicLetys5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 1
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
public func testStructPublicLet(_ b: Boo) -> Int32 {
return b.Prop0
}
// Check that f.x is not constant folded, because the initializer of Foo2 has multiple
// assignments to the property x with different values.
// CHECK-LABEL: sil @$S19let_properties_opts13testClassLet2ys5Int32VAA4Foo2CF : $@convention(thin) (@guaranteed Foo2) -> Int32
// bb0
// CHECK: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
// CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
// CHECK: return
public func testClassLet2(_ f: Foo2) -> Int32 {
return f.x + f.x
}
// Check that the sum of properties is not folded into a constant.
// CHECK-WMO-LABEL: sil hidden [noinline] @$S19let_properties_opts27testStructWithMultipleInitsys5Int32VAA4Boo3V_AFtF : $@convention(thin) (Boo3, Boo3) -> Int32
// CHECK-WMO: bb0
// No constant folding should have been performed.
// CHECK-WMO-NOT: integer_literal $Builtin.Int32, 92
// CHECK-WMO: struct_extract
// CHECK-WMO: }
@inline(never)
func testStructWithMultipleInits( _ boos1: Boo3, _ boos2: Boo3) -> Int32 {
let count1 = boos1.Prop0 + boos1.Prop1 + boos1.Prop2 + boos1.Prop3
let count2 = boos2.Prop0 + boos2.Prop1 + boos2.Prop2 + boos2.Prop3
return count1 + count2
}
public func testStructWithMultipleInitsAndInlinedInitializer() {
let things = [C()]
// This line results in inlining of the initializer Boo3(C, C) and later
// removal of this initializer by the dead function elimination pass.
// As a result, only one initializer, Boo3(C) is seen by the Let Properties Propagation
// pass. This pass may think that there is only one initializer and take the
// values of let properties assigned there as constants and try to propagate
// those values into uses. But this is wrong! The pass should be clever enough
// to detect all stores to the let properties, including those outside of
// initializers, e.g. inside inlined initializers. And if it detects all such
// stores it should understand that values of let properties in Boo3 are not
// statically known constant initializers with the same value and thus
// cannot be propagated.
let boos1 = things.map { Boo3($0, C()) }
let boos2 = things.map(Boo3.init)
print(testStructWithMultipleInits(boos1[0], boos2[0]))
}
// Since all properties are public, they can be initialized in a
// different module.
// Their values are not known and cannot be propagated.
// CHECK-LABEL: sil @$S19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
// CHECK: struct_extract %0 : $StructWithOnlyPublicLetProperties, #StructWithOnlyPublicLetProperties.Prop0
// CHECK: return
// CHECK-WMO-LABEL: sil @$S19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
// CHECK-WMO: struct_extract %0 : $StructWithOnlyPublicLetProperties, #StructWithOnlyPublicLetProperties.Prop0
// CHECK-WMO: return
public func testStructPropertyAccessibility(_ b: StructWithOnlyPublicLetProperties) -> Int32 {
return b.Prop0 + b.Prop1
}
// Properties can be initialized in a different file in the same module.
// Their values are not known and cannot be propagated,
// unless it is a WMO compilation.
// CHECK-LABEL: sil @$S19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
// CHECK: struct_extract %0 : $StructWithPublicAndInternalLetProperties, #StructWithPublicAndInternalLetProperties.Prop0
// CHECK-NOT: integer_literal $Builtin.Int32, 21
// CHECK: return
// CHECK-WMO-LABEL: sil @$S19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
// CHECK-WMO: integer_literal $Builtin.Int32, 21
// CHECK-WMO-NEXT: struct $Int32
// CHECK-WMO-NEXT: return
public func testStructPropertyAccessibility(_ b: StructWithPublicAndInternalLetProperties) -> Int32 {
return b.Prop0 + b.Prop1
}
// Properties can be initialized only in this file, because one of the
// properties is fileprivate.
// Therefore their values are known and can be propagated.
// CHECK: sil @$S19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
// CHECK: integer_literal $Builtin.Int32, 33
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
// CHECK-WMO-LABEL: sil @$S19let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
// CHECK-WMO: integer_literal $Builtin.Int32, 33
// CHECK-WMO-NEXT: struct $Int32
// CHECK-WMO-NEXT: return
public func testStructPropertyAccessibility(_ b: StructWithPublicAndInternalAndPrivateLetProperties) -> Int32 {
return b.Prop0 + b.Prop1 + b.Prop2
}
// Force use of initializers, otherwise they got removed by the dead-function-elimination pass
// and the values of let properties cannot be determined.
public func useInitializers() -> StructWithOnlyPublicLetProperties {
return StructWithOnlyPublicLetProperties(1, 1)
}
public func useInitializers() -> StructWithPublicAndInternalLetProperties {
return StructWithPublicAndInternalLetProperties(1, 1)
}
public func useInitializers() -> StructWithPublicAndInternalAndPrivateLetProperties {
return StructWithPublicAndInternalAndPrivateLetProperties(1, 1)
}
struct RACStruct {
private let end = 27
var startIndex: Int { return 0 }
// CHECK-LABEL: RACStruct.endIndex.getter
// CHECK-NEXT: sil hidden @{{.*}}endIndexSivg
// CHECK-NEXT: bb0
// CHECK-NEXT: %1 = integer_literal $Builtin.Int{{.*}}, 27
// CHECK-NEXT: %2 = struct $Int (%1 : $Builtin.Int{{.*}})
// CHECK-NEXT: return %2 : $Int
var endIndex: Int { return end }
subscript(_ bitIndex: Int) -> Bool {
get { return false }
set { }
}
}
extension RACStruct : RandomAccessCollection {}
| 38.422164 | 160 | 0.719407 |
fce2dde90202cf5cae7784e74e6ea76fa58b1361 | 13,663 | //
// FuncListController.swift
// TokenCore_Example
//
// Created by xyz on 2019/2/28.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import MBProgressHUD
import TokenCore
import Alamofire
class FuncListController: UITableViewController {
var requestResult = ""
let sections = ["Manage Identity", "Manage Wallets", "Transactions"]
let rows = [
[
"Create Identity",
"Recover Identity",
"Export Identity"
],
[
"Derive EOS Wallet",
"Import ETH Keystore",
"Import ETH Private Key",
"Import ETH Mnemonic",
"Import BTC Mnemonic",
"Import BTC WIF"
],
[
"Transfer 0.1 ETH on Kovan",
"Transfer 0.1 SNT on Kovan",
"Transfer 0.01 BTC on TestNet"
]
]
var nonce:Int = 1000
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "func_cell", for: indexPath)
cell.textLabel?.text = rows[indexPath.section][indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
doWorkBackground("Create Identity...") {
self.generateIdentity()
}
break
case 1:
recoverIdentity()
break
case 2:
exportIdentity()
break
default:
// do nothing
break
}
case 1:
switch indexPath.row {
case 0:
doWorkBackground("Deriving EOS Wallet") {
self.deriveEosWallet()
}
break
case 1:
doWorkBackground("Import ETH Keystore") {
self.importEthKeystore()
}
break
case 2:
doWorkBackground("Import ETH PrivateKey") {
self.importEthPrivateKey()
}
break
case 3:
doWorkBackground("Import ETH Mnemonic") {
self.importEthMnemonic()
}
break
case 4:
doWorkBackground("Import BTC Mnemonic") {
self.importBtcMnemonic()
}
break
case 5:
doWorkBackground("Import BTC WIF") {
self.importBtcPrivateKey()
}
break
default:
break
}
break
case 2:
switch indexPath.row {
case 0:
doWorkBackground("Transfer ETH") {
self.transferEth()
}
break
case 1:
doWorkBackground("Transfer ETH Token") {
self.transferEthToken()
}
break
case 2:
doWorkBackground("Transfer BTC") {
self.transferBTC()
}
break
default:
break
}
default:
break
}
}
func generateIdentity(mnemonic: String? = nil) {
do {
var mnemonicStr: String = ""
let isCreate = mnemonic == nil
let source = isCreate ? WalletMeta.Source.newIdentity : WalletMeta.Source.recoveredIdentity
var metadata = WalletMeta(source: source)
metadata.network = Network.testnet
metadata.segWit = .p2wpkh
metadata.name = isCreate ? "MyFirstIdentity" : "MyRecoveredIdentity"
let identity: Identity
if let mnemonic = mnemonic {
mnemonicStr = mnemonic
identity = try Identity.recoverIdentity(metadata: metadata, mnemonic: mnemonic, password: Constants.password)
} else {
(mnemonicStr, identity) = try Identity.createIdentity(password: Constants.password, metadata: metadata)
}
var result = ""
result.append("\n")
result.append("The mnemonic:\n")
result.append(mnemonicStr)
result.append("\n")
identity.wallets.forEach { wallet in
result.append(prettyPrintJSON(wallet.serializeToMap()))
result.append("\n")
}
requestResult = result
return
} catch {
print("createIdentity failed, error:\(error)")
}
requestResult = "unknown error"
}
func recoverIdentity() {
let alert = UIAlertController(title: "Pls input your mnemonic", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addTextField(configurationHandler: { textField in
textField.text = Constants.testMnemonic
textField.placeholder = "Input your mnemonic here..."
})
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
if let mnemonic = alert.textFields?.first?.text {
self.doWorkBackground("Recover Identity...") {
AppState.shared.mnemonic = mnemonic
self.generateIdentity(mnemonic: mnemonic)
}
}
}))
self.present(alert, animated: true)
}
func exportIdentity() {
let mnemonic = try! Identity.currentIdentity?.export(password: Constants.password)
presentResult(mnemonic!)
}
func transferEth() {
do {
let ethWallet = try WalletManager.findWalletByAddress("6031564e7b2f5cc33737807b2e58daff870b590b", on: .eth)
// chainID 41:kovan 0 testnet, 1 mainnet
nonce += 1
let signedResult = try WalletManager.ethSignTransaction(walletID: ethWallet.walletID, nonce: String(nonce), gasPrice: "20", gasLimit: "21000", to: "0xEAC1a91E4E847c92161bF6DFFba23e8499d46A3e", value: "1000000000000000", data: "", password: Constants.password, chainID: 41)
// https://faucet.kovan.network/
let requestUrl = "https://api-kovan.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex=\(signedResult.signedTx)&apikey=SJMGV3C6S3CSUQQXC7CTQ72UCM966KD2XZ"
requestResult = NetworkUtil.get(requestUrl)
} catch {
print(error)
}
}
func transferBTC() {
do {
let btcWallet = try WalletManager.findWalletByAddress("2MwN441dq8qudMvtM5eLVwC3u4zfKuGSQAB", on: .btc)
let utxoReq = "https://testnet.blockchain.info/unspent?active=2MwN441dq8qudMvtM5eLVwC3u4zfKuGSQAB"
let unspentsStr = NetworkUtil.get(utxoReq)
let json = try unspentsStr.tk_toJSON()
let unspentsJson = json["unspent_outputs"] as! [JSONObject]
let signed = try WalletManager.btcSignTransaction(walletID: btcWallet.walletID, to: "mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB", amount: Int64(1e5), fee: 10000, password: Constants.password, outputs: unspentsJson, changeIdx: 0, isTestnet: true, segWit: .p2wpkh)
let signedResult = signed.signedTx
let pushTxReq = "https://api.blockcypher.com/v1/btc/test3/txs/push?token=b41082066c8344de82c04fbca16b3883"
let reqBody: Parameters = [
"tx": signedResult
]
requestResult = NetworkUtil.post(pushTxReq, body: reqBody)
} catch {
print(error)
}
}
func transferEthToken() {
do {
let ethWallet = try WalletManager.findWalletByAddress("6031564e7b2f5cc33737807b2e58daff870b590b", on: .eth)
// chainID 41:kovan 0 testnet, 1 mainnet
nonce += 1
let data = "0xa9059cbb\(Constants.password.removePrefix0xIfNeeded())\(BigNumber.parse("1000000000000000", padding: true, paddingLen: 16).hexString())"
let tokenID = "0xf26085682797370769bbb4391a0ed05510d9029d"
let signedResult = try WalletManager.ethSignTransaction(walletID: ethWallet.walletID, nonce: String(nonce), gasPrice: "20", gasLimit: "21000", to: tokenID, value: "0", data: data, password: Constants.password, chainID: 41)
// https://faucet.kovan.network/
let requestUrl = "https://api-kovan.etherscan.io/api?module=proxy&action=eth_sendRawTransaction&hex=\(signedResult.signedTx)&apikey=SJMGV3C6S3CSUQQXC7CTQ72UCM966KD2XZ"
requestResult = NetworkUtil.get(requestUrl)
} catch {
print(error)
}
}
func importEthKeystore() {
do {
if let existWallet = try? WalletManager.findWalletByAddress("41983f2e3af196c1df429a3ff5cdecc45c82c600", on: .eth) {
_ = existWallet.delete()
}
let meta = WalletMeta(chain: .eth, source: .keystore)
let keystoreStr = """
{
"crypto": {
"cipher": "aes-128-ctr",
"cipherparams": {
"iv": "a322450a5d78b355d3f10d32424bdeb7"
},
"ciphertext": "7323633304b6e10fce17725b2f6ff8190b8e2f1c4fdb29904802e8eb9cb1ac6b",
"kdf": "pbkdf2",
"kdfparams": {
"c": 65535,
"dklen": 32,
"prf": "hmac-sha256",
"salt": "51bcbf8d464d96fca108a6bd7779381076a3f5a6ca5242eb12c8c219f1015767"
},
"mac": "cf81fa8f858554a21d00a376923138e727567f686f30f77fe3bba31b40a91c56"
},
"id": "045861fe-0e9b-4069-92aa-0ac03cad55e0",
"version": 3,
"address": "41983f2e3af196c1df429a3ff5cdecc45c82c600",
"imTokenMeta": {
"backup": [],
"chainType": "ETHEREUM",
"mode": "NORMAL",
"name": "ETH-Wallet-2",
"passwordHint": "",
"source": "KEYSTORE",
"timestamp": 1519611469,
"walletType": "V3"
}
}
"""
let keystore = try! keystoreStr.tk_toJSON()
let ethWallet = try! WalletManager.importFromKeystore(keystore, encryptedBy: Constants.password, metadata: meta)
requestResult = "Import ETH Wallet by keystore success:\n"
requestResult = requestResult + prettyPrintJSON(ethWallet.serializeToMap())
requestResult = try! ethWallet.privateKey(password: Constants.password)
}
}
func importEthPrivateKey() {
do {
if let existWallet = try? WalletManager.findWalletByAddress("41983f2e3af196c1df429a3ff5cdecc45c82c600", on: .eth) {
_ = existWallet.delete()
}
let meta = WalletMeta(chain: .eth, source: .privateKey)
let ethWallet = try! WalletManager.importFromPrivateKey(Constants.testPrivateKey, encryptedBy: Constants.password, metadata: meta)
requestResult = "Import ETH Wallet by PrivateKey success:\n"
requestResult = requestResult + prettyPrintJSON(ethWallet.serializeToMap())
}
}
func importEthMnemonic() {
do {
if let existWallet = try? WalletManager.findWalletByAddress("41983f2e3af196c1df429a3ff5cdecc45c82c600", on: .eth) {
_ = existWallet.delete()
}
let meta = WalletMeta(chain: .eth, source: .mnemonic)
let ethWallet = try! WalletManager.importFromMnemonic(Constants.testMnemonic, metadata: meta, encryptBy: Constants.password, at: BIP44.eth)
requestResult = "Import ETH Wallet by Mnemonic success:\n"
requestResult = requestResult + prettyPrintJSON(ethWallet.serializeToMap())
}
}
func importBtcMnemonic() {
do {
if let existWallet = try? WalletManager.findWalletByAddress("mpke4CzhBTV2dFZpnABT9EN1kPc4vDWZxw", on: .btc) {
_ = existWallet.delete()
}
let meta = WalletMeta(chain: .btc, source: .mnemonic, network: .testnet)
let btcWallet = try! WalletManager.importFromMnemonic(Constants.testMnemonic, metadata: meta, encryptBy: Constants.password, at: BIP44.btcSegwitTestnet)
requestResult = "Import BTC SegWit Wallet by Mnemonic success:\n"
requestResult = requestResult + prettyPrintJSON(btcWallet.serializeToMap())
}
}
func importBtcPrivateKey() {
do {
if let existWallet = try? WalletManager.findWalletByAddress("n2ZNV88uQbede7C5M5jzi6SyG4GVuPpng6", on: .btc) {
_ = existWallet.delete()
}
let meta = WalletMeta(chain: .btc, source: .wif, network: .testnet)
let btcWallet = try! WalletManager.importFromPrivateKey(Constants.testWif, encryptedBy: Constants.password, metadata: meta)
requestResult = "Import BTC SegWit Wallet by WIF success:\n"
requestResult = requestResult + prettyPrintJSON(btcWallet.serializeToMap())
}
}
func deriveEosWallet() {
do {
if let existWallet = try? WalletManager.findWalletByAddress("n2ZNV88uQbede7C5M5jzi6SyG4GVuPpng6", on: .btc) {
_ = existWallet.delete()
}
guard let identity = Identity.currentIdentity else {
requestResult = "Pls create or recover an identity first"
return
}
let wallets = try! identity.deriveWallets(for: [.eos], password: Constants.password)
let eosWallet = wallets.first!
requestResult = "Derived EOS Wallet by identity mnemonic success:\n"
requestResult = requestResult + prettyPrintJSON(eosWallet.serializeToMap())
}
}
private func presentResult(_ result: String) {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ResultController") as! ResultController
vc.info = result
self.navigationController?.pushViewController(vc, animated: true)
}
func doWorkBackground(_ workTip: String, hardWork: @escaping () -> Void) {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = workTip
DispatchQueue.global().async {
hardWork()
DispatchQueue.main.async {
MBProgressHUD.hide(for: self.view, animated: true)
self.presentResult(self.requestResult)
}
}
}
}
| 33.903226 | 278 | 0.64693 |
f536768545734699f14e4d6d7eb45ebaf56aa268 | 19,244 | //
// GeoPrimitives.swift
// Merops
//
// Created by sumioka-air on 2018/02/04.
// Copyright © 2018年 sho sumioka. All rights reserved.
//
import Foundation
import SceneKit
class SCNLine: SCNNode {
// 直線
init(from: SCNVector3, to: SCNVector3) {
super.init()
let source = SCNGeometrySource.init(vertices: [from, to])
let indices: [UInt8] = [0, 1]
let data = Data(indices)
let element = SCNGeometryElement.init(data: data, primitiveType: .line,
primitiveCount: 1, bytesPerIndex: 1)
let geometry = SCNGeometry.init(sources: [source], elements: [element])
self.geometry = geometry
// Material
let material = SCNMaterial.init()
material.diffuse.contents = Color.white.cgColor
self.geometry!.insertMaterial(material, at: 0)
}
// Bezier
init(path: SCNPath) {
super.init()
let source = SCNGeometrySource(vertices: path.points)
let indices: [UInt32] = {
var rtn = [UInt32]();
for i in 0..<path.points.count - 1 {
rtn += [UInt32(i), UInt32(i + 1)]
};
return rtn
}()
let element = SCNGeometryElement(indices: indices, primitiveType: .line)
let geometry = SCNGeometry(sources: [source], elements: [element])
self.geometry = geometry
// Material
let material = SCNMaterial()
material.diffuse.contents = Color.white
self.geometry!.insertMaterial(material, at: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
}
infix operator =>
public func =><T, U>(lhs: T, rhs: (T) throws -> U) rethrows -> U {
return try rhs(lhs)
}
public class SCNPath {
private var current: SCNVector3 = SCNVector3(0, 0, 0)
var points: [SCNVector3] = [] //曲線を構成する点の座標を保存する
/// 始点を設定します。pointsは上書きされます。デフォルトでは(0, 0, 0)です。
func start(from point: SCNVector3) -> SCNPath {
current = point
points = [point]
return self
}
func addLine(to point: SCNVector3) -> SCNPath {
var rtn = [SCNVector3]()
points.append(current)
rtn.append(current)
current = point
return self
}
func addQuadCurve(to point: SCNVector3, control: SCNVector3) -> SCNPath {
var rtn = [SCNVector3]()
let n = 1 //((control - current).length + (point - control).length) * 12
for i in 0..<n {
let t = SCNFloat(i / n)
let q1 = current + (control - current) * t
let q2 = control + (point - control) * t
let r = q1 + (q2 - q1) * t
rtn.append(r)
}
points += rtn
current = point
return self
}
func addCurve(to point: SCNVector3, control1: SCNVector3, control2: SCNVector3) -> SCNPath {
var rtn = [SCNVector3]()
let n = 1 //Int((control1 - current).length + (control2 - control1).length + (point - control2).length) * 12
for i in 0..<n {
let t = SCNFloat(i / n)
let q1 = current + (control1 - current) * t
let q2 = control1 + (control2 - control1) * t
let q3 = control2 + (point - control2) * t
let r1 = q1 + (q2 - q1) * t
let r2 = q2 + (q3 - q2) * t
let s = r1 + (r2 - r1) * t
rtn.append(s)
}
points += rtn
current = point
return self
}
func end() {
points.append(current)
}
func close() -> SCNPath {
_ = addLine(to: self.points[0])
if let last = points.last, last == current {
} else {
points.append(current)
}
current = self.points[0]
return self
}
}
class Quad {
let v0: SCNVector3
let v1: SCNVector3
let v2: SCNVector3
let v3: SCNVector3
init(v0: SCNVector3, v1: SCNVector3, v2: SCNVector3, v3: SCNVector3) {
self.v0 = v0
self.v1 = v1
self.v2 = v2
self.v3 = v3
}
}
class QuadBuilder {
var quads: [Quad]
enum UVModeType {
case StretchToFitXY, StretchToFitX,
StretchToFitY, SizeToWorldUnitsXY, SizeToWorldUnitsX
}
var uvMode = UVModeType.StretchToFitXY
init(uvMode: UVModeType = .StretchToFitXY) {
self.uvMode = uvMode
quads = []
}
// Add a quad to the geometry
// - list verticies in counter-clockwise order
// when looking from the "outside" of the square
func addQuad(quad: Quad) {
quads.append(quad)
}
func getGeometry() -> SCNGeometry {
var verts: [SCNVector3] = []
var faceIndices: [CInt] = []
var normals: [SCNVector3] = []
var uvs: [CGPoint] = []
// Walk through the quads, adding 4 vertices, 2 faces and 4 normals per quad
// v1 --------------v0
// | __/ |
// | face __/ |
// | 1 __/ |
// | __/ face |
// | __/ 2 |
// v2 ------------- v3
for quad in quads {
verts.append(quad.v0)
verts.append(quad.v1)
verts.append(quad.v2)
verts.append(quad.v3)
// add face 1
faceIndices.append(CInt(verts.count - 4)) // v0
faceIndices.append(CInt(verts.count - 3)) // v1
faceIndices.append(CInt(verts.count - 2)) // v2
// add face 2
faceIndices.append(CInt(verts.count - 4)) // v0
faceIndices.append(CInt(verts.count - 2)) // v2
faceIndices.append(CInt(verts.count - 1)) // v3
// add normals for each vertice (compute seperately for face1 and face2 - common edge gets avg)
let nvf1 = getNormal(v0: quad.v0, v1: quad.v1, v2: quad.v2)
let nvf2 = getNormal(v0: quad.v0, v1: quad.v2, v2: quad.v3)
normals.append(nvf1 + nvf2) // v0
normals.append(nvf1) // v1
normals.append(nvf1 + nvf2) // v2
normals.append(nvf2) // v3
let longestUEdgeLength = max((quad.v1 - quad.v0).length(), (quad.v2 - quad.v3).length())
let longestVEdgeLength = max((quad.v1 - quad.v2).length(), (quad.v0 - quad.v3).length())
switch uvMode {
// The longest sides dictate the texture tiling, then it is stretched (if nec) across
case .SizeToWorldUnitsX:
uvs.append(CGPoint(x: Double(longestUEdgeLength), y: Double(longestVEdgeLength)))
uvs.append(CGPoint(x: 0, y: Double(longestVEdgeLength)))
uvs.append(CGPoint(x: 0, y: 0))
uvs.append(CGPoint(x: Double(longestUEdgeLength), y: 0))
case .SizeToWorldUnitsXY:
// For this uvMode, we allign the texture to the "upper left corner" (v1) and tile
// it to the "right" and "down" (and "up") based on the coordinate units and the
// texture/units ratio
let v2v0 = quad.v0 - quad.v2 // v2 to v0 edge
let v2v1 = quad.v1 - quad.v2 // v2 to v1 edge
let v2v3 = quad.v3 - quad.v2 // v2 to v3 edge
let v2v0Mag = v2v0.length() // length of v2 to v0 edge
let v2v1Mag = v2v1.length() // length of v2 to v1 edge
let v2v3Mag = v2v3.length() // length of v2 to v3 edge
let v0angle = v2v3.angle(vector: v2v0) // angle of v2v0 edge against v2v3 edge
let v1angle = v2v3.angle(vector: v2v1) // angle of v2v1 edge against v2v3 edge
// now its just some simple trig - yay!
uvs.append(CGPoint(x: CGFloat(cos(v0angle) * v2v0Mag), y: CGFloat(sin(v0angle) * v2v0Mag))) // V0
uvs.append(CGPoint(x: CGFloat(cos(v1angle) * v2v1Mag), y: CGFloat(sin(v1angle) * v2v1Mag))) // V1
uvs.append(CGPoint(x: 0, y: 0)) // V2
uvs.append(CGPoint(x: CGFloat(v2v3Mag), y: 0)) // V3
// print("v0 texture point is at \(CGPoint(x: cos(v0angle) * v2v0Mag, y: sin(v0angle) * v2v0Mag))")
// print("v1 texture point is at \(CGPoint(x: cos(v1angle) * v2v1Mag, y: sin(v1angle) * v2v1Mag))")
// print("v2 texture point is at \(CGPoint(x: 0, y: 0))")
// print("v3 texture point is at \(CGPoint(x: v2v3Mag, y: 0))")
case .StretchToFitXY:
uvs.append(CGPoint(x: 1, y: 1))
uvs.append(CGPoint(x: 0, y: 1))
uvs.append(CGPoint(x: 0, y: 0))
uvs.append(CGPoint(x: 1, y: 0))
default:
print("Unknown uv mode \(uvMode)") // no uv mapping for you!
}
}
// Define our sources
let vertexSource = SCNGeometrySource(vertices: verts)
let normalSource = SCNGeometrySource(normals: normals)
let textureSource = SCNGeometrySource(textureCoordinates: uvs)
// Define elements Data
let indexData = NSData(bytes: faceIndices, length: MemoryLayout<CInt>.size * faceIndices.count)
let element = SCNGeometryElement(data: indexData as Data, primitiveType: .triangles, primitiveCount: faceIndices.count / 3, bytesPerIndex: MemoryLayout<CInt>.size)
let geometry = SCNGeometry(sources: [vertexSource, normalSource, textureSource], elements: [element])
return geometry
}
}
extension SCNGeometry {
func square(length: Float) -> [SCNVector3] {
let m = SCNFloat(length / Float(2)), q = SCNFloat(Float(1))
let topLeft = SCNVector3Make(-m - q, m + q, m + q),
topRight = SCNVector3Make(m + q, m + q, m + q),
bottomLeft = SCNVector3Make(-m - q, -m - q, m + q),
bottomRight = SCNVector3Make(m + q, -m - q, m + q)
return [topLeft, topRight, bottomLeft, bottomRight]
}
func vertices() -> [SCNVector3] {
var vectors = [SCNVector3]()
let vertexSources = sources(for: .vertex)
if let v = vertexSources.first {
v.data.withUnsafeBytes { (p: UnsafePointer<Float32>) in
for i in 0..<v.vectorCount {
let index = (i * v.dataStride + v.dataOffset) / 4
vectors.append(SCNVector3Make(
SCNFloat(p[index + 0]),
SCNFloat(p[index + 1]),
SCNFloat(p[index + 2])
))
}
}
return vectors
}
return []
}
func normals() -> [SCNVector3] {
var vectors = [SCNVector3]()
let normalSources = sources(for: .normal)
if let v = normalSources.first {
v.data.withUnsafeBytes { (p: UnsafePointer<Float32>) in
for i in 0..<v.vectorCount {
let index = (i * v.dataStride + v.dataOffset) / 4
vectors.append(SCNVector3Make(
SCNFloat(p[index + 0]),
SCNFloat(p[index + 1]),
SCNFloat(p[index + 2])
))
}
}
return vectors
}
return []
}
}
// experimental
//func points(result: SCNHitTestResult) {
// let node = SCNNode(geometry: SCNSphere(radius: 0.3))
// node.categoryBitMask = NodeOptions.noExport.rawValue
//
// let vectors = vertices(node: node)
// for (index, vec) in vectors.enumerated() {
// NSLog("\(vec)")
// let pointNode = node.flattenedClone()
// pointNode.name = "vertex_\(index)"
// // pointNode.position = self.projectPoint(vec)
// result.node.addChildNode(pointNode)
// }
//}
//
//func lines(result: SCNHitTestResult) {
// let node = SCNNode()
// node.categoryBitMask = NodeOptions.noExport.rawValue
//
// for (index, vec) in vertices(node: node).enumerated() {
// let source = SCNGeometrySource(
// vertices: [vec, vec]),
// indices: [UInt8] = [0, 1],
// data = Data(bytes: indices
// ),
// element = SCNGeometryElement(
// data: data, primitiveType: .line, primitiveCount: 1, bytesPerIndex: 1
// )
// node.geometry = SCNGeometry(sources: [source], elements: [element])
// let lineNode = node.flattenedClone()
// lineNode.name = "line\(index)"
//
// let material = SCNMaterial()
// material.diffuse.contents = Color.red
// lineNode.geometry!.insertMaterial(material, at: 0)
// result.node.addChildNode(lineNode)
// }
//}
//extension SCNGeometrySource {
// convenience init(textureCoordinates texcoord: [float2]) {
// let data = Data(bytes: texcoord, length: sizeof(float2) * texcoord.count)
// self.init(data: data, semantic: SCNGeometrySourceSemanticTexcoord,
// vectorCount: texcoord.count, floatComponents: true,
// componentsPerVector: 2, bytesPerComponent: sizeof(Float),
// dataOffset: 0, dataStride: sizeof(float2)
// )
// }
//}
//
//func addLineBetweenVertices(vertexA: simd_float3,
// vertexB: simd_float3,
// inScene scene: SCNScene,
// useSpheres: Bool = false,
// color: Color = .yellow) {
// if useSpheres {
// addSphereAt(position: vertexB,
// radius: 0.01,
// color: .red,
// scene: scene)
// } else {
// let geometrySource = SCNGeometrySource(vertices: [SCNVector3(x: vertexA.x,
// y: vertexA.y,
// z: vertexA.z),
// SCNVector3(x: vertexB.x,
// y: vertexB.y,
// z: vertexB.z)])
// let indices: [Int8] = [0, 1]
// let indexData = Data(bytes: indices, count: 2)
// let element = SCNGeometryElement(data: indexData,
// primitiveType: .line,
// primitiveCount: 1,
// bytesPerIndex: MemoryLayout<Int8>.size)
//
// let geometry = SCNGeometry(sources: [geometrySource],
// elements: [element])
//
// geometry.firstMaterial?.isDoubleSided = true
// geometry.firstMaterial?.emission.contents = color
//
// let node = SCNNode(geometry: geometry)
//
// scene.rootNode.addChildNode(node)
// }
//}
//
//@discardableResult
//func addTriangle(vertices: [simd_float3], inScene scene: SCNScene) -> SCNNode {
// assert(vertices.count == 3, "vertices count must be 3")
//
// let vector1 = vertices[2] - vertices[1]
// let vector2 = vertices[0] - vertices[1]
// let normal = simd_normalize(simd_cross(vector1, vector2))
//
// let normalSource = SCNGeometrySource(normals: [SCNVector3(x: normal.x, y: normal.y, z: normal.z),
// SCNVector3(x: normal.x, y: normal.y, z: normal.z),
// SCNVector3(x: normal.x, y: normal.y, z: normal.z)])
//
// let sceneKitVertices = vertices.map {
// return SCNVector3(x: $0.x, y: $0.y, z: $0.z)
// }
// let geometrySource = SCNGeometrySource(vertices: sceneKitVertices)
//
// let indices: [Int8] = [0, 1, 2]
// let indexData = Data(bytes: indices, count: 3)
// let element = SCNGeometryElement(data: indexData,
// primitiveType: .triangles,
// primitiveCount: 1,
// bytesPerIndex: MemoryLayout<Int8>.size)
//
// let geometry = SCNGeometry(sources: [geometrySource, normalSource],
// elements: [element])
//
// geometry.firstMaterial?.isDoubleSided = true
// geometry.firstMaterial?.diffuse.contents = Color.orange
//
// let node = SCNNode(geometry: geometry)
//
// scene.rootNode.addChildNode(node)
//
// return node
//}
//
//func addCube(vertices: [simd_float3], inScene scene: SCNScene) -> SCNNode {
// assert(vertices.count == 8, "vertices count must be 3")
//
// let sceneKitVertices = vertices.map {
// return SCNVector3(x: $0.x, y: $0.y, z: $0.z)
// }
// let geometrySource = SCNGeometrySource(vertices: sceneKitVertices)
//
// let indices: [Int8] = [
// // bottom
// 0, 2, 1,
// 1, 2, 3,
// // back
// 2, 6, 3,
// 3, 6, 7,
// // left
// 0, 4, 2,
// 2, 4, 6,
// // right
// 1, 3, 5,
// 3, 7, 5,
// // front
// 0, 1, 4,
// 1, 5, 4,
// // top
// 4, 5, 6,
// 5, 7, 6 ]
//
// let indexData = Data(bytes: indices, count: indices.count)
// let element = SCNGeometryElement(data: indexData,
// primitiveType: .triangles,
// primitiveCount: 12,
// bytesPerIndex: MemoryLayout<Int8>.size)
//
// let geometry = SCNGeometry(sources: [geometrySource],
// elements: [element])
//
// geometry.firstMaterial?.isDoubleSided = true
// geometry.firstMaterial?.diffuse.contents = Color.purple
// geometry.firstMaterial?.lightingModel = .physicallyBased
//
// let node = SCNNode(geometry: geometry)
//
// scene.rootNode.addChildNode(node)
//
// return node
//}
//
//func addAxisArrows(scene: SCNScene) {
// let xArrow = arrow(color: Color.red)
// xArrow.simdEulerAngles = simd_float3(x: 0, y: 0, z: -.pi * 0.5)
//
// let yArrow = arrow(color: Color.green)
//
// let zArrow = arrow(color: Color.blue)
// zArrow.simdEulerAngles = simd_float3(x: .pi * 0.5, y: 0, z: 0)
//
// let node = SCNNode()
// node.addChildNode(xArrow)
// node.addChildNode(yArrow)
// node.addChildNode(zArrow)
//
// node.simdPosition = simd_float3(x: -1.5, y: -1.25, z: 0.0)
//
// scene.rootNode.addChildNode(node)
//}
//
//func arrow(color: Color) -> SCNNode {
// let cylinder = SCNCylinder(radius: 0.01, height: 0.5)
// cylinder.firstMaterial?.diffuse.contents = color
// let cylinderNode = SCNNode(geometry: cylinder)
//
// let cone = SCNCone(topRadius: 0, bottomRadius: 0.03, height: 0.1)
// cone.firstMaterial?.diffuse.contents = color
// let coneNode = SCNNode(geometry: cone)
//
// coneNode.simdPosition = simd_float3(x: 0, y: 0.25, z: 0)
//
// let returnNode = SCNNode()
// returnNode.addChildNode(cylinderNode)
// returnNode.addChildNode(coneNode)
//
// returnNode.pivot = SCNMatrix4MakeTranslation(0, -0.25, 0)
//
// return returnNode
//}
| 35.836127 | 171 | 0.526762 |
ebb3d3f54285aafc357306615c968dbbce32a3b3 | 589 |
import Foundation
public struct AnySearchable: Searchable, InternalSearchable {
private let _components: (Bool) -> [String : Double]
public init<S : Searchable>(_ searchable: S) {
_components = { Fuzzi.components(for: searchable, includeAll: $0) }
}
public var body: Never {
fatalError("Body not implemented")
}
func components(includeAll: Bool) -> [String : Double] {
return _components(includeAll)
}
}
extension Searchable {
public func eraseToAnySearchable() -> AnySearchable {
return AnySearchable(self)
}
}
| 21.035714 | 75 | 0.657046 |
20d1c455f08a3d491ee45cf0c25c9c8d72a40bd7 | 26,554 | import XCTest
import Quick
import Nimble
import Cuckoo
@testable import BitcoinCore
class BlockSyncerTests: QuickSpec {
override func spec() {
let mockStorage = MockIStorage()
let mockFactory = MockIFactory()
let mockListener = MockISyncStateListener()
let mockTransactionProcessor = MockITransactionProcessor()
let mockBlockchain = MockIBlockchain()
let mockAddressManager = MockIPublicKeyManager()
let mockState = MockBlockSyncerState()
let checkpointBlock = TestData.checkpointBlock
var syncer: BlockSyncer!
beforeEach {
stub(mockStorage) { mock in
when(mock.blocksCount.get).thenReturn(1)
when(mock.lastBlock.get).thenReturn(nil)
when(mock.deleteBlockchainBlockHashes()).thenDoNothing()
}
stub(mockListener) { mock in
when(mock.initialBestBlockHeightUpdated(height: equal(to: 0))).thenDoNothing()
}
stub(mockBlockchain) { mock in
when(mock.handleFork()).thenDoNothing()
}
stub(mockAddressManager) { mock in
when(mock.fillGap()).thenDoNothing()
}
stub(mockState) { mock in
when(mock.iteration(hasPartialBlocks: any())).thenDoNothing()
}
}
afterEach {
reset(mockStorage, mockListener, mockTransactionProcessor, mockBlockchain, mockAddressManager, mockState)
syncer = nil
}
context("static methods") {
describe("#instance") {
it("triggers #initialBestBlockHeightUpdated event on listener") {
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(checkpointBlock)
}
stub(mockListener) { mock in
when(mock.initialBestBlockHeightUpdated(height: any())).thenDoNothing()
}
let _ = BlockSyncer.instance(storage: mockStorage, checkpointBlock: checkpointBlock, factory: mockFactory, listener: mockListener, transactionProcessor: mockTransactionProcessor,
blockchain: mockBlockchain, publicKeyManager: mockAddressManager, hashCheckpointThreshold: 100)
verify(mockListener).initialBestBlockHeightUpdated(height: equal(to: Int32(checkpointBlock.height)))
verifyNoMoreInteractions(mockListener)
}
}
describe("#checkpointBlock") {
let bip44CheckpointBlock = TestData.checkpointBlock
let lastCheckpointBlock = TestData.firstBlock
let mockNetwork = MockINetwork()
beforeEach {
stub(mockNetwork) { mock in
when(mock.bip44CheckpointBlock.get).thenReturn(bip44CheckpointBlock)
when(mock.lastCheckpointBlock.get).thenReturn(lastCheckpointBlock)
}
}
afterEach {
reset(mockNetwork)
}
context("when there are some blocks in storage") {
let lastBlock = TestData.secondBlock
beforeEach {
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(lastBlock)
}
}
it("doesn't save checkpointBlock to storage") {
_ = BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .api, storage: mockStorage)
verify(mockStorage, never()).save(block: any())
verify(mockStorage).lastBlock.get()
verifyNoMoreInteractions(mockStorage)
}
context("when syncMode is .full") {
it("returns bip44CheckpointBlock") {
expect(BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .full, storage: mockStorage)).to(equal(bip44CheckpointBlock))
}
}
context("when syncMode is not .full") {
context("when lastBlock's height is more than lastCheckpointBlock") {
it("returns lastCheckpointBlock") {
lastBlock.height = lastCheckpointBlock.height + 1
expect(BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .api, storage: mockStorage)).to(equal(lastCheckpointBlock))
}
}
context("when lastBlock's height is less than lastCheckpointBlock") {
it("returns bip44CheckpointBlock") {
lastBlock.height = lastCheckpointBlock.height - 1
expect(BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .api, storage: mockStorage)).to(equal(bip44CheckpointBlock))
}
}
}
}
context("when there's no block in storage") {
beforeEach {
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(nil)
when(mock.save(block: any())).thenDoNothing()
}
}
context("when syncMode is .full") {
it("returns bip44CheckpointBlock") {
expect(BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .full, storage: mockStorage)).to(equal(bip44CheckpointBlock))
}
it("saves bip44CheckpointBlock to storage") {
_ = BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .full, storage: mockStorage)
verify(mockStorage).save(block: sameInstance(as: bip44CheckpointBlock))
}
}
context("when syncMode is not .full") {
it("returns lastCheckpointBlock") {
expect(BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .api, storage: mockStorage)).to(equal(lastCheckpointBlock))
}
it("saves lastCheckpointBlock to storage") {
_ = BlockSyncer.checkpointBlock(network: mockNetwork, syncMode: .api, storage: mockStorage)
verify(mockStorage).save(block: sameInstance(as: lastCheckpointBlock))
}
}
}
}
}
context("instance methods") {
beforeEach {
syncer = BlockSyncer(storage: mockStorage, checkpointBlock: checkpointBlock, factory: mockFactory, listener: mockListener, transactionProcessor: mockTransactionProcessor,
blockchain: mockBlockchain, publicKeyManager: mockAddressManager,
hashCheckpointThreshold: 100, logger: nil, state: mockState)
}
describe("#localDownloadedBestBlockHeight") {
context("when there are some blocks in storage") {
it("returns the height of the last block") {
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(checkpointBlock)
}
expect(syncer.localDownloadedBestBlockHeight).to(equal(Int32(checkpointBlock.height)))
}
}
context("when there's no block in storage") {
it("returns 0") {
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(nil)
}
expect(syncer.localDownloadedBestBlockHeight).to(equal(0))
}
}
}
describe("#localKnownBestBlockHeight") {
let blockHash = BlockHash(headerHash: Data(repeating: 0, count: 32), height: 0, order: 0)
context("when no blockHashes") {
beforeEach {
stub(mockStorage) { mock in
when(mock.blockchainBlockHashes.get).thenReturn([])
when(mock.blocksCount(headerHashes: equal(to: []))).thenReturn(0)
}
}
context("when no blocks") {
it("returns 0") {
expect(syncer.localKnownBestBlockHeight).to(equal(0))
}
}
context("when there are some blocks") {
it("returns last block's height + blocks count") {
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(checkpointBlock)
}
expect(syncer.localKnownBestBlockHeight).to(equal(Int32(checkpointBlock.height)))
}
}
}
context("when there are some blockHashes which haven't downloaded blocks") {
beforeEach {
stub(mockStorage) { mock in
when(mock.blockchainBlockHashes.get).thenReturn([blockHash])
when(mock.blocksCount(headerHashes: equal(to: [blockHash.headerHash]))).thenReturn(0)
}
}
it("returns lastBlock + blockHashes count") {
expect(syncer.localKnownBestBlockHeight).to(equal(1))
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(checkpointBlock)
}
expect(syncer.localKnownBestBlockHeight).to(equal(Int32(checkpointBlock.height + 1)))
}
}
context("when there are some blockHashes which have downloaded blocks") {
beforeEach {
stub(mockStorage) { mock in
when(mock.blockchainBlockHashes.get).thenReturn([blockHash])
when(mock.blocksCount(headerHashes: equal(to: [blockHash.headerHash]))).thenReturn(1)
}
}
it("returns lastBlock + count of blockHashes without downloaded blocks") {
expect(syncer.localKnownBestBlockHeight).to(equal(0))
stub(mockStorage) { mock in
when(mock.lastBlock.get).thenReturn(checkpointBlock)
}
expect(syncer.localKnownBestBlockHeight).to(equal(Int32(checkpointBlock.height)))
}
}
}
describe("#prepareForDownload") {
let emptyBlocks = [Block]()
beforeEach {
stub(mockStorage) { mock in
when(mock.blockHashHeaderHashes(except: equal(to: checkpointBlock.headerHash))).thenReturn([])
when(mock.blocks(byHexes: equal(to: []))).thenReturn(emptyBlocks)
}
stub(mockBlockchain) { mock in
when(mock.deleteBlocks(blocks: equal(to: emptyBlocks))).thenDoNothing()
}
syncer.prepareForDownload()
}
it("handles partial blocks") {
verify(mockAddressManager).fillGap()
verify(mockState).iteration(hasPartialBlocks: equal(to: false))
}
it("clears BlockHashes") {
verify(mockStorage).deleteBlockchainBlockHashes()
}
it("clears partialBlock blocks") {
verify(mockStorage).blockHashHeaderHashes(except: equal(to: checkpointBlock.headerHash))
verify(mockStorage).blocks(byHexes: equal(to: []))
verify(mockBlockchain).deleteBlocks(blocks: equal(to: emptyBlocks))
}
it("handles fork") {
verify(mockBlockchain).handleFork()
}
}
describe("#downloadIterationCompleted") {
context("when iteration has partial blocks") {
it("handles partial blocks") {
stub(mockState) { mock in
when(mock.iterationHasPartialBlocks.get).thenReturn(true)
}
syncer.downloadIterationCompleted()
verify(mockAddressManager).fillGap()
verify(mockState).iteration(hasPartialBlocks: equal(to: false))
}
}
context("when iteration has not partial blocks") {
it("does not handle partial blocks") {
stub(mockState) { mock in
when(mock.iterationHasPartialBlocks.get).thenReturn(false)
}
syncer.downloadIterationCompleted()
verify(mockAddressManager, never()).fillGap()
verify(mockState, never()).iteration(hasPartialBlocks: any())
}
}
}
describe("#downloadCompleted") {
it("handles fork") {
syncer.downloadCompleted()
verify(mockBlockchain).handleFork()
}
}
describe("#downloadFailed") {
let emptyBlocks = [Block]()
beforeEach {
stub(mockStorage) { mock in
when(mock.blockHashHeaderHashes(except: equal(to: checkpointBlock.headerHash))).thenReturn([])
when(mock.blocks(byHexes: equal(to: []))).thenReturn(emptyBlocks)
}
stub(mockBlockchain) { mock in
when(mock.deleteBlocks(blocks: equal(to: emptyBlocks))).thenDoNothing()
}
syncer.downloadFailed()
}
it("handles partial blocks") {
verify(mockAddressManager).fillGap()
verify(mockState).iteration(hasPartialBlocks: equal(to: false))
}
it("clears BlockHashes") {
verify(mockStorage).deleteBlockchainBlockHashes()
}
it("clears partialBlock blocks") {
verify(mockStorage).blockHashHeaderHashes(except: equal(to: checkpointBlock.headerHash))
verify(mockStorage).blocks(byHexes: equal(to: []))
verify(mockBlockchain).deleteBlocks(blocks: equal(to: emptyBlocks))
}
it("handles fork") {
verify(mockBlockchain).handleFork()
}
}
describe("#getBlockHashes") {
it("returns first 500 blockhashes") {
let blockHashes = [BlockHash(headerHash: Data(repeating: 0, count: 0), height: 0, order: 0)]
stub(mockStorage) { mock in
when(mock.blockHashesSortedBySequenceAndHeight(limit: equal(to: 500))).thenReturn(blockHashes)
}
expect(syncer.getBlockHashes()).to(equal(blockHashes))
verify(mockStorage).blockHashesSortedBySequenceAndHeight(limit: equal(to: 500))
}
}
describe("#getBlockLocatorHashes(peerLastBlockHeight:)") {
let peerLastBlockHeight: Int32 = 10
let firstBlock = TestData.firstBlock
let secondBlock = TestData.secondBlock
beforeEach {
stub(mockStorage) { mock in
when(mock.lastBlockchainBlockHash.get).thenReturn(nil)
when(mock.blocks(heightGreaterThan: equal(to: checkpointBlock.height), sortedBy: equal(to: Block.Columns.height), limit: equal(to: 10))).thenReturn([Block]())
when(mock.block(byHeight: Int(peerLastBlockHeight))).thenReturn(nil)
}
}
context("when there's no blocks or blockhashes") {
it("returns checkpointBlock's header hash") {
expect(syncer.getBlockLocatorHashes(peerLastBlockHeight: peerLastBlockHeight)).to(equal([checkpointBlock.headerHash]))
}
}
context("when there are blockchain blockhashes") {
it("returns last blockchain blockhash") {
let blockHash = BlockHash(headerHash: Data(repeating: 0, count: 0), height: 0, order: 0)
stub(mockStorage) { mock in
when(mock.lastBlockchainBlockHash.get).thenReturn(blockHash)
when(mock.blocks(heightGreaterThan: equal(to: checkpointBlock.height), sortedBy: equal(to: Block.Columns.height), limit: equal(to: 10))).thenReturn([firstBlock, secondBlock])
}
expect(syncer.getBlockLocatorHashes(peerLastBlockHeight: peerLastBlockHeight)).to(equal([
blockHash.headerHash, checkpointBlock.headerHash
]))
}
}
context("when there's no blockhashes but there are blocks") {
it("returns last 10 blocks' header hashes") {
stub(mockStorage) { mock in
when(mock.blocks(heightGreaterThan: equal(to: checkpointBlock.height), sortedBy: equal(to: Block.Columns.height), limit: equal(to: 10))).thenReturn([secondBlock, firstBlock])
}
expect(syncer.getBlockLocatorHashes(peerLastBlockHeight: peerLastBlockHeight)).to(equal([
secondBlock.headerHash, firstBlock.headerHash, checkpointBlock.headerHash
]))
}
}
context("when the peers last block is already in storage") {
it("returns peers last block's headerHash instead of checkpointBlocks'") {
stub(mockStorage) { mock in
when(mock.block(byHeight: Int(peerLastBlockHeight))).thenReturn(firstBlock)
}
expect(syncer.getBlockLocatorHashes(peerLastBlockHeight: peerLastBlockHeight)).to(equal([firstBlock.headerHash]))
}
}
}
describe("#add(blockHashes:)") {
let existingBlockHash = Data(repeating: 0, count: 32)
let newBlockHash = Data(repeating: 1, count: 32)
let blockHash = BlockHash(headerHash: existingBlockHash, height: 0, order: 10)
beforeEach {
stub(mockStorage) { mock in
when(mock.blockHashHeaderHashes.get).thenReturn([existingBlockHash])
when(mock.add(blockHashes: any())).thenDoNothing()
}
stub(mockFactory) { mock in
when(mock.blockHash(withHeaderHash: equal(to: newBlockHash), height: equal(to: 0), order: any())).thenReturn(blockHash)
}
}
context("when there's a blockHash in storage") {
it("sets order of given blockhashes starting from last blockhashes order") {
let lastBlockHash = BlockHash(headerHash: Data(repeating: 0, count: 0), height: 0, order: 10)
stub(mockStorage) { mock in
when(mock.lastBlockHash.get).thenReturn(lastBlockHash)
}
syncer.add(blockHashes: [existingBlockHash, newBlockHash])
verify(mockFactory).blockHash(withHeaderHash: equal(to: newBlockHash), height: equal(to: 0), order: equal(to: lastBlockHash.sequence + 1))
verify(mockStorage).add(blockHashes: equal(to: [blockHash]))
}
}
context("when there's no blockhashes") {
it("sets order of given blockhashes starting from 0") {
stub(mockStorage) { mock in
when(mock.lastBlockHash.get).thenReturn(nil)
}
syncer.add(blockHashes: [existingBlockHash, newBlockHash])
verify(mockFactory).blockHash(withHeaderHash: equal(to: newBlockHash), height: equal(to: 0), order: equal(to: 1))
verify(mockStorage).add(blockHashes: equal(to: [blockHash]))
}
}
}
describe("#handle(merkleBlock:,maxBlockHeight:)") {
let block = TestData.firstBlock
let merkleBlock = MerkleBlock(header: block.header, transactionHashes: [], transactions: [])
let maxBlockHeight: Int32 = Int32(block.height + 100)
beforeEach {
stub(mockBlockchain) { mock in
when(mock.forceAdd(merkleBlock: equal(to: merkleBlock), height: equal(to: block.height))).thenReturn(block)
when(mock.connect(merkleBlock: equal(to: merkleBlock))).thenReturn(block)
}
stub(mockTransactionProcessor) { mock in
when(mock.processReceived(transactions: any(), inBlock: any(), skipCheckBloomFilter: any())).thenDoNothing()
}
stub(mockState) { mock in
when(mock.iterationHasPartialBlocks.get).thenReturn(false)
}
stub(mockStorage) { mock in
when(mock.deleteBlockHash(byHash: equal(to: block.headerHash))).thenDoNothing()
}
stub(mockListener) { mock in
when(mock.currentBestBlockHeightUpdated(height: equal(to: Int32(block.height)), maxBlockHeight: equal(to: maxBlockHeight))).thenDoNothing()
}
}
it("handles merkleBlock") {
try! syncer.handle(merkleBlock: merkleBlock, maxBlockHeight: maxBlockHeight)
verify(mockBlockchain).connect(merkleBlock: equal(to: merkleBlock))
verify(mockTransactionProcessor).processReceived(transactions: equal(to: [FullTransaction]()), inBlock: equal(to: block), skipCheckBloomFilter: equal(to: false))
verify(mockStorage).deleteBlockHash(byHash: equal(to: block.headerHash))
verify(mockListener).currentBestBlockHeightUpdated(height: equal(to: Int32(block.height)), maxBlockHeight: equal(to: maxBlockHeight))
}
context("when merklBlocks's height is null") {
it("force adds the block to blockchain") {
merkleBlock.height = block.height
try! syncer.handle(merkleBlock: merkleBlock, maxBlockHeight: maxBlockHeight)
verify(mockBlockchain).forceAdd(merkleBlock: equal(to: merkleBlock), height: equal(to: block.height))
verifyNoMoreInteractions(mockBlockchain)
}
}
context("when bloom filter is expired while processing transactions") {
it("sets iteration state to hasPartialBlocks") {
stub(mockTransactionProcessor) { mock in
when(mock.processReceived(transactions: equal(to: [FullTransaction]()), inBlock: equal(to: block), skipCheckBloomFilter: equal(to: false))).thenThrow(BloomFilterManager.BloomFilterExpired())
}
try! syncer.handle(merkleBlock: merkleBlock, maxBlockHeight: maxBlockHeight)
verify(mockState).iteration(hasPartialBlocks: equal(to: true))
}
}
context("when iteration has partial blocks") {
it("doesn't delete block hash") {
stub(mockState) { mock in
when(mock.iterationHasPartialBlocks.get).thenReturn(true)
}
stub(mockTransactionProcessor) { mock in
when(mock.processReceived(transactions: equal(to: []), inBlock: equal(to: block), skipCheckBloomFilter: equal(to: true))).thenDoNothing()
}
try! syncer.handle(merkleBlock: merkleBlock, maxBlockHeight: maxBlockHeight)
verify(mockStorage, never()).deleteBlockHash(byHash: equal(to: block.headerHash))
}
}
}
describe("#shouldRequestBlock(withHash:)") {
let hash = Data(repeating: 0, count: 32)
context("when the given block is in storage") {
it("returns false") {
stub(mockStorage) { mock in
when(mock.block(byHash: equal(to: hash))).thenReturn(TestData.firstBlock)
}
expect(syncer.shouldRequestBlock(withHash: hash)).to(beFalsy())
}
}
context("when the given block is not in storage") {
it("returns true") {
stub(mockStorage) { mock in
when(mock.block(byHash: equal(to: hash))).thenReturn(nil)
}
expect(syncer.shouldRequestBlock(withHash: hash)).to(beTruthy())
}
}
}
}
}
}
| 48.105072 | 218 | 0.513444 |
8991a67d71e86b0d86397cc712bd0806ae6e3dc2 | 296 | //
// ImageObject.swift
// PhotoJournal
//
// Created by Oscar Victoria Gonzalez on 1/24/20.
// Copyright © 2020 Oscar Victoria Gonzalez . All rights reserved.
//
import Foundation
struct ImageObject: Codable {
let imageData: Data
let date: Date
let identifier = UUID().uuidString
}
| 18.5 | 67 | 0.709459 |
6913615e1f5ab05aea2cbe8bb0d922d891b83c80 | 6,234 | //
// CustomCombinedChartRenderer.swift
// Charts
//
// Created by GEM on 5/14/18.
//
import Foundation
import CoreGraphics
open class CustomCombinedChartRenderer: DataRenderer
{
open weak var chart: CustomCombinedChartView?
/// if set to true, all values are drawn above their bars, instead of below their top
open var drawValueAboveBarEnabled = true
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
open var drawBarShadowEnabled = false
internal var _renderers = [DataRenderer]()
internal var _drawOrder: [CustomCombinedChartView.DrawOrder] = [.bar, .bubble, .line, .candle, .scatter]
public init(chart: CustomCombinedChartView?, animator: Animator, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
createRenderers()
}
/// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration.
internal func createRenderers()
{
_renderers = [DataRenderer]()
guard let
chart = chart,
let animator = animator,
let viewPortHandler = self.viewPortHandler
else { return }
for order in drawOrder
{
switch (order)
{
case .bar:
if chart.barData !== nil
{
_renderers.append(BarChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler))
}
break
case .line:
if chart.lineData !== nil
{
_renderers.append(LineChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler))
}
break
case .candle:
if chart.candleData !== nil
{
_renderers.append(CandleStickChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler))
}
break
case .scatter:
if chart.scatterData !== nil
{
_renderers.append(ScatterChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler))
}
break
case .bubble:
if chart.bubbleData !== nil
{
_renderers.append(BubbleChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler))
}
break
}
}
}
open override func initBuffers()
{
for renderer in _renderers
{
renderer.initBuffers()
}
}
open override func drawData(context: CGContext)
{
for renderer in _renderers
{
renderer.drawData(context: context)
}
}
open override func drawValues(context: CGContext)
{
for renderer in _renderers
{
renderer.drawValues(context: context)
}
}
open override func drawExtras(context: CGContext)
{
for renderer in _renderers
{
renderer.drawExtras(context: context)
}
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
for renderer in _renderers
{
var data: ChartData?
if renderer is BarChartRenderer
{
data = (renderer as! BarChartRenderer).dataProvider?.barData
}
else if renderer is LineChartRenderer
{
data = (renderer as! LineChartRenderer).dataProvider?.lineData
}
else if renderer is CandleStickChartRenderer
{
data = (renderer as! CandleStickChartRenderer).dataProvider?.candleData
}
else if renderer is ScatterChartRenderer
{
data = (renderer as! ScatterChartRenderer).dataProvider?.scatterData
}
else if renderer is BubbleChartRenderer
{
data = (renderer as! BubbleChartRenderer).dataProvider?.bubbleData
}
let dataIndex = data == nil ? nil : (chart?.data as? CombinedChartData)?.allData.index(of: data!)
let dataIndices = indices.filter{ $0.dataIndex == dataIndex || $0.dataIndex == -1 }
renderer.drawHighlighted(context: context, indices: dataIndices)
}
}
/// - returns: The sub-renderer object at the specified index.
open func getSubRenderer(index: Int) -> DataRenderer?
{
if index >= _renderers.count || index < 0
{
return nil
}
else
{
return _renderers[index]
}
}
/// - returns: All sub-renderers.
open var subRenderers: [DataRenderer]
{
get { return _renderers }
set { _renderers = newValue }
}
// MARK: Accessors
/// - returns: `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled }
/// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled }
/// the order in which the provided data objects should be drawn.
/// The earlier you place them in the provided array, the further they will be in the background.
/// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines.
open var drawOrder: [CustomCombinedChartView.DrawOrder]
{
get
{
return _drawOrder
}
set
{
if newValue.count > 0
{
_drawOrder = newValue
}
}
}
}
| 31.014925 | 138 | 0.555662 |
dbc5dcb6e0622bddc95ab88ad89fd6f34486ff68 | 1,274 | //
// BaseViewController.swift
// RamonBBCChallengeiOS
//
// Created by Ramon Haro Marques on 18/06/2019.
// Copyright © 2019 Reimond Hill. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
//MARK:- Properties
//MARK: Constants
let networkHelper:NetworkHelper
//MARK: Vars
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
//MARK:- Constructor
init(networkHelper:NetworkHelper = NetworkHelper.shared) {
self.networkHelper = networkHelper
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:- Lifecycle methods
extension BaseViewController{
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.mainViewBackground
view.accessibilityIdentifier = identifier
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
AnalyticsHelper.sendScreenAnalyticsEvent(identifier: identifier, network: networkHelper.network, completion: nil)
}
}
| 21.965517 | 121 | 0.647567 |
ac18bf35b546123f721880dea53a3c7cb03cd8d7 | 19,984 | //
// JCGroupSettingViewController.swift
// JChat
//
// Created by JIGUANG on 2017/4/27.
// Copy © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCGroupSettingViewController: CTViewController {
var group: JMSGGroup!
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private var tableView: UITableView = UITableView(frame: .zero, style: .grouped)
fileprivate var memberCount = 0
fileprivate lazy var users: [JMSGUser] = []
fileprivate var isMyGroup = false
fileprivate var isNeedUpdate = false
var customType:CustomerType = .otherMember
//MARK: - private func
private func _init() {
self.title = "群组信息"
view.backgroundColor = .white
users = group.memberArray()
// users = users + users + users
memberCount = users.count
// let user = JMSGUser.myInfo()
// && group.ownerAppKey == user.appKey! 这里group.ownerAppKey == "" 目测sdk bug
// if group.owner == user.username {
// isMyGroup = true
// }
customType = MJManager.customerType()
// customType = .inService
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.sectionIndexColor = UIColor(netHex: 0x2dd0cf)
tableView.sectionIndexBackgroundColor = .clear
tableView.register(JCButtonCell.self, forCellReuseIdentifier: "JCButtonCell")
tableView.register(JCMineInfoCell.self, forCellReuseIdentifier: "JCMineInfoCell")
tableView.register(GroupAvatorCell.self, forCellReuseIdentifier: "GroupAvatorCell")
// tableView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height-56)
view.addSubview(tableView)
// self.view.addSubview(exitGroupBtn)
// exitGroupBtn.snp.makeConstraints { (make) in
// make.left.right.bottom.equalToSuperview()
// make.height.equalTo(56)
// }
tableView.snp.makeConstraints { (make) in
make.top.left.right.equalToSuperview()
make.bottom.equalTo(self.view)
}
// customLeftBarButton(delegate: self)
JMSGGroup.groupInfo(withGroupId: group.gid) { (result, error) in
if error == nil {
guard let group = result as? JMSGGroup else {
return
}
self.group = group
self.isNeedUpdate = true
self._updateGroupInfo()
}
}
NotificationCenter.default.addObserver(self, selector: #selector(_updateGroupInfo), name: NSNotification.Name(rawValue: kUpdateGroupInfo), object: nil)
}
fileprivate lazy var exitGroupBtn : UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.white
button.setTitle("退出此群", for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.addTarget(self, action: #selector(exitGroup), for: .touchUpInside)
return button
}()
//MARK: 退出此群
@objc fileprivate func exitGroup(sender:UIButton) {
buttonCell(clickButton: sender)
}
@objc func _updateGroupInfo() {
if !isNeedUpdate {
let conv = JMSGConversation.groupConversation(withGroupId: group.gid)
group = conv?.target as! JMSGGroup
}
if group.memberArray().count != memberCount {
isNeedUpdate = true
memberCount = group.memberArray().count
}
users = group.memberArray()
memberCount = users.count
tableView.reloadData()
// if !isNeedUpdate {
// let conv = JMSGConversation.groupConversation(withGroupId: group.gid)
// group = conv?.target as? JMSGGroup
// }
// if group.memberArray().count != memberCount {
// isNeedUpdate = true
// }
//
// group.memberInfoList {[weak self] (list, error) in
// if let userArr = list as? [JMSGUser] {
// if userArr.count != self?.memberCount {
// self?.isNeedUpdate = true
// self?.memberCount = userArr.count
// }
// self?.users = userArr
// self?.memberCount = self?.users.count ?? 0
// self?.tableView.reloadData()
// }
// }
//////////11111
// group.memberArray {[weak self] (list, error) in
// if let userArr = list as? [JMSGUser] {
// if userArr.count != self?.memberCount {
// self?.isNeedUpdate = true
// self?.memberCount = userArr.count
// }
// self?.users = userArr
// self?.memberCount = self?.users.count ?? 0
// self?.tableView.reloadData()
// }
//
// }
// if group.memberArray().count != memberCount {
// isNeedUpdate = true
// memberCount = group.memberArray().count
// }
// users = group.memberArray()
// memberCount = users.count
// tableView.reloadData()
}
}
extension JCGroupSettingViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 1
case 2:
return 3
case 3:
// return 5
return 3
case 4:
return 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
if customType == .inService {
if memberCount > 13 {
return 314
}
if memberCount > 8 {
return 260
}
if memberCount > 3 {
return 200
}
return 100
}else if customType == .outService {
if memberCount > 14 {
return 314
}
if memberCount > 9 {
return 260
}
if memberCount > 4 {
return 200
}
return 100
}else{
if memberCount > 15 {
return 314
}
if memberCount > 10 {
return 260
}
if memberCount > 5 {
return 200
}
return 100
}
// if isMyGroup {
// if memberCount > 13 {
// return 314
// }
// if memberCount > 8 {
// return 260
// }
// if memberCount > 3 {
// return 200
// }
// return 100
// } else {
// if memberCount > 14 {
// return 314
// }
// if memberCount > 9 {
// return 260
// }
// if memberCount > 4 {
// return 200
// }
// return 100
// }
case 1:
return 45
case 2:
return 45
case 3:
return 40
default:
return 45
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// if section == 0 {
// return 0.0001
// }
return 8
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0001
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
var cell = tableView.dequeueReusableCell(withIdentifier: "JCGroupSettingCell") as? JCGroupSettingCell
if isNeedUpdate {
cell = JCGroupSettingCell(style: .default, reuseIdentifier: "JCGroupSettingCell", group: self.group)
isNeedUpdate = false
}
if cell == nil {
cell = JCGroupSettingCell(style: .default, reuseIdentifier: "JCGroupSettingCell", group: self.group)
}
return cell!
}
if indexPath.section == 4 {
return tableView.dequeueReusableCell(withIdentifier: "JCButtonCell", for: indexPath)
}
if indexPath.section == 2 && indexPath.row == 0 {
return tableView.dequeueReusableCell(withIdentifier: "GroupAvatorCell", for: indexPath)
}
if indexPath.section == 1 {
return tableView.dequeueReusableCell(withIdentifier: "GroupAvatorCell", for: indexPath)
}
return tableView.dequeueReusableCell(withIdentifier: "JCMineInfoCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.selectionStyle = .none
if indexPath.section == 4 {
guard let cell = cell as? JCButtonCell else {
return
}
cell.buttonColor = UIColor(netHex: 0xEB424D)
cell.buttonTitle = "退出此群"
cell.delegate = self
return
}
cell.accessoryType = .disclosureIndicator
if indexPath.section == 0 {
guard let cell = cell as? JCGroupSettingCell else {
return
}
cell.bindData(self.group)
cell.delegate = self
cell.accessoryType = .none
return
}
if let cell = cell as? GroupAvatorCell {
if indexPath.section == 2 {
cell.title = "群头像"
cell.bindData(group)
}else if indexPath.section == 1 {
cell.title = "群二维码"
cell.avator = UIImage.init(named: "二维码")
}
}
guard let cell = cell as? JCMineInfoCell else {
return
}
if indexPath.section == 3 {
if indexPath.row == 0 {
cell.delegate = self
cell.indexPate = indexPath
cell.accessoryType = .none
cell.isSwitchOn = group.isNoDisturb
cell.isShowSwitch = true
}
if indexPath.row == 1 {
cell.delegate = self
cell.indexPate = indexPath
cell.accessoryType = .none
cell.isSwitchOn = group.isShieldMessage
cell.isShowSwitch = true
}
}
if indexPath.section == 2 {
let conv = JMSGConversation.groupConversation(withGroupId: self.group.gid)
let group = conv?.target as! JMSGGroup
switch indexPath.row {
case 1:
cell.title = "群聊名称"
cell.detail = group.displayName()
case 2:
cell.title = "群描述"
cell.detail = group.desc
default:
break
}
} else if indexPath.section == 3 {
switch indexPath.row {
// case 0:
// cell.title = "聊天文件"
case 0:
cell.title = "消息免打扰"
case 1:
cell.title = "消息屏蔽"
// case 2:
// cell.title = "清理缓存"
case 2:
cell.title = "清空聊天记录"
default:
break
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 2 {
let gid = CacheClass.stringForEnumKey(.groupid) ?? ""
let customer_type = CacheClass.stringForEnumKey(.customer_type) ?? ""
if gid == "5" && customer_type == "0" { //内部客服
switch indexPath.row {
case 0:
let vc = GroupAvatorViewController()
vc.group = group
navigationController?.pushViewController(vc, animated: true)
case 1:
let vc = JCGroupNameViewController()
vc.group = group
navigationController?.pushViewController(vc, animated: true)
case 2:
let vc = JCGroupDescViewController()
vc.group = group
navigationController?.pushViewController(vc, animated: true)
default:
break
}
}else{
MBProgressHUD_JChat.show(text: "你没有修改权限", view: self.view)
}
}
if indexPath.section == 1 {
let gid = CacheClass.stringForEnumKey(.groupid) ?? ""
if gid == "5" { //客服
let vc = UserQRCodeVC()//MJ
vc.group = group
navigationController?.pushViewController(vc, animated: true)
}else{
MBProgressHUD_JChat.show(text: "你没有权限", view: self.view)
}
}
if indexPath.section == 3 {
switch indexPath.row {
// case 2:
// let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "清理缓存")
// actionSheet.tag = 1001
// actionSheet.show(in: self.view)
// case 0:
// let vc = FileManagerViewController()
// let conv = JMSGConversation.groupConversation(withGroupId: group.gid)
// vc.conversation = conv
// navigationController?.pushViewController(vc, animated: true)
case 2:
let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "清空聊天记录")
actionSheet.tag = 1001
actionSheet.show(in: self.view)
default:
break
}
}
}
}
extension JCGroupSettingViewController: UIAlertViewDelegate {
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
switch buttonIndex {
case 1:
MBProgressHUD_JChat.showMessage(message: "退出中...", toView: self.view)
group.exit({ (result, error) in
MBProgressHUD_JChat.hide(forView: self.view, animated: true)
if error == nil {
self.navigationController?.popToRootViewController(animated: true)
} else {
MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view)
}
})
default:
break
}
}
}
extension JCGroupSettingViewController: JCMineInfoCellDelegate {
func mineInfoCell(clickSwitchButton button: UISwitch, indexPath: IndexPath?) {
if indexPath != nil {
switch (indexPath?.row)! {
case 1:
if group.isNoDisturb == button.isOn {
return
}
// 消息免打扰
group.setIsNoDisturb(button.isOn, handler: { (result, error) in
MBProgressHUD_JChat.hide(forView: self.view, animated: true)
if error != nil {
button.isOn = !button.isOn
MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view)
}
})
case 2:
if group.isShieldMessage == button.isOn {
return
}
// 消息屏蔽
group.setIsShield(button.isOn, handler: { (result, error) in
MBProgressHUD_JChat.hide(forView: self.view, animated: true)
if error != nil {
button.isOn = !button.isOn
MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view)
}
})
default:
break
}
}
}
}
extension JCGroupSettingViewController: JCButtonCellDelegate {
func buttonCell(clickButton button: UIButton) {
let alertView = UIAlertView(title: "退出此群", message: "确定要退出此群?", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
alertView.show()
}
}
extension JCGroupSettingViewController: JCGroupSettingCellDelegate {
func clickMoreButton(clickButton button: UIButton) {
let vc = JCGroupMembersViewController()
vc.group = self.group
self.navigationController?.pushViewController(vc, animated: true)
}
func clickAddCell(cell: JCGroupSettingCell) {
let vc = JCUpdateMemberViewController()
vc.group = group
self.navigationController?.pushViewController(vc, animated: true)
}
func clickRemoveCell(cell: JCGroupSettingCell) {
let vc = JCRemoveMemberViewController()
vc.group = group
self.navigationController?.pushViewController(vc, animated: true)
}
func didSelectCell(cell: JCGroupSettingCell, indexPath: IndexPath) {
let index = indexPath.section * 5 + indexPath.row
let user = users[index]
if user.isEqual(to: JMSGUser.myInfo()) {
let chatVC = ChatPersonalCenterVC()
chatVC.isMySelf = true
chatVC.user = user
navigationController?.pushViewController(/**JCMyInfoViewController()**/chatVC, animated: true)
return
}
let vc = ChatPersonalCenterVC() //JCUserInfoViewController()
vc.group = group
vc.user = user
navigationController?.pushViewController(vc, animated: true)
}
}
extension JCGroupSettingViewController: UIActionSheetDelegate {
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
// if actionSheet.tag == 1001 {
// // SDK 暂无该功能
// }
if actionSheet.tag == 1001 {
if buttonIndex == 1 {
let conv = JMSGConversation.groupConversation(withGroupId: group.gid)
conv?.deleteAllMessages()
NotificationCenter.default.post(name: Notification.Name(rawValue: kDeleteAllMessage), object: nil)
MBProgressHUD_JChat.show(text: "成功清空", view: self.view)
}
}
}
}
//extension JCGroupSettingViewController: UIGestureRecognizerDelegate {
// public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// return true
// }
//}
| 33.643098 | 159 | 0.514061 |
f72c51b08c114ae7245be2f3a6dafaf2db0304a4 | 446 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -emit-ir
protocol A{var f={struct ManagedBuffer{var f=(t:f
| 44.6 | 79 | 0.753363 |
fc6414e3dad61b6f2b502174866563f5ce4ae8ac | 1,889 | //
// FBRefreshHeader.swift
// JKSwiftRefresh_Example
//
// Created by IronMan on 2021/2/1.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import UIKit
import MJRefresh
class FBRefreshGifHeader: MJRefreshGifHeader {
override func prepare() {
super.prepare()
// 隐藏时间
setTitle("下拉刷新", for: .idle)
setTitle("松开立即刷新", for: .pulling)
setTitle("刷新中...", for: .refreshing)
// 修改字体
stateLabel!.font = UIFont.systemFont(ofSize: 12)
// 修改文字颜色
stateLabel!.textColor = UIColor(hexString: "#9C9CAB")
// 隐藏时间
lastUpdatedTimeLabel!.isHidden = true
// lastUpdatedTimeLabel!.textColor = UIColor.blue
// lastUpdatedTimeLabel!.font = UIFont.systemFont(ofSize: 13)
// 隐藏状态
// header.stateLabel!.isHidden = true
// 下拉过程时的图片集合(根据下拉距离自动改变)
var idleImages = [UIImage]()
idleImages.append(UIImage(named: "loading_1")!)
setImages(idleImages, for: .idle)
// 下拉到一定距离后,提示松开刷新的图片集合(定时自动改变)
var pullingImages = [UIImage]()
pullingImages.append(UIImage(named: "loading_1")!)
setImages(pullingImages, for: .pulling)
// 刷新状态下的图片集合(定时自动改变)
var refreshingImages = [UIImage]()
for i in 1...22 {
refreshingImages.append(UIImage(named:"loading_\(i)")!)
}
setImages(refreshingImages, for: .refreshing)
// 下面表示刷新图片在1秒钟的时间内播放一轮
setImages(refreshingImages, duration: 2, for: .refreshing)
self.mj_h = 70
}
// 在这里设置子控件的位置和尺寸
override func placeSubviews() {
super.placeSubviews()
gifView!.frame = CGRect(x: UIScreen.main.bounds.width / 2.0 - 20, y: 11, width: 40, height: 40)
stateLabel!.frame = CGRect(x: 0, y: gifView!.jk.bottom + 2, width: kScreenW, height: 14)
}
}
| 30.467742 | 103 | 0.599788 |
d9ed4dace5933de5613645867fcb05b499fdac62 | 296 | // Copyright (c) 2019 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
/// A type that represents an archive.
public protocol Archive {
/// Unarchive data from the archive.
static func unarchive(archive: Data) throws -> Data
}
| 19.733333 | 55 | 0.722973 |
7544e9957533611e876892876985578f3efe247b | 5,512 | import Foundation
import JSBridge
import PromiseKit
import XCTest
import Marionette
@available(iOS 11.0, macOS 10.13, *)
class WaitTests: MarionetteTestCase {
func test_waitForFunction_shouldAcceptAString() {
let page = Marionette()
let watchdog = page.waitForFunction("window.__FOO === 1")
expectation() {
firstly {
page.evaluate("window.__FOO = 1")
}.then {
watchdog
}
}
waitForExpectations(timeout: 5)
}
func test_waitForFunction_shouldSurviveCrossProcessNavigation() {
let page = Marionette()
var fooFound = false
let waitForSelector = page.waitForFunction("window.__FOO === 1").done { _ in fooFound = true }
expectation() {
firstly {
page.goto(AssetServer.url(forFile: "empty.html"))
}.done {
XCTAssertEqual(fooFound, false)
}.then {
page.reload()
}.done {
XCTAssertEqual(fooFound, false)
}.then {
page.goto(AssetServer.url(forFile: "grid.html"))
}.done {
XCTAssertEqual(fooFound, false)
}.then {
page.evaluate("window.__FOO = 1")
}.then {
waitForSelector
}.done {
XCTAssertEqual(fooFound, true)
}
}
waitForExpectations(timeout: 5)
}
func test_waitForSelector_shouldImmediatelyResolvePromiseIfNodeExists() {
let page = Marionette()
expectation() {
firstly {
page.goto(AssetServer.url(forFile: "empty.html"))
}.then {
page.waitForSelector("*")
}.then {
page.evaluate("document.body.appendChild(document.createElement('div'))")
}.then {
page.waitForSelector("div")
}
}
waitForExpectations(timeout: 5)
}
func test_waitForSelector_shouldResolvePromiseWhenNodeIsAdded() {
let page = Marionette()
let watchdog = page.waitForSelector("div")
expectation() {
firstly {
page.goto(AssetServer.url(forFile: "empty.html"))
}.then {
page.evaluate("document.body.appendChild(document.createElement('br'))")
}.then {
page.evaluate("document.body.appendChild(document.createElement('div'))")
}.then {
watchdog
}
}
waitForExpectations(timeout: 5)
}
func test_waitForSelector_shouldWorkWhenNodeIsAddedThroughInnerHtml() {
let page = Marionette()
let watchdog = page.waitForSelector("h3 div")
expectation() {
firstly {
page.goto(AssetServer.url(forFile: "empty.html"))
}.then {
page.evaluate("document.body.appendChild(document.createElement('span'))")
}.then {
page.evaluate("document.querySelector('span').innerHTML = '<h3><div></div></h3>'")
}.then {
watchdog
}
}
waitForExpectations(timeout: 5)
}
func test_waitForSelector_shouldThrowIfEvaluationFailed() {
let page = Marionette()
expectation() {
firstly {
page.goto(AssetServer.url(forFile: "empty.html"))
}.then {
page.evaluate("document.querySelector = null")
}.then {
page.waitForSelector("*")
}.done {
XCTFail("Missed expected error")
}.recover { (err) throws -> Promise<Void> in
guard let e = err as? JSError else { throw err }
XCTAssertNotNil(e.message.range(of: "document.querySelector is not a function"))
return Promise.value(())
}
}
waitForExpectations(timeout: 5)
}
func test_waitForSelector_shouldSurviveCrossProcessNavigation() {
let page = Marionette()
var boxFound = false
let waitForSelector = page.waitForSelector(".box").done { _ in boxFound = true }
expectation() {
firstly {
page.goto(AssetServer.url(forFile: "empty.html"))
}.done {
XCTAssertEqual(boxFound, false)
}.then {
page.reload()
}.done {
XCTAssertEqual(boxFound, false)
}.then {
page.goto(AssetServer.url(forFile: "grid.html"))
}.then {
waitForSelector
}.done {
XCTAssertEqual(boxFound, true)
}
}
waitForExpectations(timeout: 5)
}
func test_waitForSelector_shouldRespondToNodeAttributeMutation() {
let page = Marionette()
var divFound = false
let waitForSelector = page.waitForSelector(".zombo").done { _ in divFound = true }
expectation() {
firstly {
page.setContent("<div class='notZombo'></div>")
}.done {
XCTAssertEqual(divFound, false)
}.then {
page.evaluate("document.querySelector('div').className = 'zombo'")
}.then {
waitForSelector
}.done {
XCTAssertEqual(divFound, true)
}
}
waitForExpectations(timeout: 5)
}
}
| 29.634409 | 102 | 0.524492 |
dd15a8b03eea7bffad9645873c030a81e6d0efb9 | 1,990 | //
// String+DiskCache.swift
// MapCache
//
// Created by merlos on 02/06/2019.
//
// Based on String+Haneke.swift
// Haneke
// https://github.com/Haneke/HanekeSwift/blob/master/Haneke/String%2BHaneke.swift
//
//
import Foundation
///
/// Extension that adds a few methods that are useful for the `DiskCache`.
extension String {
/// Returns the escaped version of a filename.
func escapedFilename() -> String {
return [ "\0":"%00", ":":"%3A", "/":"%2F" ]
.reduce(self.components(separatedBy: "%").joined(separator: "%25")) {
str, m in str.components(separatedBy: m.0).joined(separator: m.1)
}
}
/// Returns the md5 digest of this string.
func toMD5() -> String {
guard let data = self.data(using: String.Encoding.utf8) else {
return self
}
let MD5Calculator = MD5(Array(data))
let MD5Data = MD5Calculator.calculate()
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(mutating: MD5Data)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.count)
let MD5String = NSMutableString()
for c in resultEnumerator {
MD5String.appendFormat("%02x", c)
}
return MD5String as String
}
/// Returns the path for the filename whose name is hold in this string.
///
/// This method is used to get the md5 file name from a string that is key filename.
func MD5Filename() -> String {
let MD5String = self.toMD5()
// NSString.pathExtension alone could return a query string, which can lead to very long filenames.
let pathExtension = URL(string: self)?.pathExtension ?? (self as NSString).pathExtension
if pathExtension.count > 0 {
return (MD5String as NSString).appendingPathExtension(pathExtension) ?? MD5String
} else {
return MD5String
}
}
}
| 32.622951 | 107 | 0.61809 |
03e8af398726fdb37e745f4651d37a82f9dd86bc | 10,740 | //
// Copyright © 2020 osy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Carbon.HIToolbox
private let macVkToScancode = [
kVK_ANSI_A: 0x1E,
kVK_ANSI_S: 0x1F,
kVK_ANSI_D: 0x20,
kVK_ANSI_F: 0x21,
kVK_ANSI_H: 0x23,
kVK_ANSI_G: 0x22,
kVK_ANSI_Z: 0x2C,
kVK_ANSI_X: 0x2D,
kVK_ANSI_C: 0x2E,
kVK_ANSI_V: 0x2F,
kVK_ANSI_B: 0x30,
kVK_ANSI_Q: 0x10,
kVK_ANSI_W: 0x11,
kVK_ANSI_E: 0x12,
kVK_ANSI_R: 0x13,
kVK_ANSI_Y: 0x15,
kVK_ANSI_T: 0x14,
kVK_ANSI_1: 0x02,
kVK_ANSI_2: 0x03,
kVK_ANSI_3: 0x04,
kVK_ANSI_4: 0x05,
kVK_ANSI_6: 0x07,
kVK_ANSI_5: 0x06,
kVK_ANSI_Equal: 0x0D,
kVK_ANSI_9: 0x0A,
kVK_ANSI_7: 0x08,
kVK_ANSI_Minus: 0x0C,
kVK_ANSI_8: 0x09,
kVK_ANSI_0: 0x0B,
kVK_ANSI_RightBracket: 0x1B,
kVK_ANSI_O: 0x18,
kVK_ANSI_U: 0x16,
kVK_ANSI_LeftBracket: 0x1A,
kVK_ANSI_I: 0x17,
kVK_ANSI_P: 0x19,
kVK_ANSI_L: 0x26,
kVK_ANSI_J: 0x24,
kVK_ANSI_Quote: 0x28,
kVK_ANSI_K: 0x25,
kVK_ANSI_Semicolon: 0x27,
kVK_ANSI_Backslash: 0x2B,
kVK_ANSI_Comma: 0x33,
kVK_ANSI_Slash: 0x35,
kVK_ANSI_N: 0x31,
kVK_ANSI_M: 0x32,
kVK_ANSI_Period: 0x34,
kVK_ANSI_Grave: 0x29,
kVK_ANSI_KeypadDecimal: 0x53,
kVK_ANSI_KeypadMultiply: 0x37,
kVK_ANSI_KeypadPlus: 0x4E,
kVK_ANSI_KeypadClear: 0x45,
kVK_ANSI_KeypadDivide: 0xE035,
kVK_ANSI_KeypadEnter: 0xE01C,
kVK_ANSI_KeypadMinus: 0x4A,
kVK_ANSI_KeypadEquals: 0x59,
kVK_ANSI_Keypad0: 0x52,
kVK_ANSI_Keypad1: 0x4F,
kVK_ANSI_Keypad2: 0x50,
kVK_ANSI_Keypad3: 0x51,
kVK_ANSI_Keypad4: 0x4B,
kVK_ANSI_Keypad5: 0x4C,
kVK_ANSI_Keypad6: 0x4D,
kVK_ANSI_Keypad7: 0x47,
kVK_ANSI_Keypad8: 0x48,
kVK_ANSI_Keypad9: 0x49,
kVK_Return: 0x1C,
kVK_Tab: 0x0F,
kVK_Space: 0x39,
kVK_Delete: 0x0E,
kVK_Escape: 0x01,
kVK_Command: 0xE05B,
kVK_Shift: 0x2A,
kVK_CapsLock: 0x3A,
kVK_Option: 0x38,
kVK_Control: 0x1D,
kVK_RightCommand: 0xE05C,
kVK_RightShift: 0x36,
kVK_RightOption: 0xE038,
kVK_RightControl: 0xE01D,
kVK_Function: 0x00,
kVK_F17: 0x68,
kVK_VolumeUp: 0xE030,
kVK_VolumeDown: 0xE02E,
kVK_Mute: 0xE020,
kVK_F18: 0x69,
kVK_F19: 0x6A,
kVK_F20: 0x6B,
kVK_F5: 0x3F,
kVK_F6: 0x40,
kVK_F7: 0x41,
kVK_F3: 0x3D,
kVK_F8: 0x42,
kVK_F9: 0x43,
kVK_F11: 0x57,
kVK_F13: 0x64,
kVK_F16: 0x67,
kVK_F14: 0x65,
kVK_F10: 0x44,
kVK_F12: 0x58,
kVK_F15: 0x66,
kVK_Help: 0x00,
kVK_Home: 0xE047,
kVK_PageUp: 0xE049,
kVK_ForwardDelete: 0xE053,
kVK_F4: 0x3E,
kVK_End: 0xE04F,
kVK_F2: 0x3C,
kVK_PageDown: 0xE051,
kVK_F1: 0x3B,
kVK_LeftArrow: 0xE04B,
kVK_RightArrow: 0xE04D,
kVK_DownArrow: 0xE050,
kVK_UpArrow: 0xE048,
kVK_ISO_Section: 0x00,
kVK_JIS_Yen: 0x7D,
kVK_JIS_Underscore: 0x73,
kVK_JIS_KeypadComma: 0x5C,
kVK_JIS_Eisu: 0x73,
kVK_JIS_Kana: 0x70,
]
class VMMetalView: MTKView {
weak var inputDelegate: VMMetalViewInputDelegate?
private var wholeTrackingArea: NSTrackingArea?
private var lastModifiers = NSEvent.ModifierFlags()
private(set) var isMouseCaptured = false
override var acceptsFirstResponder: Bool { true }
override func updateTrackingAreas() {
logger.debug("update tracking area")
let trackingArea = NSTrackingArea(rect: CGRect(origin: .zero, size: frame.size), options: [.mouseMoved, .mouseEnteredAndExited, .activeWhenFirstResponder], owner: self, userInfo: nil)
if let oldTrackingArea = wholeTrackingArea {
removeTrackingArea(oldTrackingArea)
NSCursor.unhide()
}
wholeTrackingArea = trackingArea
addTrackingArea(trackingArea)
super.updateTrackingAreas()
}
override func mouseEntered(with event: NSEvent) {
logger.debug("mouse entered")
NSCursor.hide()
}
override func mouseExited(with event: NSEvent) {
logger.debug("mouse exited")
NSCursor.unhide()
}
override func mouseDown(with event: NSEvent) {
logger.trace("mouse down: \(event.buttonNumber)")
inputDelegate?.mouseDown(button: .left)
}
override func rightMouseDown(with event: NSEvent) {
logger.trace("right mouse down: \(event.buttonNumber)")
inputDelegate?.mouseDown(button: .right)
}
override func mouseUp(with event: NSEvent) {
logger.trace("mouse up: \(event.buttonNumber)")
inputDelegate?.mouseUp(button: .left)
}
override func rightMouseUp(with event: NSEvent) {
logger.trace("right mouse up: \(event.buttonNumber)")
inputDelegate?.mouseUp(button: .right)
}
override func keyDown(with event: NSEvent) {
guard !event.isARepeat else { return }
logger.trace("key down: \(event.keyCode)")
inputDelegate?.keyDown(keyCode: macVkToScancode[Int(event.keyCode)] ?? 0)
}
override func keyUp(with event: NSEvent) {
logger.trace("key up: \(event.keyCode)")
inputDelegate?.keyUp(keyCode: macVkToScancode[Int(event.keyCode)] ?? 0)
}
override func flagsChanged(with event: NSEvent) {
let modifiers = event.modifierFlags
logger.trace("modifers: \(modifiers)")
if modifiers.isSuperset(of: [.option, .control]) {
logger.trace("release cursor")
inputDelegate?.requestReleaseCapture()
}
sendModifiers(lastModifiers.subtracting(modifiers), press: false)
sendModifiers(modifiers.subtracting(lastModifiers), press: true)
lastModifiers = modifiers
}
private func sendModifiers(_ modifier: NSEvent.ModifierFlags, press: Bool) {
if modifier.contains(.capsLock) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_CapsLock]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_CapsLock]!)
}
}
if modifier.contains(.command) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_Command]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_Command]!)
}
}
if modifier.contains(.control) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_Control]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_Control]!)
}
}
if modifier.contains(.function) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_Function]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_Function]!)
}
}
if modifier.contains(.help) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_Help]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_Help]!)
}
}
if modifier.contains(.option) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_Option]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_Option]!)
}
}
if modifier.contains(.shift) {
if press {
inputDelegate?.keyDown(keyCode: macVkToScancode[kVK_Shift]!)
} else {
inputDelegate?.keyUp(keyCode: macVkToScancode[kVK_Shift]!)
}
}
}
override func mouseDragged(with event: NSEvent) {
mouseMoved(with: event)
}
override func rightMouseDragged(with event: NSEvent) {
mouseMoved(with: event)
}
override func otherMouseDragged(with event: NSEvent) {
mouseMoved(with: event)
}
override func mouseMoved(with event: NSEvent) {
logger.trace("mouse moved: \(event.deltaX), \(event.deltaY)")
if isMouseCaptured {
inputDelegate?.mouseMove(relativePoint: CGPoint(x: event.deltaX, y: -event.deltaY),
button: NSEvent.pressedMouseButtons.inputButtons())
} else {
let location = event.locationInWindow
let converted = convert(location, from: nil)
inputDelegate?.mouseMove(absolutePoint: converted,
button: NSEvent.pressedMouseButtons.inputButtons())
}
}
override func scrollWheel(with event: NSEvent) {
guard event.deltaY != 0 else { return }
logger.trace("scroll: \(event.deltaY)")
inputDelegate?.mouseScroll(dy: event.deltaY,
button: NSEvent.pressedMouseButtons.inputButtons())
}
}
extension VMMetalView {
private var screenCenter: CGPoint? {
guard let window = self.window else { return nil }
guard let screen = window.screen else { return nil }
let centerView = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
let centerWindow = convert(centerView, to: nil)
var centerScreen = window.convertPoint(toScreen: centerWindow)
let screenHeight = screen.frame.height
centerScreen.y = screenHeight - centerScreen.y
logger.debug("screen \(centerScreen.x), \(centerScreen.y)")
return centerScreen
}
func captureMouse() {
CGAssociateMouseAndMouseCursorPosition(0)
CGWarpMouseCursorPosition(screenCenter ?? .zero)
isMouseCaptured = true
NSCursor.hide()
}
func releaseMouse() {
CGAssociateMouseAndMouseCursorPosition(1)
isMouseCaptured = false
NSCursor.unhide()
}
}
private extension Int {
func inputButtons() -> CSInputButton {
var pressed = CSInputButton()
if self & (1 << 0) != 0 {
pressed.formUnion(.left)
}
if self & (1 << 1) != 0 {
pressed.formUnion(.right)
}
if self & (1 << 2) != 0 {
pressed.formUnion(.middle)
}
return pressed
}
}
| 31.495601 | 191 | 0.625978 |
220b468bbfc016d714982ade20a3e1f9a9f96d05 | 399 | //
// HandicapTableCellView.swift
// Example-macOS
//
// Created by Christoph Wendt on 19.08.18.
// Copyright © 2018 Christoph Wendt. All rights reserved.
//
import Foundation
import Cocoa
class HandicapTableCellView: NSTableCellView {
@IBOutlet weak var textLabel: NSTextField!
@IBOutlet weak var subtitleTextLabel: NSTextField!
@IBOutlet weak var detailTextLabel: NSTextField!
}
| 23.470588 | 58 | 0.75188 |
097762ea29f772ecf5b7d79db9a5ad3fa72e8278 | 5,210 | //
// ViewController.swift
// SampleProject
//
// Created by VinayKiran M on 28/10/20.
//
import UIKit
class ViewController: UIViewController {
//MARK:- Variables
fileprivate var country: Country?
fileprivate var dataSource = [CellInfo]()
fileprivate var myTableView: UITableView?
var networkMangaer:NetworkManager? = NetworkManager()
//MARK:- View Life Cycle Metthods
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
self.networkMangaer?.delegate = self
setNavigationButton()
self.refreshTableView()
}
deinit {
self.networkMangaer?.delegate = nil
self.networkMangaer = nil
}
//MARK:- Custom Functions
@objc func refreshTableView() {
self.networkMangaer?.getTableDatat()
}
fileprivate func setNavigationButton() {
DispatchQueue.main.async {
let navButton = UIBarButtonItem(title: "Refresh", style: .plain, target: self, action: #selector(self.refreshTableView))
self.navigationItem.setRightBarButtonItems([navButton], animated: true)
}
}
fileprivate func initTableView() {
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: self.topbarHeight,
width: displayWidth,
height: displayHeight - self.topbarHeight))
myTableView?.register(CustomImageCell.self, forCellReuseIdentifier: "cellID")
myTableView?.dataSource = self
myTableView?.delegate = self
if let aView = self.myTableView {
self.view.addSubview(aView)
}
myTableView?.tableFooterView = UIView()
myTableView?.translatesAutoresizingMaskIntoConstraints = false
myTableView?.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
myTableView?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0).isActive = true
myTableView?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0).isActive = true
myTableView?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
func reloadTableData() {
DispatchQueue.main.async {
self.navigationItem.title = self.country?.title ?? ""
self.myTableView?.reloadData()
}
}
func parseResponse(_ data: Country) {
self.dataSource.removeAll()
for info in data.rows {
let aCellInfo = CellInfo ()
aCellInfo.title = info.title ?? ""
aCellInfo.description = info.description ?? ""
aCellInfo.imageURL = info.imageHref ?? ""
self.dataSource.append(aCellInfo)
}
}
}
//MARK:- Table View Methods
extension ViewController :UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as? CustomImageCell
aCell?.cellData = self.dataSource[indexPath.row]
aCell?.configureCelll()
aCell?.selectionStyle = .none
return aCell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let height = self.getTableHeightFor(indexPath.row)
return height
}
func getTableHeightFor(_ index: Int) -> CGFloat {
let labelWidth = (self.myTableView?.bounds.width ?? 0) - 180
var rowHeight:CGFloat = 30
if !self.dataSource[index].title.isEmpty {
let aTitleFont = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.bold)
var height = self.dataSource[index].title.sizeOfString(aTitleFont, constrainedToWidth: labelWidth).height
if height < 40 {
height = 40
}
rowHeight = rowHeight + height
}
if !self.dataSource[index].description.isEmpty {
let aSubtitleFont = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.thin)
let height = self.dataSource[index].description.sizeOfString(aSubtitleFont, constrainedToWidth: labelWidth).height
rowHeight = rowHeight + height
}
if rowHeight < 120 {
rowHeight = 120
}
return rowHeight
}
}
//MARK:- APICallBack Methods
extension ViewController: APICallBack {
func onData(_ info: Any?) {
if let data = info as? Country {
self.country = data
self.parseResponse(data)
self.reloadTableData()
}
}
func onError(_ error: String) {
print(error)
}
}
| 32.767296 | 132 | 0.621113 |
5b90b73109a93af8d2975f48dc74e30989d29cf7 | 1,122 | //
// AllData.swift
// CavExh
//
// Created by Tiago Henriques on 24/05/16.
// Copyright © 2016 Tiago Henriques. All rights reserved.
//
import Foundation
class AllData : NSObject, NSCoding {
var images: [Int: Image]
var authors: [String: Author]
var history: History
init (images:[Int: Image], authors:[String: Author], history:History) {
self.images = images
self.authors = authors
self.history = history
}
// MARK: NSCoding
required init(coder decoder: NSCoder) {
//Error here "missing argument for parameter name in call
self.images = decoder.decodeObjectForKey("images") as! [Int: Image]
self.authors = decoder.decodeObjectForKey("authors") as! [String: Author]
self.history = decoder.decodeObjectForKey("history") as! History
super.init()
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.images, forKey: "images")
coder.encodeObject(self.authors, forKey: "authors")
coder.encodeObject(self.history, forKey: "history")
}
} | 26.714286 | 81 | 0.629234 |
d6e6d5051873c8031ca07b4147afe065f330f05b | 1,527 | @testable import KsApi
import Library
import Prelude
import Prelude_UIKit
import UIKit
import PlaygroundSupport
@testable import Kickstarter_Framework
let backer = User.brando
let creator = .template
|> \.id .~ 808
|> \.name .~ "Native Squad"
let project = .template
|> Project.lens.creator .~ creator
|> Project.lens.personalization.isBacking .~ false
let backerComment = .template
|> Comment.lens.author .~ backer
|> Comment.lens.body .~ "I have never seen such a beautiful project."
let creatorComment = .template
|> Comment.lens.author .~ creator
|> Comment.lens.body .~ "Thank you kindly for your feedback!"
let deletedComment = .template
|> Comment.lens.author .~ (.template |> \.name .~ "Naughty Blob")
|> Comment.lens.body .~ "This comment has been deleted by Kickstarter."
|> Comment.lens.deletedAt .~ NSDate().timeIntervalSince1970
let comments = [Comment.template, backerComment, creatorComment, deletedComment]
// Set the current app environment.
AppEnvironment.replaceCurrentEnvironment(
apiService: MockService(
fetchCommentsResponse: []
),
currentUser: backer,
language: .en,
locale: Locale(identifier: "en"),
mainBundle: Bundle.framework
)
// Initialize the view controller.
initialize()
let controller = CommentsViewController.configuredWith(project: project)
let (parent, _) = playgroundControllers(device: .phone4inch, orientation: .portrait, child: controller)
let frame = parent.view.frame
parent.view.frame = frame
PlaygroundPage.current.liveView = parent
| 28.277778 | 103 | 0.745252 |
e2f3b29c9201dfb17265a135de8a6312a890f564 | 975 | //
// UIImage+Pixel.swift
// TPSVG_Tests
//
// Created by Philip Niedertscheider on 28.11.18.
// Copyright © 2018 techprimate GmbH & Co. KG. All rights reserved.
//
/**
TODO: documentation
*/
extension UIImage {
/**
TODO: documentation
*/
internal func pixel(at point: CGPoint) -> UIColor? {
return cgImage?.pixel(at: point)
}
/**
TODO: documentation
*/
internal func pixels(at points: [CGPoint]) -> [UIColor]? {
return cgImage?.pixels(at: points)
}
/**
TODO: documentation
*/
internal func pixelsEqual(to other: UIImage, threshold: Double = 0.01) -> Bool {
return pixelError(to: other) <= threshold
}
/**
TODO: documentation
*/
internal func pixelError(to other: UIImage) -> Double {
guard let cgImg = self.cgImage, let otherCGImage = other.cgImage else {
return 1.0
}
return cgImg.pixelError(to: otherCGImage)
}
}
| 21.666667 | 84 | 0.591795 |
0ac0e9b4cfbda319755ce8ce78ce0ba896e02c29 | 15,231 | //
// BSViewsManager.swift
// BluesnapSDK
//
// Created by Shevie Chen on 23/04/2017.
// Copyright © 2017 Bluesnap. All rights reserved.
//
import Foundation
open class BSViewsManager {
// MARK: - Constants
static let bundleIdentifier = "com.bluesnap.BluesnapSDK"
static let storyboardName = "BlueSnap"
static let currencyScreenStoryboardId = "BSCurrenciesStoryboardId"
static let startScreenStoryboardId = "BSStartScreenStoryboardId"
static let purchaseScreenStoryboardId = "BSPaymentScreenStoryboardId"
static let existingCcScreenStoryboardId = "BSExistingCcScreenStoryboardId"
static let countryScreenStoryboardId = "BSCountriesStoryboardId"
static let stateScreenStoryboardId = "BSStatesStoryboardId"
static let webScreenStoryboardId = "BSWebViewController"
fileprivate static var currencyScreen: BSCurrenciesViewController!
fileprivate static var bsBundle: Bundle = createBundle()
/**
Create the bundle containing BlueSnap assets
*/
private static func createBundle() -> Bundle {
let bundleforURL = Bundle(for: BSViewsManager.self)
if let bundleurl = bundleforURL.url(forResource: "BluesnapUI", withExtension: "bundle") {
return Bundle(url: bundleurl)!
} else {
return Bundle(identifier: BSViewsManager.bundleIdentifier)!;
}
}
/**
Get the bundle containing BlueSnap assets
*/
public static func getBundle() -> Bundle {
return bsBundle
}
/**
Open the check-out start screen, where the shopper chooses CC/ApplePay.
- parameters:
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
*/
public static func showStartScreen(
inNavigationController: UINavigationController!,
animated: Bool) {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle)
let startScreen = storyboard.instantiateViewController(withIdentifier: BSViewsManager.startScreenStoryboardId) as! BSStartViewController
startScreen.initScreen()
inNavigationController.pushViewController(startScreen, animated: animated)
}
/**
Open the check-out screen, where the shopper payment details are entered.
- parameters:
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
*/
open class func showCCDetailsScreen(
existingCcPurchaseDetails: BSExistingCcSdkResult?,
inNavigationController: UINavigationController!,
animated: Bool) {
if let sdkRequest = BlueSnapSDK.sdkRequest {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle);
let purchaseScreen = storyboard.instantiateViewController(withIdentifier: BSViewsManager.purchaseScreenStoryboardId) as! BSPaymentViewController
let purchaseDetails = existingCcPurchaseDetails ?? BSCcSdkResult(sdkRequest: sdkRequest)
purchaseScreen.initScreen(purchaseDetails: purchaseDetails)
inNavigationController.pushViewController(purchaseScreen, animated: animated)
}
}
/**
Open the check-out screen for an existing CC, For returning shopper.
- parameters:
- purchaseDetails: returning shopper details in the payment request
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
*/
open class func showExistingCCDetailsScreen(
purchaseDetails: BSExistingCcSdkResult!,
inNavigationController: UINavigationController!,
animated: Bool) {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle);
let existingCcScreen = storyboard.instantiateViewController(withIdentifier: BSViewsManager.existingCcScreenStoryboardId) as! BSExistingCCViewController
existingCcScreen.initScreen(purchaseDetails: purchaseDetails)
inNavigationController.pushViewController(existingCcScreen, animated: animated)
}
/**
Open the shipping screen
- parameters:
- purchaseDetails: payment request (new or existing)
- submitPaymentFields: function to be called when clicking "Pay"
- validateOnEntry: true if you want to run validation
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
*/
open class func showShippingScreen(
purchaseDetails: BSCcSdkResult!,
submitPaymentFields: @escaping () -> Void,
validateOnEntry: Bool,
inNavigationController: UINavigationController!,
animated: Bool) {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle);
let shippingScreen = storyboard.instantiateViewController(withIdentifier: "BSShippingDetailsScreen") as! BSShippingViewController
shippingScreen.initScreen(purchaseDetails: purchaseDetails, submitPaymentFields: submitPaymentFields, validateOnEntry: validateOnEntry)
inNavigationController.pushViewController(shippingScreen, animated: true)
}
/**
Navigate to the country list, allow changing current selection.
- parameters:
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
- selectedCountryCode: ISO country code
- updateFunc: callback; will be called each time a new value is selected
*/
open class func showCountryList(
inNavigationController: UINavigationController!,
animated: Bool,
selectedCountryCode : String!,
updateFunc: @escaping (String, String)->Void) {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle)
let screen : BSCountryViewController! = storyboard.instantiateViewController(withIdentifier: BSViewsManager.countryScreenStoryboardId) as? BluesnapSDK.BSCountryViewController
screen.initCountries(selectedCode: selectedCountryCode, updateFunc: updateFunc)
inNavigationController.pushViewController(screen, animated: animated)
}
/**
Navigate to the currency list, allow changing current selection.
- parameters:
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
- selectedCurrencyCode: 3 characters of the current language code (uppercase)
- updateFunc: callback; will be called each time a new value is selected
- errorFunc: callback; will be called if we fail to get the currencies
*/
open class func showCurrencyList(
inNavigationController: UINavigationController!,
animated: Bool,
selectedCurrencyCode : String!,
updateFunc: @escaping (BSCurrency?, BSCurrency)->Void,
errorFunc: @escaping ()->Void) {
if currencyScreen == nil {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle)
currencyScreen = storyboard.instantiateViewController(withIdentifier: BSViewsManager.currencyScreenStoryboardId) as? BSCurrenciesViewController
}
currencyScreen.initCurrencies(
currencyCode: selectedCurrencyCode,
currencies: BSApiManager.bsCurrencies!,
updateFunc: updateFunc)
DispatchQueue.main.async {
inNavigationController.pushViewController(currencyScreen, animated: animated)
}
}
/**
Navigate to the state list, allow changing current selection.
- parameters:
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- animated: how to navigate to the new screen
- selectedCountryCode: ISO country code
- selectedStateCode: state code
- updateFunc: callback; will be called each time a new value is selected
*/
open class func showStateList(
inNavigationController: UINavigationController!,
animated: Bool,
addressDetails: BSBaseAddressDetails,
updateFunc: @escaping (String, String)->Void) {
let selectedCountryCode = addressDetails.country ?? ""
let selectedStateCode = addressDetails.state ?? ""
let countryManager = BSCountryManager.getInstance()
if let states = countryManager.getCountryStates(countryCode: selectedCountryCode) {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle)
let screen = storyboard.instantiateViewController(withIdentifier: BSViewsManager.stateScreenStoryboardId) as! BSStatesViewController
screen.initStates(selectedCode: selectedStateCode, allStates: states, updateFunc: updateFunc)
inNavigationController.pushViewController(screen, animated: animated)
} else {
NSLog("No state data available for \(selectedCountryCode)")
}
}
open class func getImage(imageName: String!) -> UIImage? {
var result : UIImage?
let myBundle = BSViewsManager.getBundle()
if let image = UIImage(named: imageName, in: myBundle, compatibleWith: nil) {
result = image
}
return result
}
open class func createErrorAlert(title: BSLocalizedString, message: BSLocalizedString) -> UIAlertController {
let messageText = BSLocalizedStrings.getString(message)
return createErrorAlert(title: title, message: messageText)
}
open class func createErrorAlert(title: BSLocalizedString, message: String) -> UIAlertController {
let titleText = BSLocalizedStrings.getString(title)
let okButtonText = BSLocalizedStrings.getString(BSLocalizedString.Alert_OK_Button_Text)
let alert = UIAlertController(title: titleText, message: message, preferredStyle: .alert)
let cancel = UIAlertAction(title: okButtonText, style: .default, handler: { (action) -> Void in })
alert.addAction(cancel)
return alert
//After you create alert, you show it like this: present(alert, animated: true, completion: nil)
}
open class func createActivityIndicator(view: UIView!) -> UIActivityIndicatorView {
let indicator = UIActivityIndicatorView()
view.addSubview(indicator)
indicator.center = view.center
indicator.hidesWhenStopped = true
indicator.style = .gray
return indicator
}
open class func startActivityIndicator(activityIndicator: UIActivityIndicatorView!, blockEvents: Bool) {
if blockEvents {
UIApplication.shared.beginIgnoringInteractionEvents()
}
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
activityIndicator.startAnimating()
}
}
}
open class func stopActivityIndicator(activityIndicator: UIActivityIndicatorView?) {
UIApplication.shared.endIgnoringInteractionEvents()
if let activityIndicator = activityIndicator {
DispatchQueue.global(qos: .default).async {
DispatchQueue.main.async {
activityIndicator.stopAnimating()
}
}
}
}
/*
Create the popup menu for payment screen
*/
open class func openPopupMenu(purchaseDetails: BSBaseSdkResult?,
inNavigationController : UINavigationController,
updateCurrencyFunc: @escaping (BSCurrency?, BSCurrency)->Void,
errorFunc: @escaping ()->Void) -> UIAlertController {
let menu = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
// Add change currency menu item
let currencyMenuTitle = BSLocalizedStrings.getString(BSLocalizedString.Menu_Item_Currency)
let currencyMenuOption = UIAlertAction(title: currencyMenuTitle, style: UIAlertAction.Style.default) { _ in
if let purchaseDetails = purchaseDetails {
BSViewsManager.showCurrencyList(
inNavigationController: inNavigationController,
animated: true,
selectedCurrencyCode: purchaseDetails.getCurrency(),
updateFunc: updateCurrencyFunc,
errorFunc: errorFunc)
}
}
menu.addAction(currencyMenuOption)
// Add Cancel menu item
let cancelMenuTitle = BSLocalizedStrings.getString(BSLocalizedString.Menu_Item_Cancel)
let cancelMenuOption = UIAlertAction(title: cancelMenuTitle, style: UIAlertAction.Style.cancel, handler: nil)
menu.addAction(cancelMenuOption)
//presentViewController(otherAlert, animated: true, completion: nil)
return menu
}
/**
Navigate to the web browser screen, showing the given URL.
- parameters:
- inNavigationController: your viewController's navigationController (to be able to navigate back)
- url : URL for the browser
*/
open class func showBrowserScreen(
inNavigationController: UINavigationController!,
url: String!, shouldGoToUrlFunc: ((_ url : String) -> Bool)?) {
let bundle = BSViewsManager.getBundle()
let storyboard = UIStoryboard(name: BSViewsManager.storyboardName, bundle: bundle)
let screen = storyboard.instantiateViewController(withIdentifier: BSViewsManager.webScreenStoryboardId) as! BSWebViewController
screen.initScreen(url: url, shouldGoToUrlFunc: shouldGoToUrlFunc)
inNavigationController.pushViewController(screen, animated: true)
}
/**
Generate the Pay button text according to the amounts
*/
open class func getPayButtonText(subtotalAmount: Double!, taxAmount: Double!, toCurrency: String!) -> String {
let amount = subtotalAmount + taxAmount
let currencyCode = (toCurrency == "USD" ? "$" : toCurrency) ?? ""
let payFormat = BSLocalizedStrings.getString(BSLocalizedString.Payment_Pay_Button_Format)
let result = String(format: payFormat, currencyCode, CGFloat(amount))
/*
TODO
Guy patch
*/
print("getPayButtonText:", amount)
if (amount == 0) {
return "SAVE"
}
return result
}
}
| 42.426184 | 182 | 0.686757 |
4a5aee4b8ad9f1f624daececab8b125926fcea94 | 1,682 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
/// Error enum for Batch
public enum BatchErrorType: AWSErrorType {
case clientException(message: String?)
case serverException(message: String?)
}
extension BatchErrorType {
public init?(errorCode: String, message: String?) {
var errorCode = errorCode
if let index = errorCode.firstIndex(of: "#") {
errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...])
}
switch errorCode {
case "ClientException":
self = .clientException(message: message)
case "ServerException":
self = .serverException(message: message)
default:
return nil
}
}
}
extension BatchErrorType: CustomStringConvertible {
public var description: String {
switch self {
case .clientException(let message):
return "ClientException: \(message ?? "")"
case .serverException(let message):
return "ServerException: \(message ?? "")"
}
}
}
| 32.346154 | 158 | 0.599287 |
f816022bbc6e95f08c8f0f669ffc22d5294bf1bf | 2,543 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************************************/
import UIKit
import KINWebBrowser
import RMBTClient
///
class StatisticsViewController: TopLevelViewController {
///
fileprivate let webBrowser = KINWebBrowserViewController()
///
override func viewDidLoad() {
super.viewDidLoad()
view.isOpaque = false
view.backgroundColor = UIColor.white
//webBrowser.delegate = self
webBrowser.showsPageTitleInNavigationBar = false
webBrowser.showsURLInNavigationBar = false
webBrowser.actionButtonHidden = false
webBrowser.tintColor = RMBTColorManager.navigationBarTitleColor
webBrowser.barTintColor = RMBTColorManager.navigationBarBackground
webBrowser.loadURLString(RMBTLocalizeURLString(RMBTConfiguration.RMBT_STATS_URL))
addChild(webBrowser)
view.addSubview(webBrowser.view)
setToolbarItems(webBrowser.toolbarItems!, animated: false)
}
///
fileprivate func enableWebBrowser(_ enabled: Bool) {
webBrowser.wkWebView?.scrollView.isScrollEnabled = enabled
webBrowser.view.isUserInteractionEnabled = enabled
}
}
// MARK: SWRevealViewControllerDelegate
///
extension StatisticsViewController {
///
func revealControllerPanGestureBegan(_ revealController: SWRevealViewController!) {
enableWebBrowser(false)
}
///
func revealControllerPanGestureEnded(_ revealController: SWRevealViewController!) {
enableWebBrowser(true)
}
///
override func revealController(_ revealController: SWRevealViewController!, didMoveTo position: FrontViewPosition) {
super.revealController(revealController, didMoveTo: position)
enableWebBrowser(position == .left)
}
}
| 31.7875 | 120 | 0.66221 |
dbf0314152161931bedf6cc1720a71a1f04f4a63 | 4,082 | //
// VideoCapture.swift
// Awesome ML
//
// Created by Eugene Bokhan on 3/13/18.
// Copyright © 2018 Eugene Bokhan. All rights reserved.
//
import UIKit
import AVFoundation
import CoreVideo
public protocol VideoCaptureDelegate: class {
func videoCapture(_ capture: VideoCapture, didCaptureVideoFrame: CVPixelBuffer?/*, timestamp: CMTime*/)
}
public class VideoCapture: NSObject {
public var previewLayer: AVCaptureVideoPreviewLayer?
public weak var delegate: VideoCaptureDelegate?
public var fps = 15
let captureSession = AVCaptureSession()
let videoOutput = AVCaptureVideoDataOutput()
let queue = DispatchQueue(label: "com.tucan9389.camera-queue")
// var lastTimestamp = CMTime()
public func setUp(sessionPreset: AVCaptureSession.Preset = .vga640x480,
completion: @escaping (Bool) -> Void) {
self.setUpCamera(sessionPreset: sessionPreset, completion: { success in
completion(success)
})
}
func setUpCamera(sessionPreset: AVCaptureSession.Preset, completion: @escaping (_ success: Bool) -> Void) {
captureSession.beginConfiguration()
captureSession.sessionPreset = sessionPreset
guard let captureDevice = AVCaptureDevice.default(for: AVMediaType.video) else {
print("Error: no video devices available")
return
}
guard let videoInput = try? AVCaptureDeviceInput(device: captureDevice) else {
print("Error: could not create AVCaptureDeviceInput")
return
}
if captureSession.canAddInput(videoInput) {
captureSession.addInput(videoInput)
}
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspect
previewLayer.connection?.videoOrientation = .portrait
self.previewLayer = previewLayer
let settings: [String : Any] = [
kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA),
]
videoOutput.videoSettings = settings
videoOutput.alwaysDiscardsLateVideoFrames = true
videoOutput.setSampleBufferDelegate(self, queue: queue)
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
}
// We want the buffers to be in portrait orientation otherwise they are
// rotated by 90 degrees. Need to set this _after_ addOutput()!
videoOutput.connection(with: AVMediaType.video)?.videoOrientation = .portrait
captureSession.commitConfiguration()
let success = true
completion(success)
}
public func start() {
if !captureSession.isRunning {
captureSession.startRunning()
}
}
public func stop() {
if captureSession.isRunning {
captureSession.stopRunning()
}
}
}
extension VideoCapture: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// Because lowering the capture device's FPS looks ugly in the preview,
// we capture at full speed but only call the delegate at its desired
// framerate.
// let timestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
// let deltaTime = timestamp - lastTimestamp
// if deltaTime >= CMTimeMake(1, Int32(fps)) {
// lastTimestamp = timestamp
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
delegate?.videoCapture(self, didCaptureVideoFrame: imageBuffer/*, timestamp: timestamp*/)
// }
}
public func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
//print("dropped frame")
}
}
| 36.123894 | 136 | 0.659971 |
1aa3aa9e4a2c5028dbb4f50784cfdbc8551f6b64 | 624 | //
// DrawingView1.swift
// Drawing
//
// Created by Tiger Yang on 9/8/21.
//
import SwiftUI
struct DrawingView1: View {
var body: some View {
HStack {
// stroke has the wide stroke half inside the shape, half outside
Circle()
.stroke(Color.blue, lineWidth: 40)
// stroke border draws the stroke strictly inside the shape border
Circle()
.strokeBorder(Color.blue, lineWidth: 40)
}
}
}
struct DrawingView1_Previews: PreviewProvider {
static var previews: some View {
DrawingView1()
}
}
| 21.517241 | 78 | 0.573718 |
03014e96faae385c5236816ace747c2ae37ba05d | 4,843 | //
// OrganizationAffiliation.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/OrganizationAffiliation) on 2019-05-21.
// 2019, SMART Health IT.
//
import Foundation
/**
Defines an affiliation/assotiation/relationship between 2 distinct oganizations, that is not a part-of relationship/sub-
division relationship.
*/
open class OrganizationAffiliation: DomainResource {
override open class var resourceType: String {
get { return "OrganizationAffiliation" }
}
/// Whether this organization affiliation record is in active use.
public var active: FHIRBool?
/// Definition of the role the participatingOrganization plays.
public var code: [CodeableConcept]?
/// Technical endpoints providing access to services operated for this role.
public var endpoint: [Reference]?
/// Healthcare services provided through the role.
public var healthcareService: [Reference]?
/// Business identifiers that are specific to this role.
public var identifier: [Identifier]?
/// The location(s) at which the role occurs.
public var location: [Reference]?
/// Health insurance provider network in which the participatingOrganization provides the role's services (if
/// defined) at the indicated locations (if defined).
public var network: [Reference]?
/// Organization where the role is available.
public var organization: Reference?
/// Organization that provides/performs the role (e.g. providing services or is a member of).
public var participatingOrganization: Reference?
/// The period during which the participatingOrganization is affiliated with the primary organization.
public var period: Period?
/// Specific specialty of the participatingOrganization in the context of the role.
public var specialty: [CodeableConcept]?
/// Contact details at the participatingOrganization relevant to this Affiliation.
public var telecom: [ContactPoint]?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
active = createInstance(type: FHIRBool.self, for: "active", in: json, context: &instCtx, owner: self) ?? active
code = createInstances(of: CodeableConcept.self, for: "code", in: json, context: &instCtx, owner: self) ?? code
endpoint = createInstances(of: Reference.self, for: "endpoint", in: json, context: &instCtx, owner: self) ?? endpoint
healthcareService = createInstances(of: Reference.self, for: "healthcareService", in: json, context: &instCtx, owner: self) ?? healthcareService
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
location = createInstances(of: Reference.self, for: "location", in: json, context: &instCtx, owner: self) ?? location
network = createInstances(of: Reference.self, for: "network", in: json, context: &instCtx, owner: self) ?? network
organization = createInstance(type: Reference.self, for: "organization", in: json, context: &instCtx, owner: self) ?? organization
participatingOrganization = createInstance(type: Reference.self, for: "participatingOrganization", in: json, context: &instCtx, owner: self) ?? participatingOrganization
period = createInstance(type: Period.self, for: "period", in: json, context: &instCtx, owner: self) ?? period
specialty = createInstances(of: CodeableConcept.self, for: "specialty", in: json, context: &instCtx, owner: self) ?? specialty
telecom = createInstances(of: ContactPoint.self, for: "telecom", in: json, context: &instCtx, owner: self) ?? telecom
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.active?.decorate(json: &json, withKey: "active", errors: &errors)
arrayDecorate(json: &json, withKey: "code", using: self.code, errors: &errors)
arrayDecorate(json: &json, withKey: "endpoint", using: self.endpoint, errors: &errors)
arrayDecorate(json: &json, withKey: "healthcareService", using: self.healthcareService, errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
arrayDecorate(json: &json, withKey: "location", using: self.location, errors: &errors)
arrayDecorate(json: &json, withKey: "network", using: self.network, errors: &errors)
self.organization?.decorate(json: &json, withKey: "organization", errors: &errors)
self.participatingOrganization?.decorate(json: &json, withKey: "participatingOrganization", errors: &errors)
self.period?.decorate(json: &json, withKey: "period", errors: &errors)
arrayDecorate(json: &json, withKey: "specialty", using: self.specialty, errors: &errors)
arrayDecorate(json: &json, withKey: "telecom", using: self.telecom, errors: &errors)
}
}
| 51.521277 | 171 | 0.747058 |
de7e246d0ff6ff9a34c9ca31846e02a8bfd2a0cc | 3,491 | //
// 🦠 Corona-Warn-App
//
import UIKit
import OpenCombine
class MultipleChoiceChoiceView: UIControl {
// MARK: - Init
@available(*, unavailable)
override init(frame: CGRect) {
fatalError("init(frame:) has not been implemented")
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(iconImage: UIImage?, title: String, accessibilityIdentifier: String? = nil, onTap: @escaping () -> Void) {
self.onTap = onTap
super.init(frame: .zero)
setUp(iconImage: iconImage, title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
// MARK: - Overrides
override var isSelected: Bool {
didSet {
updateForSelectionState()
}
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
onTap()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateForCurrentTraitCollection()
}
// MARK: - Private
private let onTap: () -> Void
private let checkmarkImageView = UIImageView()
private let iconImageView = UIImageView()
private func setUp(iconImage: UIImage?, title: String) {
backgroundColor = UIColor.enaColor(for: .background)
let contentStackView = UIStackView()
contentStackView.axis = .horizontal
contentStackView.alignment = .center
contentStackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentStackView)
NSLayoutConstraint.activate([
contentStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
contentStackView.topAnchor.constraint(equalTo: topAnchor, constant: 11),
contentStackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -11)
])
checkmarkImageView.adjustsImageSizeForAccessibilityContentSizeCategory = true
checkmarkImageView.setContentHuggingPriority(.required, for: .horizontal)
checkmarkImageView.setContentCompressionResistancePriority(.required, for: .horizontal)
contentStackView.addArrangedSubview(checkmarkImageView)
contentStackView.setCustomSpacing(21, after: checkmarkImageView)
if let iconImage = iconImage {
iconImageView.image = iconImage
iconImageView.contentMode = .scaleAspectFit
NSLayoutConstraint.activate([
iconImageView.widthAnchor.constraint(equalToConstant: 24),
iconImageView.heightAnchor.constraint(equalToConstant: 16)
])
contentStackView.addArrangedSubview(iconImageView)
contentStackView.setCustomSpacing(15, after: iconImageView)
}
let label = ENALabel()
label.numberOfLines = 0
label.text = title
label.style = .body
contentStackView.addArrangedSubview(label)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
addGestureRecognizer(tapGestureRecognizer)
updateForSelectionState()
updateForCurrentTraitCollection()
isAccessibilityElement = true
accessibilityLabel = title
}
@objc
private func viewTapped() {
onTap()
}
private func updateForSelectionState() {
checkmarkImageView.image = isSelected ? UIImage(named: "Checkmark_Selected") : UIImage(named: "Checkmark_Unselected")
accessibilityTraits = isSelected ? [.button, .selected] : [.button]
}
private func updateForCurrentTraitCollection() {
iconImageView.isHidden = traitCollection.preferredContentSizeCategory.isAccessibilityCategory
}
}
| 27.488189 | 119 | 0.775136 |
e58b3da37b65fd7eb6a91fce778ded3dfab08749 | 254 | //
// ManagersSpecialApp.swift
// ManagersSpecial
//
// Created by Ike Mattice on 5/27/21.
//
import SwiftUI
@main
struct ManagersSpecialApp: App {
var body: some Scene {
WindowGroup {
ManagersSpecialView()
}
}
}
| 14.111111 | 38 | 0.606299 |
d95d2ec4c7638318e1932cabab5c34407e34ca0d | 2,894 | /// Copyright (c) 2022 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 MetalKit
// swiftlint:disable force_unwrapping
// swiftlint:disable force_cast
struct Mesh {
let vertexBuffers: [MTLBuffer]
let submeshes: [Submesh]
var transform: TransformComponent?
}
extension Mesh {
init(mdlMesh: MDLMesh, mtkMesh: MTKMesh) {
var vertexBuffers: [MTLBuffer] = []
for mtkMeshBuffer in mtkMesh.vertexBuffers {
vertexBuffers.append(mtkMeshBuffer.buffer)
}
self.vertexBuffers = vertexBuffers
submeshes = zip(mdlMesh.submeshes!, mtkMesh.submeshes).map { mesh in
Submesh(mdlSubmesh: mesh.0 as! MDLSubmesh, mtkSubmesh: mesh.1)
}
}
init(
mdlMesh: MDLMesh,
mtkMesh: MTKMesh,
startTime: TimeInterval,
endTime: TimeInterval
) {
self.init(mdlMesh: mdlMesh, mtkMesh: mtkMesh)
if let mdlMeshTransform = mdlMesh.transform {
transform = TransformComponent(
transform: mdlMeshTransform,
object: mdlMesh,
startTime: startTime,
endTime: endTime)
} else {
transform = nil
}
}
}
| 39.108108 | 83 | 0.732205 |
ab95b00b226feac6012a93b6b62ac2af101c7b10 | 6,825 | class RemoteNotificationsOperationsController: NSObject {
private let apiController: RemoteNotificationsAPIController
private let modelController: RemoteNotificationsModelController?
private let deadlineController: RemoteNotificationsOperationsDeadlineController?
private let operationQueue: OperationQueue
private var isLocked: Bool = false {
didSet {
if isLocked {
stop()
}
}
}
required init(with session: Session) {
apiController = RemoteNotificationsAPIController(with: session)
var modelControllerInitializationError: Error?
modelController = RemoteNotificationsModelController(&modelControllerInitializationError)
deadlineController = RemoteNotificationsOperationsDeadlineController(with: modelController?.managedObjectContext)
if let modelControllerInitializationError = modelControllerInitializationError {
DDLogError("Failed to initialize RemoteNotificationsModelController and RemoteNotificationsOperationsDeadlineController: \(modelControllerInitializationError)")
isLocked = true
}
operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(didMakeAuthorizedWikidataDescriptionEdit), name: WikidataDescriptionEditingController.DidMakeAuthorizedWikidataDescriptionEditNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(modelControllerDidLoadPersistentStores(_:)), name: RemoteNotificationsModelController.didLoadPersistentStoresNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public func stop() {
operationQueue.cancelAllOperations()
}
@objc private func sync(_ completion: @escaping () -> Void) {
let completeEarly = {
self.operationQueue.addOperation(completion)
}
guard !isLocked else {
completeEarly()
return
}
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(sync), object: nil)
guard operationQueue.operationCount == 0 else {
completeEarly()
return
}
guard apiController.isAuthenticated else {
stop()
completeEarly()
return
}
guard deadlineController?.isBeforeDeadline ?? false else {
completeEarly()
return
}
guard let modelController = self.modelController else {
completeEarly()
return
}
let markAsReadOperation = RemoteNotificationsMarkAsReadOperation(with: apiController, modelController: modelController)
let fetchOperation = RemoteNotificationsFetchOperation(with: apiController, modelController: modelController)
let completionOperation = BlockOperation(block: completion)
fetchOperation.addDependency(markAsReadOperation)
completionOperation.addDependency(fetchOperation)
operationQueue.addOperation(markAsReadOperation)
operationQueue.addOperation(fetchOperation)
operationQueue.addOperation(completionOperation)
}
// MARK: Notifications
@objc private func didMakeAuthorizedWikidataDescriptionEdit(_ note: Notification) {
deadlineController?.resetDeadline()
}
@objc private func modelControllerDidLoadPersistentStores(_ note: Notification) {
if let object = note.object, let error = object as? Error {
DDLogDebug("RemoteNotificationsModelController failed to load persistent stores with error \(error); stopping RemoteNotificationsOperationsController")
isLocked = true
} else {
isLocked = false
}
}
}
extension RemoteNotificationsOperationsController: PeriodicWorker {
func doPeriodicWork(_ completion: @escaping () -> Void) {
sync(completion)
}
}
extension RemoteNotificationsOperationsController: BackgroundFetcher {
func performBackgroundFetch(_ completion: @escaping (UIBackgroundFetchResult) -> Void) {
doPeriodicWork {
completion(.noData)
}
}
}
// MARK: RemoteNotificationsOperationsDeadlineController
final class RemoteNotificationsOperationsDeadlineController {
private let remoteNotificationsContext: NSManagedObjectContext
init?(with remoteNotificationsContext: NSManagedObjectContext?) {
guard let remoteNotificationsContext = remoteNotificationsContext else {
return nil
}
self.remoteNotificationsContext = remoteNotificationsContext
}
let startTimeKey = "WMFRemoteNotificationsOperationsStartTime"
let deadline: TimeInterval = 86400 // 24 hours
private var now: CFAbsoluteTime {
return CFAbsoluteTimeGetCurrent()
}
private func save() {
guard remoteNotificationsContext.hasChanges else {
return
}
do {
try remoteNotificationsContext.save()
} catch let error {
DDLogError("Error saving managedObjectContext: \(error)")
}
}
public var isBeforeDeadline: Bool {
guard let startTime = startTime else {
return false
}
return now - startTime < deadline
}
private var startTime: CFAbsoluteTime? {
set {
let moc = remoteNotificationsContext
moc.perform {
if let newValue = newValue {
moc.wmf_setValue(NSNumber(value: newValue), forKey: self.startTimeKey)
} else {
moc.wmf_setValue(nil, forKey: self.startTimeKey)
}
self.save()
}
}
get {
let moc = remoteNotificationsContext
let value: CFAbsoluteTime? = moc.performWaitAndReturn {
let keyValue = remoteNotificationsContext.wmf_keyValue(forKey: startTimeKey)
guard let value = keyValue?.value else {
return nil
}
guard let number = value as? NSNumber else {
assertionFailure("Expected keyValue \(startTimeKey) to be of type NSNumber")
return nil
}
return number.doubleValue
}
return value
}
}
public func resetDeadline() {
startTime = now
}
}
private extension NSManagedObjectContext {
func performWaitAndReturn<T>(_ block: () -> T?) -> T? {
var result: T? = nil
performAndWait {
result = block()
}
return result
}
}
| 34.821429 | 225 | 0.65685 |
bb22b2fdb06a1dd935676027f2dc70724b7f1801 | 7,716 | //
// DPAGNavigationController.swift
// ginlo
//
// Created by RBU on 26/01/16.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import SIMSmeCore
import UIKit
class DPAGNavigationBar: UINavigationBar {
fileprivate func resetNavigationBarStyle() {
self.barTintColor = DPAGColorProvider.shared[.navigationBar]
self.tintColor = DPAGColorProvider.shared[.navigationBarTint]
self.titleTextAttributes = [.foregroundColor: DPAGColorProvider.shared[.navigationBarTint]]
self.shadowImage = UIImage()
self.largeTitleTextAttributes = [.foregroundColor: DPAGColorProvider.shared[.navigationBarTint]]
}
fileprivate func copyNavigationBarStyle(navBarSrc: UINavigationBar) {
self.barTintColor = navBarSrc.barTintColor
self.tintColor = navBarSrc.tintColor
self.titleTextAttributes = navBarSrc.titleTextAttributes
self.shadowImage = navBarSrc.shadowImage
self.largeTitleTextAttributes = navBarSrc.largeTitleTextAttributes
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let itemsLeft = self.topItem?.leftBarButtonItems {
for item in itemsLeft {
if let viewCustom = item.customView, let viewHit = viewCustom.hitTest(self.convert(point, to: viewCustom), with: event) {
return viewHit
}
}
}
if let itemsRight = self.topItem?.rightBarButtonItems {
for item in itemsRight {
if let viewCustom = item.customView, let viewHit = viewCustom.hitTest(self.convert(point, to: viewCustom), with: event) {
return viewHit
}
}
}
return super.hitTest(point, with: event)
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let itemsLeft = self.topItem?.leftBarButtonItems {
for item in itemsLeft {
if let viewCustom = item.customView, viewCustom.point(inside: self.convert(point, to: viewCustom), with: event) {
return true
}
}
}
if let itemsRight = self.topItem?.rightBarButtonItems {
for item in itemsRight {
if let viewCustom = item.customView, viewCustom.point(inside: self.convert(point, to: viewCustom), with: event) {
return true
}
}
}
return super.point(inside: point, with: event)
}
override
func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
DPAGColorProvider.shared.darkMode = traitCollection.userInterfaceStyle == .dark
self.barTintColor = DPAGColorProvider.shared[.navigationBar]
self.tintColor = DPAGColorProvider.shared[.navigationBarTint]
self.titleTextAttributes = [.foregroundColor: DPAGColorProvider.shared[.navigationBarTint]]
self.largeTitleTextAttributes = [.foregroundColor: DPAGColorProvider.shared[.navigationBarTint]]
}
} else {
DPAGColorProvider.shared.darkMode = false
}
}
}
class DPAGToolbar: UIToolbar {
fileprivate func copyToolBarStyle(navBarSrc: UINavigationBar) {
self.barTintColor = navBarSrc.barTintColor
self.tintColor = navBarSrc.tintColor
}
}
class DPAGNavigationController: UINavigationController, UINavigationControllerDelegate, DPAGNavigationControllerProtocol {
// needs to be strong reference
var transitioningDelegateZooming: UIViewControllerTransitioningDelegate?
convenience init() {
self.init(nibName: nil, bundle: Bundle(for: type(of: self)))
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.setValue(true, forKey: "hidesShadow")
}
override var childForStatusBarStyle: UIViewController? {
if let presentedViewController = self.presentedViewController, presentedViewController.isBeingDismissed == false {
return presentedViewController.childForStatusBarStyle
}
if self.viewControllers.count > 0 {
if let vc = self.topViewController {
if vc is DPAGNavigationControllerStatusBarStyleSetter {
return vc
}
}
}
return super.childForStatusBarStyle
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if let vc = self.childForStatusBarStyle {
if vc != self {
return vc.preferredStatusBarStyle
}
}
return DPAGColorProvider.shared.preferredStatusBarStyle
}
override var prefersStatusBarHidden: Bool {
if let vc = self.childForStatusBarStyle {
if vc != self {
return vc.prefersStatusBarHidden
}
}
return false
}
override var shouldAutorotate: Bool {
if self.viewControllers.count > 0 {
if let vc = self.topViewController {
return vc.shouldAutorotate
}
}
return super.shouldAutorotate
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
self.visibleViewController?.preferredInterfaceOrientationForPresentation ?? super.preferredInterfaceOrientationForPresentation
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if let visibleViewController = self.visibleViewController {
if AppConfig.isShareExtension == false {
if visibleViewController is UIAlertController {
if let topViewController = self.topViewController {
if let presentedViewController = topViewController.presentedViewController, presentedViewController != visibleViewController {
return presentedViewController.supportedInterfaceOrientations
}
return topViewController.supportedInterfaceOrientations
}
return super.supportedInterfaceOrientations
}
}
return visibleViewController.supportedInterfaceOrientations
}
return super.supportedInterfaceOrientations
}
func resetNavigationBarStyle() {
(self.navigationBar as? DPAGNavigationBar)?.resetNavigationBarStyle()
}
func copyNavigationBarStyle(navVCSrc: UINavigationController?) {
if let navVCSrc = navVCSrc {
(self.navigationBar as? DPAGNavigationBar)?.copyNavigationBarStyle(navBarSrc: navVCSrc.navigationBar)
}
}
func copyToolBarStyle(navVCSrc: UINavigationController?) {
if let navVCSrc = navVCSrc {
(self.toolbar as? DPAGToolbar)?.copyToolBarStyle(navBarSrc: navVCSrc.navigationBar)
}
}
}
| 37.823529 | 150 | 0.655132 |
62946f700b5b44a5e0ea3e35eb0bc688b056dcb0 | 4,770 | import Bootstrap
import Nimble
import Nimble_Snapshots
import Quick
class DynamicTypeTests: QuickSpec {
override func spec() {
describe("in some context") {
var view: UIView!
beforeEach {
setNimbleTolerance(0)
setNimbleTestFolder("tests")
view = DynamicTypeView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
}
it("has a valid snapshot for all content size categories (iOS 10)") {
let version = ProcessInfo.processInfo.operatingSystemVersion
guard version.iOS10 else {
return
}
expect(view).to(haveValidDynamicTypeSnapshot())
let name = "something custom_\(version.majorVersion)_\(version.minorVersion)"
expect(view).to(haveValidDynamicTypeSnapshot(named: name))
}
it("has a valid snapshot for a single content size category (iOS 10)") {
let version = ProcessInfo.processInfo.operatingSystemVersion
guard version.iOS10 else {
return
}
expect(view).to(haveValidDynamicTypeSnapshot(sizes: [.extraLarge]))
let name = "something custom_\(version.majorVersion)_\(version.minorVersion)"
expect(view).to(haveValidDynamicTypeSnapshot(named: name, sizes: [.extraLarge]))
}
it("has a valid pretty-syntax snapshot (iOS 10)") {
let version = ProcessInfo.processInfo.operatingSystemVersion
guard version.iOS10 else {
return
}
expect(view) == dynamicTypeSnapshot()
}
it("has a valid pretty-syntax snapshot for only one size category (iOS 10)") {
let version = ProcessInfo.processInfo.operatingSystemVersion
guard version.iOS10 else {
return
}
expect(view) == dynamicTypeSnapshot(sizes: [.extraLarge])
}
it("has a valid snapshot with model and OS in name") {
//expect(view).to(recordDynamicTypeSnapshot(isDeviceAgnostic: true))
expect(view).to(haveValidDynamicTypeSnapshot(isDeviceAgnostic: true))
//expect(view).to(recordDynamicTypeSnapshot(named: "something custom with model and OS", isDeviceAgnostic: true))
expect(view).to(haveValidDynamicTypeSnapshot(named: "something custom with model and OS",
isDeviceAgnostic: true))
}
it("has a valid snapshot with identifier") {
//expect(view).to(recordDynamicTypeSnapshot(identifier: "bootstrap"))
expect(view).to(haveValidDynamicTypeSnapshot(identifier: "bootstrap"))
//expect(view).to(recordDynamicTypeSnapshot(named: "something custom with model and OS", identifier: "bootstrap"))
expect(view).to(haveValidDynamicTypeSnapshot(named: "something custom with model and OS",
identifier: "bootstrap"))
}
it("works with adjustsFontForContentSizeCategory") {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 100))
label.text = "Example"
label.adjustsFontForContentSizeCategory = true
label.font = .preferredFont(forTextStyle: .body)
expect(label) == dynamicTypeSnapshot()
}
it("works with adjustsFontForContentSizeCategory in a subview") {
let frame = CGRect(x: 0, y: 0, width: 300, height: 100)
let view = UIView(frame: frame)
let label = UILabel(frame: frame)
label.text = "Example"
label.adjustsFontForContentSizeCategory = true
label.font = .preferredFont(forTextStyle: .body)
view.addSubview(label)
expect(view) == dynamicTypeSnapshot()
}
it("works with traitCollectionDidChange in a view controller from a storyboard") {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateInitialViewController()
controller?.beginAppearanceTransition(true, animated: false)
controller?.endAppearanceTransition()
expect(controller).to(haveValidDynamicTypeSnapshot())
}
}
}
}
private extension OperatingSystemVersion {
var iOS10: Bool {
return majorVersion == 10 && minorVersion == 3
}
}
| 41.478261 | 130 | 0.570021 |
d9f502674fb0569a53e8ebcc5d3c615e31daea9f | 212 | import UIKit
struct MenuItemOptions:MenuItemGenericProtocol
{
typealias A = ArchOptions
let order:Menu.Order = Menu.Order.options
let icon:UIImage = #imageLiteral(resourceName: "assetMenuOptions")
}
| 23.555556 | 70 | 0.768868 |
4ad9a195bd1257755d9e34adb775d921a19561e0 | 3,289 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for APIGateway
public struct APIGatewayErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case conflictException = "ConflictException"
case limitExceededException = "LimitExceededException"
case notFoundException = "NotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
case tooManyRequestsException = "TooManyRequestsException"
case unauthorizedException = "UnauthorizedException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize APIGateway
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The submitted request is not valid, for example, the input is incomplete or incorrect. See the accompanying error message for details.
public static var badRequestException: Self { .init(.badRequestException) }
/// The request configuration has conflicts. For details, see the accompanying error message.
public static var conflictException: Self { .init(.conflictException) }
/// The request exceeded the rate limit. Retry after the specified time period.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The requested resource is not found. Make sure that the request URI is correct.
public static var notFoundException: Self { .init(.notFoundException) }
/// The requested service is not available. For details see the accompanying error message. Retry after the specified time period.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// The request has reached its throttling limit. Retry after the specified time period.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
/// The request is denied because the caller has insufficient permissions.
public static var unauthorizedException: Self { .init(.unauthorizedException) }
}
extension APIGatewayErrorType: Equatable {
public static func == (lhs: APIGatewayErrorType, rhs: APIGatewayErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension APIGatewayErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 43.276316 | 142 | 0.692004 |
231cb05f3d3ff64de7cc23b032d4a5c75996a032 | 406 | @testable import App
import XCTest
import XCTVapor
class AbstractTestCase: XCTestCase {
// swiftlint:disable:next test_case_accessibility
var app: Application!
override func setUpWithError() throws {
try super.setUpWithError()
app = Application(.testing)
try configure(app)
}
override func tearDown() {
super.tearDown()
app.shutdown()
}
}
| 20.3 | 53 | 0.660099 |
118152bce7809c37adc66cd7d2be3a7b73f5eb39 | 3,617 | //
// FeatureRepository.swift
// SwiftExampleApp
//
// Copyright (c) 2020 Alternative Payments Ltd
//
// 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
class FeatureRepository {
let features = [
FeatureViewModel(type: .payment,
title: "Pay with card",
subtitle: "by entering card details"),
FeatureViewModel(type: .preAuth,
title: "PreAuth with card",
subtitle: "by entering card details"),
FeatureViewModel(type: .registerCard,
title: "Register card",
subtitle: "to be stored for future transactions"),
FeatureViewModel(type: .checkCard,
title: "Check card",
subtitle: "to validate card"),
FeatureViewModel(type: .saveCard,
title: "Save card",
subtitle: "to be stored for future transactions"),
FeatureViewModel(type: .applePay,
title: "Apple Pay payment",
subtitle: "with a wallet card"),
FeatureViewModel(type: .applePreAuth,
title: "Apple Pay preAuth",
subtitle: "with a wallet card"),
FeatureViewModel(type: .applePayButtons,
title: "Standalone Apple Pay buttons",
subtitle: "with supported button types and styles"),
FeatureViewModel(type: .paymentMethods,
title: "Payment methods",
subtitle: "with default payment methods"),
FeatureViewModel(type: .preAuthMethods,
title: "PreAuth methods",
subtitle: "with default pre-auth methods"),
FeatureViewModel(type: .serverToServer,
title: "Server-to-Server payment methods",
subtitle: "with default server-to-server payment methods"),
FeatureViewModel(type: .payByBank,
title: "Pay By Bank App",
subtitle: "by using your existing Bank app"),
FeatureViewModel(type: .tokenPayments,
title: "Token payments",
subtitle: "by using your stored card token"),
FeatureViewModel(type: .transactionDetails,
title: "Get transaction details",
subtitle: "by using your receipt ID")
]
}
| 41.102273 | 84 | 0.587227 |
8acecff67af15c59eb5d488ba53369e06e7b434d | 2,839 | extension WebAppLocalServer {
func simulatePageReload(_ command: CDVInvokedUrlCommand) {
onReset()
let result = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate?.send(result, callbackId:command.callbackId)
}
func simulateAppRestart(_ command: CDVInvokedUrlCommand) {
initializeAssetBundles()
onReset()
let result = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate?.send(result, callbackId:command.callbackId)
}
func resetToInitialState(_ command: CDVInvokedUrlCommand) {
commandDelegate?.run() {
self.configuration.reset()
self.initializeAssetBundles()
self.onReset()
let result = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate?.send(result, callbackId:command.callbackId)
}
}
func getAuthTokenKeyValuePair(_ command: CDVInvokedUrlCommand) {
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: authTokenKeyValuePair)
commandDelegate?.send(result, callbackId:command.callbackId)
}
func downloadedVersionExists(_ command: CDVInvokedUrlCommand) {
guard let version = command.argument(at: 0) as? String else {
let errorMessage = "'version' argument required"
let result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorMessage)
commandDelegate?.send(result, callbackId: command.callbackId)
return
}
let versionExists = assetBundleManager.downloadedAssetBundleWithVersion(version) != nil
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: versionExists)
commandDelegate?.send(result, callbackId:command.callbackId)
}
func simulatePartialDownload(_ command: CDVInvokedUrlCommand) {
guard let version = command.argument(at: 0) as? String else {
let errorMessage = "'version' argument required"
let result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorMessage)
commandDelegate?.send(result, callbackId: command.callbackId)
return
}
commandDelegate?.run() {
let wwwDirectoryURL = Bundle.main.resourceURL!.appendingPathComponent("www")
let versionDirectoryURL = wwwDirectoryURL.appendingPathComponent("partially_downloaded_versions/\(version)")
let versionsDirectoryURL = self.assetBundleManager.versionsDirectoryURL
let downloadDirectoryURL = versionsDirectoryURL.appendingPathComponent("Downloading")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: downloadDirectoryURL.path) {
try! fileManager.removeItem(at: downloadDirectoryURL)
}
try! fileManager.copyItem(at: versionDirectoryURL, to: downloadDirectoryURL)
let result = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate?.send(result, callbackId:command.callbackId)
};
}
}
| 37.853333 | 114 | 0.753787 |
0a084a8c4e531a541b871b22c52d120702ca3c24 | 2,102 | //
// AppDelegate.swift
// RxS
//
// Created by Puthnith on 2018-10-27.
// Copyright © 2018 Puthnith. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 44.723404 | 281 | 0.776879 |
fe54c5ed54827a7d54d888e2967e8a64e434fa0a | 3,406 | import Foundation
class Exporter {
static func toText(_ foreground: Eyedropper, _ background: Eyedropper) -> String {
let colorWCAGCompliance = foreground.color.toWCAGCompliance(with: background.color)
let colorContrastRatio = foreground.color.toContrastRatioString(with: background.color)
let foregroundHex = foreground.color.toFormat(format: ColorFormat.hex)
let foregroundRgb = foreground.color.toFormat(format: ColorFormat.rgb)
let foregroundHsb = foreground.color.toFormat(format: ColorFormat.hsb)
let foregroundHsl = foreground.color.toFormat(format: ColorFormat.hsl)
let backgroundHex = background.color.toFormat(format: ColorFormat.hex)
let backgroundRgb = background.color.toFormat(format: ColorFormat.rgb)
let backgroundHsb = background.color.toFormat(format: ColorFormat.hsb)
let backgroundHsl = background.color.toFormat(format: ColorFormat.hsl)
let passMessage = NSLocalizedString("color.wcag.pass", comment: "Pass")
let failMessage = NSLocalizedString("color.wcag.fail", comment: "Fail")
// swiftlint:disable line_length
return """
\(NSLocalizedString("color.foreground", comment: "Foreground")): \(foregroundHex) · \(foregroundRgb) · \(foregroundHsb) · \(foregroundHsl)
\(NSLocalizedString("color.background", comment: "Background")): \(backgroundHex) · \(backgroundRgb) · \(backgroundHsb) · \(backgroundHsl)
\(NSLocalizedString("color.ratio", comment: "Contrast Ratio")): \(colorContrastRatio):1
\(NSLocalizedString("color.wcag", comment: "WCAG Compliance")): AA Large (\(colorWCAGCompliance.ratio30 ? passMessage : failMessage)) · AA / AAA Large (\(colorWCAGCompliance.ratio45 ? passMessage : failMessage)) · AAA (\(colorWCAGCompliance.ratio70 ? passMessage : failMessage)) · Non-text (\(colorWCAGCompliance.ratio30 ? passMessage : failMessage))
"""
// swiftlint:enable line_length
}
static func toJSON(_ foreground: Eyedropper, _ background: Eyedropper) -> String {
let colorWCAGCompliance = foreground.color.toWCAGCompliance(with: background.color)
let colorContrastRatio = foreground.color.toContrastRatioString(with: background.color)
return """
{
"colors": {
"foreground": {
"hex": "\(foreground.color.toFormat(format: ColorFormat.hex))",
"rgb": "\(foreground.color.toFormat(format: ColorFormat.rgb))",
"hsb": "\(foreground.color.toFormat(format: ColorFormat.hsb))",
"hsl": "\(foreground.color.toFormat(format: ColorFormat.hsl))",
"name": "\(foreground.getClosestColor())"
},
"background": {
"hex": "\(background.color.toFormat(format: ColorFormat.hex))",
"rgb": "\(background.color.toFormat(format: ColorFormat.rgb))",
"hsb": "\(background.color.toFormat(format: ColorFormat.hsb))",
"hsl": "\(background.color.toFormat(format: ColorFormat.hsl))",
"name": "\(background.getClosestColor())"
}
},
"ratio": "\(colorContrastRatio)",
"wcag": {
"ratio30": \(colorWCAGCompliance.ratio30),
"ratio45": \(colorWCAGCompliance.ratio45),
"ratio70": \(colorWCAGCompliance.ratio70)
}
}
"""
}
}
| 54.935484 | 358 | 0.649442 |
08402f28cf9b2972779d909689b9b75ab2a7c8a9 | 246 | //
// AdminDTO.swift
// CastrApp
//
// Created by Antoine on 28/11/2017.
// Copyright © 2017 Castr. All rights reserved.
//
import Foundation
struct AdminDTO {
var color: Int
var id: String
var name: String
var picture: String
}
| 13.666667 | 48 | 0.662602 |
892c4325311f89ae0de59c0271819eef628edf33 | 1,399 | //
// AppDelegate.swift
// TestingFramework
//
// Created by Nikita on 10/05/21.
//
import UIKit
@main
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
}
// MARK: UISceneSession Lifecycle
// func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// // Called when a new scene session is being created.
// // Use this method to select a configuration to create the new scene with.
// return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
// }
//
// func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// // Called when the user discards a scene session.
// // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
// }
}
| 35.871795 | 181 | 0.732666 |
f5ca381604c4c12da8d5e2b754e9d3bbc6000c10 | 1,207 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view showing the details for a landmark.
*/
import SwiftUI
struct LandmarkDetail: View {
var landMark: Landmark
var body: some View {
VStack {
MapView(coordinate: landMark.locationCoordinate)
.edgesIgnoringSafeArea(.top)
.frame(height: 300)
CircleImage(image: landMark.image(forSize: 250))
.offset(x: 0, y: -130)
.padding(.bottom, -130)
VStack(alignment: .leading) {
Text(landMark.name)
.font(.title)
HStack(alignment: .top) {
Text(landMark.park)
.font(.subheadline)
Spacer()
Text(landMark.state)
.font(.subheadline)
}
}
.padding()
Spacer()
}
.navigationBarTitle(Text(landMark.name), displayMode: .inline)
}
}
#if DEBUG
struct LandmarkDetail_Previews: PreviewProvider {
static var previews: some View {
LandmarkDetail(landMark: landmarkData[0])
}
}
#endif
| 24.632653 | 70 | 0.522784 |
ffafb2c7049c28a883b827f39a5a1e8fceaafbd0 | 257 | //
// CommentFormViewModel.swift
// Microblog
//
// Created by Victor on 27/08/2019.
// Copyright © 2019 Victor Nouvellet. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
struct CommentFormViewModel {
let post: PostModel
}
| 16.0625 | 59 | 0.731518 |
bfea007e033d1f6b722bfd9e8609a89c31462e3d | 2,190 | //
// AppDelegate.swift
// Demo12-UIScrollView
//
// Created by Prashant on 28/09/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.595745 | 285 | 0.756164 |
87e748da98211bf169f0b1732484967ec8ea04ec | 3,363 | //
// AddressActionsTests.swift
// falconTests
//
// Created by Juan Pablo Civile on 08/01/2019.
// Copyright © 2019 muun. All rights reserved.
//
import XCTest
import RxSwift
@testable import core
@testable import Muun
class AddressActionsTests: MuunTestCase {
override func setUp() {
super.setUp()
// TODO: Setup user private key and muun cosigning key
let keyRepository: KeysRepository = resolve()
let muunKey = WalletPublicKey.fromBase58("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", on: DerivationSchema.external.path)
let swapServerKey = WalletPublicKey.fromBase58("xpub6DE1bvvTaMkDaAghedChtufg3rDPeYdWt9sM5iTwBVYe9X6bmLenQrSexSa1qDscYtidSMUEo9u7TuXg48Y3hBXQr7Yw8zUaEToH1rVgvif", on: DerivationSchema.external.path)
let userKey = WalletPrivateKey.fromBase58("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", on: DerivationSchema.base.path)
keyRepository.store(cosigningKey: muunKey)
keyRepository.store(swapServerKey: swapServerKey)
try! keyRepository.store(key: userKey)
_ = try! keyRepository.getBasePrivateKey()
}
func testAfterSignUp() throws {
let fake = replace(.singleton, HoustonService.self, FakeHoustonService.init)
let addressActions: AddressActions = resolve()
let keyRepository: KeysRepository = resolve()
let syncExternalAddresses: SyncExternalAddresses = resolve()
// Mimic sign up
keyRepository.updateMaxUsedIndex(0)
keyRepository.updateMaxWatchingIndex(10)
_ = try addressActions.generateExternalAddresses()
wait(for: syncExternalAddresses.getValue())
XCTAssertEqual(keyRepository.getMaxUsedIndex(), 1)
XCTAssertEqual(keyRepository.getMaxWatchingIndex(), 11)
XCTAssertEqual(fake.updateCalls, 1)
}
func testRandomAddress() throws {
let fake = replace(.singleton, HoustonService.self, FakeHoustonService.init)
let addressActions: AddressActions = resolve()
let keyRepository: KeysRepository = resolve()
let syncExternalAddresses: SyncExternalAddresses = resolve()
// Mimic sign up
keyRepository.updateMaxUsedIndex(10)
keyRepository.updateMaxWatchingIndex(10)
_ = try addressActions.generateExternalAddresses()
expectTimeout(for: syncExternalAddresses.getValue())
XCTAssertEqual(keyRepository.getMaxUsedIndex(), 10)
XCTAssertEqual(keyRepository.getMaxWatchingIndex(), 10)
XCTAssertEqual(fake.updateCalls, 0)
}
}
fileprivate class FakeHoustonService: HoustonService {
var updateCalls = 0
override func update(externalAddressesRecord: ExternalAddressesRecord) -> Single<ExternalAddressesRecord> {
let maxIndex = max(externalAddressesRecord.maxUsedIndex, externalAddressesRecord.maxWatchingIndex ?? -1)
return Single.just(ExternalAddressesRecord(
maxUsedIndex: externalAddressesRecord.maxUsedIndex,
maxWatchingIndex: maxIndex + 10))
.do(onSubscribe: {
self.updateCalls += 1
})
}
}
| 37.786517 | 205 | 0.705323 |
bfb238fe35e808cb13f8f264e6827809336a2cc3 | 2,780 | //
// DracoonError.swift
// dracoon-sdk
//
// Copyright © 2018 Dracoon. All rights reserved.
//
import Foundation
public enum DracoonError: Error {
case api(error: ModelErrorResponse?)
case decode(error: Error)
case nodes(error: Error)
case shares(error: Error)
case account(error: Error)
case encrypted_share_no_password_provided
case read_data_failure(at: URL)
case node_path_invalid(path: String)
case path_range_invalid
case node_not_found(path: String)
case file_does_not_exist(at: URL)
case no_encryption_password
case filekey_not_found
case filekey_encryption_failure
case encryption_cipher_failure
case file_decryption_error(nodeId: Int64)
case keypair_failure(description: String)
case keypair_decryption_failure
case keypair_does_not_exist
case authorization_code_flow_in_progress(clientId: String, clientSecret: String, authorizationCode: String)
case authorization_token_expired
}
extension DracoonError {
public var errorDescription: String? {
switch self {
case .api(let error):
return error.debugDescription
case .account(let error):
return error.localizedDescription
case .nodes(error: let error):
return error.localizedDescription
case .no_encryption_password:
return "No encryption password set"
case .filekey_not_found:
return "File Key not found"
case .filekey_encryption_failure:
return "File Key could not be encrypted"
case .encryption_cipher_failure:
return "Encryption cipher could not be created"
case .keypair_does_not_exist:
return "User has no keypair"
case .authorization_code_flow_in_progress(_, _, _):
return "Code flow already in progress"
case .authorization_token_expired:
return "OAuth access token expired"
case .encrypted_share_no_password_provided:
return "No password provided for encrypted share"
case .read_data_failure(let at):
return "Failure at reading from \(at.path)"
case .node_path_invalid(let path):
return "Invalid node path \(path)"
case .path_range_invalid:
return "Invalid range path"
case .node_not_found(let path):
return "Node at \(path) not found"
case .file_does_not_exist(let at):
return "File at \(at) does not exist"
case .file_decryption_error(let nodeId):
return "Could not decrypt node with id \(nodeId)"
case .keypair_decryption_failure:
return "Could not decrypt key pair"
default:
return nil
}
}
}
| 33.902439 | 111 | 0.665468 |
907a62ce6f4b15b0193ef2afab862e54d62f5509 | 2,509 | //
// GithubOrgsFlowableFactory.swift
// Example
//
// Created by Kensuke Tamura on 2020/12/25.
//
import Foundation
import Combine
import StoreFlowable
struct GithubOrgsFlowableFactory: PaginationStoreFlowableFactory {
typealias PARAM = UnitHash
typealias DATA = [GithubOrg]
private static let EXPIRE_SECONDS = TimeInterval(60)
private static let PER_PAGE = 20
private let githubApi = GithubApi()
let flowableDataStateManager: FlowableDataStateManager<UnitHash> = GithubOrgsStateManager.shared
func loadDataFromCache(param: UnitHash) -> AnyPublisher<[GithubOrg]?, Never> {
Future { promise in
promise(.success(GithubInMemoryCache.orgsCache))
}.eraseToAnyPublisher()
}
func saveDataToCache(newData: [GithubOrg]?, param: UnitHash) -> AnyPublisher<Void, Never> {
Future { promise in
GithubInMemoryCache.orgsCache = newData
GithubInMemoryCache.orgsCacheCreatedAt = Date()
promise(.success(()))
}.eraseToAnyPublisher()
}
func saveNextDataToCache(cachedData: [GithubOrg], newData: [GithubOrg], param: UnitHash) -> AnyPublisher<Void, Never> {
Future { promise in
GithubInMemoryCache.orgsCache = cachedData + newData
promise(.success(()))
}.eraseToAnyPublisher()
}
func fetchDataFromOrigin(param: UnitHash) -> AnyPublisher<Fetched<[GithubOrg]>, Error> {
githubApi.getOrgs(since: nil, perPage: GithubOrgsFlowableFactory.PER_PAGE).map { data in
Fetched(
data: data,
nextKey: data.last?.id.description
)
}.eraseToAnyPublisher()
}
func fetchNextDataFromOrigin(nextKey: String, param: UnitHash) -> AnyPublisher<Fetched<[GithubOrg]>, Error> {
return githubApi.getOrgs(since: Int(nextKey), perPage: GithubOrgsFlowableFactory.PER_PAGE).map { data in
Fetched(
data: data,
nextKey: data.last?.id.description
)
}.eraseToAnyPublisher()
}
func needRefresh(cachedData: [GithubOrg], param: UnitHash) -> AnyPublisher<Bool, Never> {
Future { promise in
if let createdAt = GithubInMemoryCache.orgsCacheCreatedAt {
let expiredAt = createdAt + GithubOrgsFlowableFactory.EXPIRE_SECONDS
promise(.success(expiredAt < Date()))
} else {
promise(.success(true))
}
}.eraseToAnyPublisher()
}
}
| 34.369863 | 123 | 0.646074 |
3936d3fbdf274e81a312851010b185045ec0d229 | 929 | //
// SearchCityWeatherView.swift
// weather-app-ios-group-01
//
// Created by jack Maarek on 12/09/2021.
//
import SwiftUI
struct SearchCityWeatherView: View {
@State private var searchText: String
private var cityData: [City] = City.cityData
init(_: SearchCityViewModel = SearchCityViewModel()) {
searchText = ""
cityData = City.cityData
}
var body: some View {
VStack(alignment: .leading) {
SearchBar(text: $searchText)
List {
ForEach(self.cityData.filter {
self.searchText.isEmpty ? true : $0.name.lowercased().contains(self.searchText.lowercased())
}, id: \.self) { city in
NavigationLink(destination: DetailView(viewModel: SearchCityViewModel(city: city.name))) {
Text(city.name)
}
}
}
}
}
}
| 27.323529 | 112 | 0.556512 |
69f8faf3a8632a2773546002b4135b1b796ed9d4 | 3,635 | //
// TweetDetailView.swift
// Twitter
//
// Created by Arthur on 2017/2/28.
// Copyright © 2017年 Kuan-Ting Wu (Arthur Wu). All rights reserved.
//
import UIKit
class TweetDetailView: UIViewController
{
static var tweet: Tweet?
@IBOutlet var userName: UILabel!
@IBOutlet var tweetText: UILabel!
@IBOutlet var timeStamp: UILabel!
@IBOutlet var profilePic: UIImageView!
@IBOutlet var retweetCount: UILabel!
@IBOutlet var favorCount: UILabel!
@IBOutlet var retweetButton: UIButton!
@IBOutlet var favButton: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
userName.text = TweetDetailView.tweet!.userName
tweetText.text = TweetDetailView.tweet!.text
timeStamp.text = ("\(TweetDetailView.tweet!.timestamp!)")
profilePic.setImageWith(TweetDetailView.tweet!.profilePicUrl!)
retweetCount.text = ("\(TweetDetailView.tweet!.retweetCount)")
favorCount.text = ("\(TweetDetailView.tweet!.favoritesCount)")
if(TweetDetailView.tweet!.retweet! == true)
{
retweetButton.setImage(UIImage(named: "retweet-icon-green.png"), for: UIControlState.normal)
}
else
{
retweetButton.setImage(UIImage(named: "retweet-icon.png"), for: UIControlState.normal)
}
if(TweetDetailView.tweet!.fav! == true)
{
favButton.setImage(UIImage(named: "favor-icon-red.png"), for: UIControlState.normal)
}
else
{
favButton.setImage(UIImage(named: "favor-icon.png"), for: UIControlState.normal)
}
// Do any additional setup after loading the view.
}
@IBAction func retweet(_ sender: Any)
{
print("retweet")
TwitterClient.sharedInstance?.retweet(id: TweetDetailView.tweet!.id!)
retweetButton.setImage(UIImage(named: "retweet-icon-green.png"), for: UIControlState.normal)
var buffer = Int(retweetCount.text!)
TweetDetailView.tweet!.retweetCount = buffer! + 1
retweetCount.text! = "\(TweetDetailView.tweet!.retweetCount)"
TweetDetailView.tweet!.retweet = true;
}
@IBAction func fav(_ sender: Any)
{
TwitterClient.sharedInstance?.favorite(id: TweetDetailView.tweet!.id!)
favButton.setImage(UIImage(named: "favor-icon-red.png"), for: UIControlState.normal)
var buffer = Int(favorCount.text!)
TweetDetailView.tweet!.favoritesCount = buffer! + 1
favorCount.text! = "\(TweetDetailView.tweet!.favoritesCount)"
TweetDetailView.tweet!.fav = true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
let cell = sender as! UIButton
let descriptionView = segue.destination as! ReplyPageViewController;
descriptionView.tweet = TweetDetailView.tweet;
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.747748 | 106 | 0.641541 |
e95c538ad45f980c1f88e3da718cd3c0e7019b64 | 1,253 | /*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* To use GooglePlacePickerDemos, please register an API Key for your application and set it here.
* Your API Key should be kept private.
*
* See documentation on getting an API Key for your API Project here:
* https://developers.google.com/places/ios-sdk/start#get-key
*/
// Register your API keys and insert here. Likely these two keys will be the same for your project,
// provided that it has both the GoogleMaps SDK for iOS and the Places API for iOS enabled in the
// developer console. If you do have separate keys for the two APIs you can provide these here.
internal let kPlacesAPIKey = ""
internal let kMapsAPIKey = ""
| 43.206897 | 99 | 0.747805 |
d5c8108c583edfbb75ed8f70e83e86fc4b6228f5 | 3,303 | //
// CornerDesignableTests.swift
// IBAnimatable
//
// Created by Steven on 5/12/17.
// Copyright © 2017 IBAnimatable. All rights reserved.
//
import XCTest
@testable import IBAnimatable
// MARK: - CornerDesignableTests Protocol
protocol CornerDesignableTests: class {
associatedtype Element
var element: Element { get set }
func testCornerRadius()
func test_cornerSides()
}
// MARK: - Universal Tests
extension CornerDesignableTests where Element: StringCornerDesignable {
func _test_cornerSides() {
element._cornerSides = "topLeft"
XCTAssertEqual(element.cornerSides, .topLeft)
element._cornerSides = "topRight"
XCTAssertEqual(element.cornerSides, .topRight)
element._cornerSides = "bottomLeft"
XCTAssertEqual(element.cornerSides, .bottomLeft)
element._cornerSides = "bottomRight"
XCTAssertEqual(element.cornerSides, .bottomRight)
element._cornerSides = "allSides"
XCTAssertEqual(element.cornerSides, .allSides)
element._cornerSides = ""
XCTAssertEqual(element.cornerSides, .allSides)
}
}
// MARK: - UIView Tests
extension CornerDesignableTests where Element: UIView, Element: CornerDesignable {
func _testCornerRadius() {
element.cornerRadius = 3
element.cornerSides = .allSides
testRadiusPath(for: .allCorners)
element.cornerSides = [.bottomLeft, .bottomRight, .topLeft]
testRadiusPath(for: [.bottomLeft, .bottomRight, .topLeft])
}
private func testRadiusPath(for sides: UIRectCorner) {
let mask = element.layer.mask as? CAShapeLayer
if sides == .allCorners {
XCTAssertNil(mask)
} else {
XCTAssertEqual(mask?.frame, CGRect(origin: .zero, size: element.bounds.size))
XCTAssertEqual(mask?.name, "cornerSideLayer")
let cornerRadii = CGSize(width: element.cornerRadius, height: element.cornerRadius)
let corners: UIRectCorner = sides
let mockPath = UIBezierPath(roundedRect: element.bounds, byRoundingCorners: corners, cornerRadii: cornerRadii).cgPath
XCTAssertEqual(mask?.path, mockPath)
}
}
}
// MARK: - UICollectionViewCell Tests
extension CornerDesignableTests where Element: UICollectionViewCell, Element: CornerDesignable {
func _testCornerRadius() {
element.cornerRadius = -1
XCTAssertFalse(element.contentView.layer.masksToBounds)
element.cornerRadius = 3.0
XCTAssertNil(element.layer.mask)
XCTAssertEqual(element.layer.cornerRadius, 0.0)
element.cornerSides = .allSides
testRadiusPath(for: .allCorners)
element.cornerSides = [.bottomLeft, .bottomRight, .topLeft]
testRadiusPath(for: [.bottomLeft, .bottomRight, .topLeft])
}
private func testRadiusPath(for sides: UIRectCorner) {
let mask = element.contentView.layer.mask as? CAShapeLayer
if sides == .allCorners {
XCTAssertNil(mask)
} else {
XCTAssertEqual(mask?.frame, CGRect(origin: .zero, size: element.contentView.bounds.size))
XCTAssertEqual(mask?.name, "cornerSideLayer")
let cornerRadii = CGSize(width: element.cornerRadius, height: element.cornerRadius)
let corners: UIRectCorner = sides
let mockPath = UIBezierPath(roundedRect: element.contentView.bounds, byRoundingCorners: corners, cornerRadii: cornerRadii).cgPath
XCTAssertEqual(mask?.path, mockPath)
}
}
}
| 31.160377 | 135 | 0.732667 |
281a74bf0be8dbf1bfcad4866dc4c1e429cdbcd7 | 3,166 | import UIKit
import HaishinKit
import SRTHaishinKit
import AVFoundation
final class LiveViewController: UIViewController {
private static let maxRetryCount: Int = 5
@IBOutlet private weak var lfView: MTHKView!
@IBOutlet private weak var currentFPSLabel: UILabel!
@IBOutlet private weak var publishButton: UIButton!
@IBOutlet private weak var pauseButton: UIButton!
@IBOutlet private weak var videoBitrateLabel: UILabel!
@IBOutlet private weak var videoBitrateSlider: UISlider!
@IBOutlet private weak var audioBitrateLabel: UILabel!
@IBOutlet private weak var zoomSlider: UISlider!
@IBOutlet private weak var audioBitrateSlider: UISlider!
@IBOutlet private weak var fpsControl: UISegmentedControl!
@IBOutlet private weak var effectSegmentControl: UISegmentedControl!
private var connection: SRTConnection!
private var stream: SRTStream!
private var currentPosition: AVCaptureDevice.Position = .back
override func viewDidLoad() {
super.viewDidLoad()
connection = .init()
stream = SRTStream(connection)
stream.captureSettings = [
.sessionPreset: AVCaptureSession.Preset.hd1280x720,
.continuousAutofocus: true,
.continuousExposure: true
]
stream.videoSettings = [
.width: 720,
.height: 1280
]
connection.attachStream(stream)
lfView.attachStream(stream)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
stream.attachAudio(AVCaptureDevice.default(for: .audio)) { _ in
// logger.warn(error.description)
}
stream.attachCamera(DeviceUtil.device(withPosition: currentPosition)) { _ in
// logger.warn(error.description)
}
}
@IBAction func rotateCamera(_ sender: UIButton) {
}
@IBAction func toggleTorch(_ sender: UIButton) {
}
@IBAction func on(slider: UISlider) {
}
@IBAction func on(pause: UIButton) {
}
@IBAction func on(close: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func on(publish: UIButton) {
if publish.isSelected {
UIApplication.shared.isIdleTimerDisabled = false
stream.close()
connection.close()
publish.setTitle("●", for: [])
} else {
UIApplication.shared.isIdleTimerDisabled = true
((try? connection.connect(URL(string: Preference.shared.url))) as ()??)
stream.publish(Preference.shared.streamName)
publish.setTitle("■", for: [])
}
publish.isSelected.toggle()
}
func tapScreen(_ gesture: UIGestureRecognizer) {
}
@IBAction private func onFPSValueChanged(_ segment: UISegmentedControl) {
}
@IBAction private func onEffectValueChanged(_ segment: UISegmentedControl) {
}
@objc
private func on(_ notification: Notification) {
}
@objc
private func didEnterBackground(_ notification: Notification) {
}
@objc
private func didBecomeActive(_ notification: Notification) {
}
}
| 30.152381 | 84 | 0.660455 |
4846f701f09a9c39f3df2e4574f3bbe9ce451f91 | 2,752 | //
// File.swift
//
//
// Created by GoEun Jeong on 2021/08/25.
//
// https://swiftwithmajid.com/2019/12/25/building-pager-view-in-swiftui/
//
import SwiftUI
#if os(iOS) || os(OSX)
/// SwiftUI view that displays contained children in pages, like a `UIPageViewController` in UIKit.
///
/// Parameters to initialize:
/// - pageCount: number of pages.
/// - currentIndex: binding fo current page.
/// - pageChanged: block to be called whenever a new page is displayed.
/// - content: `@ViewBuilder` block to generate all children pages.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
struct PagerView<Content: View>: View {
let pageCount: Int
@Binding var currentIndex: Int
let content: Content
@GestureState private var translation: CGFloat = 0
var pageChanged: ((Int) -> ())? = nil
/// Creates a new `PagerView` to display paginated, scrolling views.
/// - Parameters:
/// - pageCount: number of pages.
/// - currentIndex: binding fo current page.
/// - pageChanged: block to be called whenever a new page is displayed.
/// - content: `@ViewBuilder` block to generate all children pages.
init(pageCount: Int, currentIndex: Binding<Int>, pageChanged: ((Int) -> ())? = nil, @ViewBuilder content: () -> Content) {
self.pageCount = pageCount
self._currentIndex = currentIndex
self.pageChanged = pageChanged
self.content = content()
}
var body: some View {
GeometryReader { geometry in
HStack(alignment: .top , spacing: 0) {
self.content.frame(width: geometry.size.width
,height: geometry.size.height, alignment: .top)
}
.frame(width: geometry.size.width, alignment: .leading)
.offset(x: -CGFloat(self.currentIndex) * geometry.size.width)
.offset(x: self.translation)
.animation(.interactiveSpring())
.gesture(
DragGesture().updating(self.$translation) { value, state, _ in
state = value.translation.width
}.onEnded { value in
let offset = value.translation.width / geometry.size.width
let newIndex = (CGFloat(self.currentIndex) - offset).rounded()
let oldIndex = self.currentIndex
self.currentIndex = min(max(Int(newIndex), 0), self.pageCount - 1)
if oldIndex != self.currentIndex, let pageChanged = self.pageChanged {
pageChanged(self.currentIndex)
}
}
)
}
}
}
#endif
| 36.693333 | 126 | 0.574855 |
1ee9a7218863907a582ec94cbf8b048362a11a5a | 3,597 | //
// SettingsViewController.swift
// code_path
//
// Created by Jonah Tjandra on 11/14/21.
//
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
class SettingsViewController: UIViewController {
@IBOutlet weak var tip1Edit: UITextField!
@IBOutlet weak var tip2Edit: UITextField!
@IBOutlet weak var tip3Edit: UITextField!
@IBOutlet weak var titleSetting: UILabel!
@IBOutlet weak var tip1Label: UILabel!
@IBOutlet weak var tip2Label: UILabel!
@IBOutlet weak var tip3Label: UILabel!
@IBOutlet weak var darkModeLabel: UILabel!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var darkModeButton: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tip1Edit.keyboardType = UIKeyboardType.decimalPad;
tip2Edit.keyboardType = UIKeyboardType.decimalPad;
tip3Edit.keyboardType = UIKeyboardType.decimalPad;
self.hideKeyboardWhenTappedAround();
}
override func viewWillAppear(_ animated: Bool) {
tip1Edit.becomeFirstResponder();
if (UserDefaults.standard.integer(forKey: "dark") == 1) {
darkModeButton.setOn(true, animated: false)
setThemeLight();
} else {
darkModeButton.setOn(false, animated: false)
setThemeDark();
}
}
func setThemeDark() {
self.view.backgroundColor = UIColor.white;
titleSetting.textColor = UIColor.black;
tip1Label.textColor = UIColor.black;
tip2Label.textColor = UIColor.black;
tip3Label.textColor = UIColor.black;
darkModeLabel.textColor = UIColor.black;
saveButton.tintColor = UIColor.black;
}
func setThemeLight() {
self.view.backgroundColor = UIColor(red:0.15, green:0.15, blue:0.15, alpha:1);
titleSetting.textColor = UIColor.white;
tip1Label.textColor = UIColor.white;
tip2Label.textColor = UIColor.white;
tip3Label.textColor = UIColor.white;
darkModeLabel.textColor = UIColor.white;
saveButton.tintColor = UIColor.white;
}
@IBAction func saveClicked(_ sender: Any) {
let defaults = UserDefaults.standard;
defaults.set(tip1Edit.text!, forKey: "tip1");
defaults.set(tip2Edit.text!, forKey: "tip2");
defaults.set(tip3Edit.text!, forKey: "tip3");
defaults.synchronize();
tip1Edit.text = "";
tip2Edit.text = "";
tip3Edit.text = "";
}
@IBAction func toggleDarkMode(_ sender: UISwitch) {
let defaults = UserDefaults.standard;
if (sender.isOn == true) {
defaults.set(1, forKey: "dark");
setThemeLight();
} else {
defaults.set(0, forKey: "dark");
setThemeDark();
}
}
/*
// 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.
}
*/
}
| 30.483051 | 131 | 0.633584 |
f54119e1634824995a69e5b4bd7f79bb86ce9917 | 1,658 | import Foundation
import UIKit
open class CustomSegmentControl:UISegmentedControl {
public var textColor:UIColor = UIColor.black
public var textSelectedColor:UIColor = UIColor.black
public var textSize: CGFloat = 14.0
}
public extension CustomSegmentControl {
@IBInspectable
var segTextColor: UIColor{
get {
return self.textColor
}
set {
self.textColor = newValue
let unselectedAttributes = [NSAttributedString.Key.foregroundColor: self.textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.textSize)]
self.setTitleTextAttributes(unselectedAttributes, for: .normal)
}
}
@IBInspectable
var segSelectedTextColor: UIColor{
get {
return self.textSelectedColor
}
set {
self.textSelectedColor = newValue
let unselectedAttributes = [NSAttributedString.Key.foregroundColor: self.textSelectedColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.textSize)]
self.setTitleTextAttributes(unselectedAttributes, for: .selected)
}
}
@IBInspectable
var segTextSize: CGFloat {
get {
return self.textSize
}
set {
self.textSize = newValue
let unselectedAttributes = [NSAttributedString.Key.foregroundColor: self.textColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.textSize)]
self.setTitleTextAttributes(unselectedAttributes, for: .normal)
self.setTitleTextAttributes(unselectedAttributes, for: .selected)
}
}
}
| 33.836735 | 174 | 0.667672 |
21c2d5c15f84ca0d9fb6de74dbf6cbabde4f2ecb | 2,184 | //
// AppDelegate.swift
// SHToggleButton
//
// Created by Soufian Hossam on 9/18/18.
// Copyright © 2018 Soufian Hossam. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.468085 | 285 | 0.755952 |
ed6b1679cb53c137a1f049fe1f1447d0d99b5d5b | 12,777 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testMembersPostfix1 | %FileCheck %s -check-prefix=testMembersPostfix1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testMembersDot1 | %FileCheck %s -check-prefix=testMembersDot1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testMembersDot2 | %FileCheck %s -check-prefix=testMembersDot2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testMultipleSubscript1 | %FileCheck %s -check-prefix=testMultipleSubscript1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testInherit1 | %FileCheck %s -check-prefix=testInherit1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testInherit2 | %FileCheck %s -check-prefix=testInherit2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testShadow1 | %FileCheck %s -check-prefix=testShadow1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testGeneric1 | %FileCheck %s -check-prefix=testGeneric1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testGenericUnderconstrained1 | %FileCheck %s -check-prefix=testGenericUnderconstrained1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testExistential1 | %FileCheck %s -check-prefix=testGenericUnderconstrained1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testExistential2 | %FileCheck %s -check-prefix=testExistential2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testProtocolConform1 | %FileCheck %s -check-prefix=testProtocolConform1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OnSelf1 | %FileCheck %s -check-prefix=OnSelf1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testSelfExtension1 | %FileCheck %s -check-prefix=testSelfExtension1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testInvalid1 | %FileCheck %s -check-prefix=testInvalid1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testInvalid2 | %FileCheck %s -check-prefix=testInvalid2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testInvalid3 | %FileCheck %s -check-prefix=testInvalid3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testInvalid4 | %FileCheck %s -check-prefix=testInvalid4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testGenericRoot1 | %FileCheck %s -check-prefix=testGenericRoot1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testAnyObjectRoot1 | %FileCheck %s -check-prefix=testAnyObjectRoot1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testNested1 | %FileCheck %s -check-prefix=testNested1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testNested2 | %FileCheck %s -check-prefix=testNested2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testCycle1 | %FileCheck %s -check-prefix=testCycle1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=testCycle2 | %FileCheck %s -check-prefix=testCycle2
struct Point {
var x: Int
var y: Int
}
struct Rectangle {
var topLeft: Point
var bottomRight: Point
}
@dynamicMemberLookup
struct Lens<T> {
var obj: T
init(_ obj: T) { self.obj = obj }
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
set { obj[keyPath: member] = newValue.obj }
}
}
func testMembersPostfix1(r: Lens<Rectangle>) {
r#^testMembersPostfix1^#
}
// testMembersPostfix1: Begin completions
// testMembersPostfix1-DAG: Decl[Subscript]/CurrNominal: [{#dynamicMember: WritableKeyPath<Rectangle, U>#}][#Lens<U>#];
// FIXME: the type should be Lens<Point>
// testMembersPostfix1-DAG: Decl[InstanceVar]/CurrNominal: .topLeft[#Point#];
// testMembersPostfix1-DAG: Decl[InstanceVar]/CurrNominal: .bottomRight[#Point#];
// testMembersPostfix1: End completions
func testMembersDot1(r: Lens<Rectangle>) {
r.#^testMembersDot1^#
}
// testMembersDot1: Begin completions
// FIXME: the type should be Lens<Point>
// testMembersDot1-DAG: Decl[InstanceVar]/CurrNominal: topLeft[#Point#];
// testMembersDot1-DAG: Decl[InstanceVar]/CurrNominal: bottomRight[#Point#];
// testMembersDot1: End completions
func testMembersDot2(r: Lens<Rectangle>) {
r.topLeft.#^testMembersDot2^#
}
// testMembersDot2: Begin completions
// FIXME: the type should be Lens<Int>
// testMembersDot2-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testMembersDot2-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testMembersDot2: End completions
@dynamicMemberLookup
struct MultipleSubscript {
subscript<U>(dynamicMember member: KeyPath<Point, U>) -> U {
return Point(x: 1, y: 2)[keyPath: member]
}
subscript<U>(dynamicMember member: KeyPath<Rectangle, U>) -> U {
return Rectangle(topLeft: Point(x: 0, y: 0), bottomRight: Point(x: 1, y: 1))[keyPath: member]
}
}
func testMultipleSubscript1(r: MultipleSubscript) {
r.#^testMultipleSubscript1^#
}
// testMultipleSubscript1: Begin completions
// testMultipleSubscript1-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testMultipleSubscript1-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testMultipleSubscript1-DAG: Decl[InstanceVar]/CurrNominal: topLeft[#Point#];
// testMultipleSubscript1-DAG: Decl[InstanceVar]/CurrNominal: bottomRight[#Point#];
// testMultipleSubscript1: End completions
@dynamicMemberLookup
class Base<T> {
var t: T
init(_ t: T) { self.t = t }
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
return t[keyPath: member]
}
}
class Inherit1<T>: Base<T> {}
func testInherit1(r: Inherit1<Point>) {
r.#^testInherit1^#
}
// testInherit1: Begin completions
// testInherit1-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testInherit1-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testInherit1: End completions
class Inherit2<T, U>: Base<T> {
var u: U
init(_ t: T, _ u: U) { super.init(t); self.u = u }
subscript<V>(dynamicMember member: KeyPath<U, V>) -> V {
return u[keyPath: member]
}
}
func testInherit2(r: Inherit2<Point, Rectangle>) {
r.#^testInherit2^#
}
// testInherit2: Begin completions
// testInherit2-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testInherit2-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testInherit2-DAG: Decl[InstanceVar]/CurrNominal: topLeft[#Point#];
// testInherit2-DAG: Decl[InstanceVar]/CurrNominal: bottomRight[#Point#];
// testInherit2: End completions
class Shadow1<T>: Base<T> {
var x: String = ""
}
func testShadow1(r: Shadow1<Point>) {
r.#^testShadow1^#
}
// testShadow1-NOT: x[#Int#];
// testShadow1: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testShadow1-NOT: x[#Int#];
// testShadow1: Decl[InstanceVar]/CurrNominal: x[#String#];
@dynamicMemberLookup
protocol P {
associatedtype T
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U
}
func testGeneric1<G: P>(r: G) where G.T == Point {
r.#^testGeneric1^#
}
// testGeneric1: Begin completions
// testGeneric1-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testGeneric1-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testGeneric1: End completions
func testGenericUnderconstrained1<G: P>(r: G) {
r.#^testGenericUnderconstrained1^#
}
// testGenericUnderconstrained1-NOT: CurrNominal
// testGenericUnderconstrained1: Keyword[self]/CurrNominal: self[#{{[GP]}}#];
// testGenericUnderconstrained1-NOT: CurrNominal
func testExistential1(r: P) {
r.#^testExistential1^#
}
@dynamicMemberLookup
protocol E {
subscript<U>(dynamicMember member: KeyPath<Point, U>) -> U
}
func testExistential2(r: E) {
r.#^testExistential2^#
}
// testExistential2: Begin completions
// testExistential2-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testExistential2-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testExistential2: End completions
struct WithP<T>: P {
var t: T
init(t: T) { self.t = t }
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
return t[keyPath: member]
}
}
func testProtocolConform1(r: WithP<Point>) {
r.#^testProtocolConform1^#
}
// testProtocolConform1: Begin completions
// testProtocolConform1-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testProtocolConform1-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testProtocolConform1: End completions
@dynamicMemberLookup
struct OnSelf {
subscript<U>(dynamicMember member: KeyPath<Point, U>) -> U {
return Point(x: 0, y: 1)[keyPath: member]
}
func test() {
self.#^OnSelf1^#
}
}
// OnSelf1: Begin completions
// OnSelf1-DAG: Decl[InstanceMethod]/CurrNominal: test()[#Void#];
// OnSelf1-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// OnSelf1-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// OnSelf1: End completions
protocol HalfRect {
var topLeft: Point
}
extension Lens where T: HalfRect {
func testSelfExtension1() {
self.#^testSelfExtension1^#
}
}
// testSelfExtension1-NOT: bottomRight
// testSelfExtension1: Decl[InstanceVar]/CurrNominal: topLeft[#Point#];
// testSelfExtension1-NOT: bottomRight
struct Invalid1 {
subscript<U>(dynamicMember member: KeyPath<Rectangle, U>) -> U {
return Point(x: 0, y: 1)[keyPath: member]
}
}
func testInvalid1(r: Invalid1) {
r.#^testInvalid1^#
}
// testInvalid1-NOT: topLeft
@dynamicMemberLookup
struct Invalid2 {
subscript<U>(dynamicMember: KeyPath<Rectangle, U>) -> U {
return Point(x: 0, y: 1)[keyPath: dynamicMember]
}
}
func testInvalid2(r: Invalid2) {
r.#^testInvalid2^#
}
// testInvalid2-NOT: topLeft
@dynamicMemberLookup
struct Invalid3 {
subscript<U>(dynamicMember member: Rectangle) -> U {
return Point(x: 0, y: 1)[keyPath: member]
}
}
func testInvalid3(r: Invalid3) {
r.#^testInvalid3^#
}
// testInvalid3-NOT: topLeft
struct NotKeyPath<T, U> {}
@dynamicMemberLookup
struct Invalid4 {
subscript<U>(dynamicMember member: NotKeyPath<Rectangle, U>) -> U {
return Point(x: 0, y: 1)[keyPath: member]
}
}
func testInvalid4(r: Invalid4) {
r.#^testInvalid4^#
}
// testInvalid4-NOT: topLeft
struct Gen1<T> {
var foo: T
}
@dynamicMemberLookup
struct GenericRoot<T> {
subscript<U>(dynamicMember member: KeyPath<Gen1<T>, U>) -> Int {
return 1
}
}
func testGenericRoot1(r: GenericRoot<Point>) {
r.#^testGenericRoot1^#
}
// FIXME: Type should be substituted to Int.
// testGenericRoot1: Decl[InstanceVar]/CurrNominal: foo[#T#];
class C {
var someUniqueName: Int = 0
}
@dynamicMemberLookup
struct AnyObjectRoot {
subscript<U>(dynamicMember member: KeyPath<AnyObject, U>) -> Int {
return 1
}
}
func testAnyObjectRoot1(r: AnyObjectRoot) {
r.#^testAnyObjectRoot1^#
}
// Do not do find via AnyObject dynamic lookup.
// testAnyObjectRoot1-NOT: someUniqueName
func testNested1(r: Lens<Lens<Point>>) {
r.#^testNested1^#
// testNested1: Begin completions
// testNested1-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testNested1-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testNested1: End completions
}
func testNested2(r: Lens<Lens<Lens<Point>>>) {
r.#^testNested2^#
// testNested2: Begin completions
// testNested2-DAG: Decl[InstanceVar]/CurrNominal: x[#Int#];
// testNested2-DAG: Decl[InstanceVar]/CurrNominal: y[#Int#];
// testNested2: End completions
}
@dynamicMemberLookup
struct Recurse<T> {
var obj: T
init(_ obj: T) { self.obj = obj }
subscript<U>(dynamicMember member: KeyPath<Recurse<T>, U>) -> Int {
return 1
}
}
func testCycle1(r: Recurse<Point>) {
r.#^testCycle1^#
// testCycle1: Begin completions
// testCycle1-NOT: x[#Int#]
}
@dynamicMemberLookup
struct CycleA<T> {
var fromA: Int
subscript<U>(dynamicMember member: KeyPath<CycleB<T>, U>) -> Int {
return 1
}
}
@dynamicMemberLookup
struct CycleB<T> {
var fromB: Int
subscript<U>(dynamicMember member: KeyPath<CycleC<T>, U>) -> Int {
return 1
}
}
@dynamicMemberLookup
struct CycleC<T> {
var fromC: Int
subscript<U>(dynamicMember member: KeyPath<CycleA<T>, U>) -> Int {
return 1
}
}
func testCycle2(r: CycleA<Point>) {
r.#^testCycle2^#
// testCycle2: Begin completions
}
| 34.532432 | 178 | 0.718322 |
4aa278299b2d726af177d78c0c36b27a98e6c6f3 | 1,400 | //
// Step.swift
// DemoApp
//
// Created by rakshitha on 13/10/18.
// Copyright © 2018 rakshitha. All rights reserved.
//
import Foundation
import CoreLocation
struct Step {
var distance: String = ""
var duration: String = ""
var endLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
var locationName: String = ""
func intermediateRouteInfo(_ leg: [String: Any]) -> [Step] {
var steps = [Step] ()
for step in leg[ApiResponseConstant.steps] as? [[String: Any]] ?? [[ :]] {
if let location = step[ApiResponseConstant.end_location] as? [String: Any], let distance = step[ApiResponseConstant.distance] as? [String: Any], let duration = step[ApiResponseConstant.duration] as? [String: Any], let name = step[ApiResponseConstant.html_instructions] as? String {
if let lat = location[ApiResponseConstant.lat] as? CLLocationDegrees, let lng = location[ApiResponseConstant.lng] as? CLLocationDegrees, let distanceText = distance[ApiResponseConstant.text] as? String, let durationText = duration[ApiResponseConstant.text] as? String {
steps.append(Step(distance: distanceText, duration: durationText, endLocation: CLLocationCoordinate2D(latitude: lat, longitude: lng), locationName: ((name).html2String)))
}
}
}
return steps
}
}
| 46.666667 | 293 | 0.677857 |
29c97c091e85ccf9b63c49d532acaeb5a0925117 | 2,205 |
// This is a version based on a simpler version created for the C language:
// https://github.com/eatonphil/referenceserver/blob/master/c/server.c
import Glibc
let fd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
if fd == -1 {
print("Error: could not start the socket.")
}
defer {
close(fd)
}
var addressName = "127.0.0.1"
var address = sockaddr_in()
address.sin_family = UInt16(AF_INET)
address.sin_addr.s_addr = inet_addr(addressName)
var portNumber: UInt16 = 9123
print("Trying to start server on \(addressName):\(portNumber)")
// Create our own version of the C function htons().
var reversePortNumber = withUnsafePointer(&portNumber) { (ptr) -> UInt16 in
var ap = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(ptr),
count: sizeofValue(portNumber))
var n: UInt16 = 0
withUnsafePointer(&n) { np in
var np = UnsafeMutableBufferPointer<UInt8>(
start: UnsafeMutablePointer<UInt8>(np), count: sizeofValue(n))
np[0] = ap[1]
np[1] = ap[0]
}
return n
}
address.sin_port = reversePortNumber
var addrlen = UInt32(sizeofValue(address))
let bindResult = withUnsafePointer(&address) { (ptr) -> Int32 in
return bind(fd, UnsafePointer<sockaddr>(ptr), addrlen)
}
if bindResult == -1 {
print("Error: Could not start the server. Port may already be in use by " +
"another process.")
exit(1)
}
var buffer = [UInt8](repeating: 0, count: 1024)
var clientAddr = sockaddr_in()
var clientAddrLen = UInt32(sizeofValue(clientAddr))
listen(fd, SOMAXCONN)
func process(cfd: Int32) {
defer {
close(cfd)
}
var buffer = [UInt8](repeating: 0, count: 1024)
recv(cfd, &buffer, 1024, 0)
write(cfd, "Hello World\n", 12)
}
signal(SIGCHLD, SIG_IGN)
while true {
var cfd = withUnsafePointer(&clientAddr) { (ptr) -> Int32 in
return accept(fd, UnsafeMutablePointer<sockaddr>(ptr), &clientAddrLen)
}
if cfd < 0 {
print("bug: \(cfd) errno: \(errno)")
// break
}
// Create the child process.
let pid = fork()
if pid < 0 {
print("Error: fork failed.")
exit(1)
}
if pid == 0 {
// This is the child process.
close(fd)
defer {
exit(0)
}
process(cfd: cfd)
} else {
close(cfd)
}
}
| 22.96875 | 77 | 0.666667 |
d545e0a47e3c4a2f2c07ea62c189a448b6f783c6 | 2,247 | @testable import Cocoapods
import XCTest
final class ThrowingScannerTests: XCTestCase {
func test___scanWhile() {
assertDoesntThrow {
let scanner = ThrowingScannerImpl(string: "xyz")
try scanner.scanWhile("x")
XCTAssertEqual(
scanner.remainingString(),
"yz"
)
}
}
func test___scanWhile___fails_if_remaining_string_doesnt_start_with_given_string() {
assertThrows {
let scanner = ThrowingScannerImpl(string: "xyz")
try scanner.scanWhile("y")
}
}
func test___scanPass_0() {
assertDoesntThrow {
let scanner = ThrowingScannerImpl(string: "xyz")
XCTAssertEqual(
try scanner.scanPass("y"),
"x"
)
XCTAssertEqual(
scanner.remainingString(),
"z"
)
}
}
func test___scanPass_1() {
assertDoesntThrow {
let scanner = ThrowingScannerImpl(string: "xyz")
XCTAssertEqual(
try scanner.scanPass("x"),
""
)
XCTAssertEqual(
scanner.remainingString(),
"yz"
)
}
}
func test___scanPass___fails_if_remaining_string_doesnt_contain_given_string() {
assertThrows {
let scanner = ThrowingScannerImpl(string: "xyz")
try scanner.scanPass("?")
}
}
func test___scanUntil() {
assertDoesntThrow {
let scanner = ThrowingScannerImpl(string: "xyz")
XCTAssertEqual(
try scanner.scanUntil("y"),
"x"
)
XCTAssertEqual(
scanner.remainingString(),
"yz"
)
}
}
func test___scanToEnd() {
assertDoesntThrow {
let scanner = ThrowingScannerImpl(string: "xyz")
try scanner.scanWhile("x")
XCTAssertEqual(
try scanner.scanToEnd(),
"yz"
)
}
}
}
| 25.247191 | 88 | 0.477081 |
8783e63bb95700ccca6cbe851cb41ac1ada0e9cd | 61 | //
// File.swift
// SharePlayExample
//
import Foundation
| 8.714286 | 20 | 0.672131 |
5d14730559f1934edb41c92a64a2961c4c5d2fcf | 2,034 | //
// Copyright 2011 - 2018 Schibsted Products & Technology AS.
// Licensed under the terms of the MIT license. See LICENSE in the project root.
//
import UIKit
class ResendViewController: IdentityUIViewController {
enum Action {
case changeIdentifier
}
var didRequestAction: ((Action) -> Void)?
@IBOutlet var header: Heading! {
didSet {
self.header.text = self.viewModel.header
}
}
@IBOutlet var code: NormalLabel! {
didSet {
self.code.font = self.theme.fonts.normal
self.code.text = self.viewModel.subtext
}
}
@IBOutlet var number: NormalLabel! {
didSet {
self.number.font = self.theme.fonts.normal
self.number.text = self.viewModel.identifier.normalizedString
}
}
@IBOutlet var edit: UIButton! {
didSet {
let string = NSAttributedString(string: self.viewModel.editText, attributes: self.theme.textAttributes.textButton)
self.edit.setAttributedTitle(string, for: .normal)
}
}
@IBOutlet var ok: PrimaryButton! {
didSet {
self.ok.setTitle(self.viewModel.proceed, for: .normal)
}
}
@IBOutlet var stackBackground: UIView!
let viewModel: ResendViewModel
init(configuration: IdentityUIConfiguration, viewModel: ResendViewModel) {
self.viewModel = viewModel
super.init(configuration: configuration, navigationSettings: NavigationSettings(), trackerViewID: .passwordlessResend)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.stackBackground.layer.cornerRadius = self.theme.geometry.cornerRadius
}
@IBAction func didClickContinue(_: Any) {
self.dismiss(animated: true)
}
@IBAction func didClickEdit(_: Any) {
self.dismiss(animated: true)
self.didRequestAction?(.changeIdentifier)
}
}
| 29.057143 | 126 | 0.642576 |
e2e0e5360641d6b99f0990401654abb535e86bd1 | 1,094 | /**
* Copyright IBM Corporation 2018
*
* 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
/** Information about something that went wrong. */
public struct WarningInfo: Decodable {
/// Codified warning string, such as `limit_reached`.
public var warningID: String
/// Information about the error.
public var description: String
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case warningID = "warning_id"
case description = "description"
}
}
| 31.257143 | 82 | 0.721207 |
723ef7e4f3dafeb061121d32910de42a65a442e2 | 2,797 | //
// RealmStoreTests.swift
// GithubRepoExample
//
// Created by Javier Cancio on 18/1/17.
// Copyright © 2017 Javier Cancio. All rights reserved.
//
import Quick
import Nimble
import RxSwift
import RealmSwift
import RxTest
@testable import GithubRepoExample
class RealmStoreTests: QuickSpec {
override func spec() {
describe("A Realm DB Store") {
var disposableBag: DisposeBag!
beforeEach {
disposableBag = DisposeBag()
}
context("given repository object") {
var repository: Repository!
beforeEach {
repository = Repository()
repository.id = 1234
Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name
}
it("stores repository object on Realm") {
let store = RealmStore()
_ = store.save(repository: repository)
let realm = try! Realm()
expect(realm.objects(Repository.self).count).to(equal(1))
}
it("dont store the same repository twice") {
let realm = try! Realm()
let store = RealmStore()
store.save(repository: repository)
store.save(repository: repository)
expect(realm.objects(Repository.self).count).to(equal(1))
}
it("returns all stored repositories") {
let store = RealmStore()
let realm = try! Realm()
let sampleRepository = Repository()
sampleRepository.id = 1234
let anotherRepository = Repository()
anotherRepository.id = 5678
try! realm.write {
realm.add([sampleRepository, anotherRepository])
}
store
.load()
.subscribe(onNext: { repositories in
expect(repositories.count).to(equal(2))
})
.addDisposableTo(disposableBag)
}
it("updates stored repository with new data") {
let realm = try! Realm()
let store = RealmStore()
repository.name = "Foo"
store.save(repository: repository)
expect(realm.object(ofType: Repository.self, forPrimaryKey: repository.id)?.name).to(equal("Foo"))
let anotherRepository = Repository()
anotherRepository.id = repository.id // Same id as previous repository so it should be updated
anotherRepository.name = "Bar"
store.save(repository: anotherRepository)
expect(realm.object(ofType: Repository.self, forPrimaryKey: repository.id)?.name).to(equal("Bar"))
}
}
}
}
}
| 27.97 | 108 | 0.554523 |
9c9819753f5c9c927138b275a378b59e12594a30 | 234 | //
// SalesHistoryCoordinatorProtocol.swift
// WhyNFT
//
// Created by Антон Текутов on 12.06.2021.
//
protocol SalesHistoryCoordinatorProtocol: DefaultCoordinatorProtocol {
func openWorkDetailsEditor(artWork: ArtWork)
}
| 19.5 | 70 | 0.75641 |
d5e24ab605c0df35a316925b7e18805ab4b7b0b4 | 1,175 | //
// ZeusConfigurator.swift
// ApiOfIceAndFire
//
// Created by Cyon Alexander (Ext. Netlight) on 23/08/16.
// Copyright © 2016 com.cyon. All rights reserved.
//
import Foundation
import Zeus
private let baseUrl = "http://anapioficeandfire.com/api/"
class ZeusConfigurator {
var store: DataStoreProtocol!
var modelManager: ModelManagerProtocol!
init() {
setup()
}
fileprivate func setup() {
setupCoreDataStack()
setupLogging()
setupMapping()
}
fileprivate func setupLogging() {
Zeus.logLevel = .Warning
}
fileprivate func setupCoreDataStack() {
store = DataStore()
modelManager = ModelManager(baseUrl: baseUrl, store: store)
DataStore.sharedInstance = store
ModelManager.sharedInstance = modelManager
}
fileprivate func setupMapping() {
modelManager.map(Character.entityMapping(store), House.entityMapping(store)) {
character, house in
character == Router.characters
character == Router.characterById(nil)
house == Router.houses
house == Router.houseById(nil)
}
}
}
| 23.979592 | 86 | 0.635745 |
ccb347d959a18db16b3551e8b3d9b6a9b639d047 | 4,327 | //
// NotStringEquals.swift
// jsonlogicTests
//
// Created by Christos Koninis on 11/02/2019.
//
import XCTest
@testable import jsonlogic
class NotStrictEquals: XCTestCase {
func testNot_StrictEquals_withConstants() {
let rule =
"""
{ "!==" : [1, 2] }
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
}
func testNot_StrictEquals_withConstants1() {
let rule =
"""
{ "!==" : [1, "1"] }
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
}
func testNot_StrictEquals_withConstants2() {
let rule =
"""
{ "!==" : [1, 1] }
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
}
func testNot_StrictEquals_withConstants3() {
let rule =
"""
{ "!==" : [1, []] }
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
}
func testNotStringEquals_NestedVar() {
let rule =
"""
{ "!==" : [ {"var" : [ {"var" : ["a"]} ] }, {"var" : ["oneNest.one"]}] }
"""
let data =
"""
{ "a" : "b", "b" : "1", "oneNest" : {"one" : "1"} }
"""
XCTAssertEqual(false, try applyRule(rule, to: data))
}
func testLogicalNot_withBooleanConstants() {
var rule =
"""
{ "!" : [true] }
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
rule =
"""
{ "!" : [false] }
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
rule =
"""
{"!" : true}
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
rule =
"""
{"!" : false}
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
}
func testLogicalNot_withArrays() {
var rule =
"""
{"!" : []}
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
rule =
"""
{"!" : [[]]}
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
rule =
"""
{"!" : [[]]}
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
}
func testLogicalNot_withNumbers() {
var rule =
"""
{ "!" : 0 }
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
rule =
"""
{ "!" : 1 }
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
}
func testLogicalNot_withStrings() {
var rule =
"""
{"!" : ""}
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
rule =
"""
{"!" : ""}
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
rule =
"""
{"!" : "1"}
"""
XCTAssertEqual(false, try applyRule(rule, to: nil))
}
func testLogicalNot_withNull() {
let rule =
"""
{"!" : null}
"""
XCTAssertEqual(true, try applyRule(rule, to: nil))
}
func testLogicalNot_withVariables() {
let data =
"""
{ "a" : "b", "b" : "1", "oneNest" : {"one" : true} }
"""
var rule =
"""
{ "!" : [ {"var" : ["oneNest.one"] } ] }
"""
XCTAssertEqual(false, try applyRule(rule, to: data ))
rule =
"""
{ "!" : {"var" : ["a"] } }
"""
XCTAssertEqual(false, try applyRule(rule, to: data ))
rule =
"""
{ "!" : {"var" : ["nonExistant"] } }
"""
XCTAssertEqual(true, try applyRule(rule, to: data ))
}
}
| 24.585227 | 92 | 0.367229 |
def6422f6efa40baf648c5569d7a4aa042762666 | 20,281 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
internal class SecureDFUExecutor : DFUExecutor, SecureDFUPeripheralDelegate {
typealias DFUPeripheralType = SecureDFUPeripheral
internal let initiator : DFUServiceInitiator
internal let logger : LoggerHelper
internal let peripheral : SecureDFUPeripheral
internal var firmware : DFUFirmware
internal var error : (error: DFUError, message: String)?
internal var firmwareRanges : [Range<Int>]?
internal var currentRangeIdx : Int = 0
private var maxLen : UInt32?
private var offset : UInt32?
private var crc : UInt32?
internal var initPacketSent : Bool = false
internal var firmwareSent : Bool = false
internal var uploadStartTime : CFAbsoluteTime?
/// Retry counter in case the peripheral returns invalid CRC
private let MaxRetryCount = 3
private var retryCount: Int
// MARK: - Initialization
required init(_ initiator: DFUServiceInitiator, _ logger: LoggerHelper, _ peripheral: SecureDFUPeripheral) {
self.initiator = initiator
self.logger = logger
self.firmware = initiator.file!
self.retryCount = MaxRetryCount
self.peripheral = peripheral
}
required convenience init(_ initiator: DFUServiceInitiator, _ logger: LoggerHelper) {
self.init(initiator, logger, SecureDFUPeripheral(initiator, logger))
}
func start() {
error = nil
peripheral.delegate = self
peripheral.start() // -> peripheralDidBecomeReady() will be called when the device is connected and DFU services was found
}
// MARK: - DFU Peripheral Delegate methods
func peripheralDidBecomeReady() {
if firmware.initPacket == nil && peripheral.isInitPacketRequired() {
error(.extendedInitPacketRequired, didOccurWithMessage: "The init packet is required by the target device")
return
}
resetFirmwareRanges()
delegate {
$0.dfuStateDidChange(to: .starting)
}
peripheral.enableControlPoint() // -> peripheralDidEnableControlPoint() will be called when done
}
func peripheralDidEnableControlPoint() {
// Check whether the target is in application or bootloader mode
if peripheral.isInApplicationMode(initiator.forceDfu) {
delegate {
$0.dfuStateDidChange(to: .enablingDfuMode)
}
peripheral.jumpToBootloader() // -> peripheralDidBecomeReady() will be called again, when connected to the Bootloader
} else {
// The device is ready to proceed with DFU
// Start by reading command object info to get the maximum write size.
peripheral.readCommandObjectInfo() // -> peripheralDidSendCommandObjectInfo(...) will be called when object received
}
}
func peripheralDidSendCommandObjectInfo(maxLen: UInt32, offset: UInt32, crc: UInt32 ) {
self.maxLen = maxLen
self.offset = offset
self.crc = crc
// Was Init packet sent, at least partially, before?
if offset > 0 {
// If we are allowed to resume, then verify CRC of the part that was sent before
if !initiator.disableResume && verifyCRC(for: firmware.initPacket!, andPacketOffset: offset, matches: crc) {
// Resume sending Init Packet
if offset < UInt32(firmware.initPacket!.count) {
logger.a("Resuming sending Init packet...")
// We need to send rest of the Init packet, but before that let's make sure the PRNs are disabled
peripheral.setPRNValue(0) // -> peripheralDidSetPRNValue() will be called
} else {
// The same Init Packet was already sent. We must execute it, as it may have not been executed before.
logger.a("Received CRC match Init packet")
peripheral.sendExecuteCommand(forCommandObject: true) // -> peripheralDidExecuteObject() or peripheralRejectedCommandObject(...) will be called
}
} else {
// Start new update. We are either flashing a different firmware,
// or we are resuming from a BL/SD + App and need to start all over again.
self.offset = 0
self.crc = 0
peripheral.createCommandObject(withLength: UInt32(firmware.initPacket!.count)) // -> peripheralDidCreateCommandObject()
}
} else {
// No Init Packet was sent before. Create the Command object.
peripheral.createCommandObject(withLength: UInt32(firmware.initPacket!.count)) // -> peripheralDidCreateCommandObject()
}
}
func peripheralDidCreateCommandObject() {
// Disable PRNs for first time while we write Init file
peripheral.setPRNValue(0) // -> peripheralDidSetPRNValue() will be called
}
func peripheralDidSetPRNValue() {
if initPacketSent == false {
// PRNs are disabled, we may sent Init Packet data.
sendInitPacket(fromOffset: offset!) // -> peripheralDidReceiveInitPacket() will be called
} else {
// PRNs are ready, check out the Data object.
peripheral.readDataObjectInfo() // -> peripheralDidSendDataObjectInfo(...) will be called
}
}
func peripheralDidReceiveInitPacket() {
logger.a(String(format: "Command object sent (CRC = %08X)", crc32(data: firmware.initPacket!)))
// Init Packet sent. Let's check the CRC before executing it.
peripheral.sendCalculateChecksumCommand() // -> peripheralDidSendChecksum(...) will be called
}
func peripheralDidSendChecksum(offset: UInt32, crc: UInt32) {
self.crc = crc
self.offset = offset
if initPacketSent == false {
// Verify CRC
if verifyCRC(for: firmware.initPacket!, andPacketOffset: UInt32(firmware.initPacket!.count), matches: crc) {
// Init Packet sent correctly.
crcOk()
// It must be now executed.
peripheral.sendExecuteCommand(forCommandObject: true) // -> peripheralDidExecuteObject() or peripheralRejectedCommandObject(...) will be called
} else {
// The CRC does not match, let's start from the beginning.
retryOrReportCrcError({
self.offset = 0
self.crc = 0
peripheral.createCommandObject(withLength: UInt32(firmware.initPacket!.count)) // -> peripheralDidCreateCommandObject()
})
}
} else {
// Verify CRC
if verifyCRC(for: firmware.data, andPacketOffset: offset, matches: crc) {
// Data object sent correctly.
crcOk()
// It must be now executed.
firmwareSent = offset == UInt32(firmware.data.count)
peripheral.sendExecuteCommand(andActivateIf: firmwareSent) // -> peripheralDidExecuteObject()
} else {
retryOrReportCrcError({
createDataObject(currentRangeIdx) // -> peripheralDidCreateDataObject() will be called
})
}
}
}
func peripheralRejectedCommandObject(withError remoteError: DFUError, andMessage message: String) {
// If the terget device has rejected the firtst part, try sending the second part.
// If may be that the SD+BL were flashed before and can't be updated again due to
// sd-req and bootloader-version parameters set in the init packet.
// In that case app update should be possible.
if firmware.hasNextPart() {
firmware.switchToNextPart()
logger.w("Invalid system components. Trying to send application")
// New Init Packet has to be sent. Create the Command object.
offset = 0
crc = 0
peripheral.createCommandObject(withLength: UInt32(firmware.initPacket!.count)) // -> peripheralDidCreateCommandObject()
} else {
error(remoteError, didOccurWithMessage: message)
}
}
func peripheralDidExecuteObject() {
if initPacketSent == false {
logger.a("Command object executed")
initPacketSent = true
// Set the correct PRN value. If initiator.packetReceiptNotificationParameter is 0
// and PRNs were already disabled to send the Init packet, this method will immediately
// call peripheralDidSetPRNValue() callback.
peripheral.setPRNValue(initiator.packetReceiptNotificationParameter) // -> peripheralDidSetPRNValue() will be called
} else {
logger.a("Data object executed")
if firmwareSent == false {
currentRangeIdx += 1
createDataObject(currentRangeIdx) // -> peripheralDidCreateDataObject() will be called
} else {
// The last data object was sent
// Now the device will reset itself and onTransferCompleted() method will ba called (from the extension)
let interval = CFAbsoluteTimeGetCurrent() - uploadStartTime! as CFTimeInterval
logger.a("Upload completed in \(interval.format(".2")) seconds")
delegate {
$0.dfuStateDidChange(to: .disconnecting)
}
}
}
}
func peripheralDidSendDataObjectInfo(maxLen: UInt32, offset: UInt32, crc: UInt32 ) {
self.maxLen = maxLen
self.offset = offset
self.crc = crc
// This is the initial state, if ranges aren't set, assume this is the first
// or the only stage in the DFU process. The Init packet was already sent and executed.
if firmwareRanges == nil {
// Split firmware into smaller object of at most maxLen bytes, if firmware is bigger than maxLen
firmwareRanges = calculateFirmwareRanges(Int(maxLen))
currentRangeIdx = 0
}
delegate {
$0.dfuStateDidChange(to: .uploading)
}
if offset > 0 {
// Find the current range index.
currentRangeIdx = 0
for range in firmwareRanges! {
if range.contains(Int(offset)) {
break
}
currentRangeIdx += 1
}
if verifyCRC(for: firmware.data, andPacketOffset: offset, matches: crc) {
logger.i("\(offset) bytes of data sent before, CRC match")
// Did we sent the whole firmware?
if offset == UInt32(firmware.data.count) {
firmwareSent = true
peripheral.sendExecuteCommand(andActivateIf: firmwareSent) // -> peripheralDidExecuteObject() will be called
} else {
logger.i("Resuming uploading firmware...")
// If the whole object was sent before, make sure it's executed
if (offset % maxLen) == 0 {
// currentRangeIdx won't go below 0 because offset > 0 and offset % maxLen == 0
currentRangeIdx -= 1
peripheral.sendExecuteCommand() // -> peripheralDidExecuteObject() will be called
} else {
// Otherwise, continue sending the current object from given offset
sendDataObject(currentRangeIdx, from: offset) // -> peripheralDidReceiveObject() will be called
}
}
} else {
// If offset % maxLen and CRC does not match it means that the whole object needs to be sent again
if (offset % maxLen) == 0 {
// currentRangeIdx won't go below 0 because offset > 0 and offset % maxLen == 0
currentRangeIdx -= 1
}
retryOrReportCrcError({
createDataObject(currentRangeIdx) // -> peripheralDidCreateDataObject() will be called
})
}
} else {
// Create the first data object
createDataObject(currentRangeIdx) // -> peripheralDidCreateDataObject() will be called
}
}
func peripheralDidCreateDataObject() {
logger.i("Data object \(currentRangeIdx + 1)/\(firmwareRanges!.count) created")
sendDataObject(currentRangeIdx) // -> peripheralDidReceiveObject() will be called
}
func peripheralDidReceiveObject() {
peripheral.sendCalculateChecksumCommand() // -> peripheralDidSendChecksum(...) will be called
}
// MARK: - Private methods
private func retryOrReportCrcError(_ operation:()->()) {
retryCount -= 1
if retryCount > 0 {
logger.w("CRC does not match! Retrying...")
operation()
} else {
logger.e("CRC does not match!")
error(.crcError, didOccurWithMessage: "Sending firmware failed")
}
}
private func crcOk() {
retryCount = MaxRetryCount
}
/**
Resets firmware ranges and progress flags. This method should be called before sending each part of the firmware.
*/
private func resetFirmwareRanges() {
currentRangeIdx = 0
firmwareRanges = nil
initPacketSent = false
firmwareSent = false
uploadStartTime = CFAbsoluteTimeGetCurrent()
}
/**
Calculates the firmware ranges.
In Secure DFU the firmware is sent as separate 'objects', where each object is at most 'maxLen' long.
This method creates a list of ranges that will be used to send data to the peripheral, for example:
0 ..< 4096, 4096 ..< 5000 in case the firmware was 5000 bytes long.
*/
private func calculateFirmwareRanges(_ maxLen: Int) -> [Range<Int>] {
var totalLength = firmware.data.count
var ranges = [Range<Int>]()
var partIdx = 0
while (totalLength > 0) {
var range : Range<Int>
if totalLength > maxLen {
totalLength -= maxLen
range = (partIdx * maxLen) ..< maxLen + (partIdx * maxLen)
} else {
range = (partIdx * maxLen) ..< totalLength + (partIdx * maxLen)
totalLength = 0
}
ranges.append(range)
partIdx += 1
}
return ranges
}
/**
Verifies if the CRC-32 of the data from byte 0 to given offset matches the given CRC value.
- parameter data: Firmware or Init packet data.
- parameter offset: Number of bytes that should be used for CRC calculation.
- parameter crc: The CRC obtained from the DFU Target to be matched.
- returns: True if CRCs are identical, false otherwise.
*/
private func verifyCRC(for data: Data, andPacketOffset offset: UInt32, matches crc: UInt32) -> Bool {
// Edge case where a different objcet might be flashed with a biger init file
if offset > UInt32(data.count) {
return false
}
// Get data form 0 up to the offset the peripheral has reproted
let offsetData : Data = (data.subdata(in: 0 ..< Int(offset)))
let calculatedCRC = crc32(data: offsetData)
// This returns true if the current data packet's CRC matches the current firmware's packet CRC
return calculatedCRC == crc
}
/**
Sends the Init packet starting from the given offset. This method is asynchronous, it calls
peripheralDidReceiveInitPacket() callback when done.
- parameter offset: The starting offset from which the Init Packet should be sent.
This allows resuming uploading the Init Packet.
*/
private func sendInitPacket(fromOffset offset: UInt32) {
let initPacketLength = UInt32(firmware.initPacket!.count)
let data = firmware.initPacket!.subdata(in: Int(offset) ..< Int(initPacketLength - offset))
// Send following bytes of init packet (offset may be 0)
peripheral.sendInitPacket(data) // -> peripheralDidReceiveInitPacket() will be called
}
/**
Creates the new data object with length equal to the length of the range with given index.
The ranges were calculated using `calculateFirmwareRanges()`.
- parameter rangeIdx: Index of a range of the firmware.
*/
internal func createDataObject(_ rangeIdx: Int) {
let currentRange = firmwareRanges![rangeIdx]
peripheral.createDataObject(withLength: UInt32(currentRange.upperBound - currentRange.lowerBound))
// -> peripheralDidCreateDataObject() will be called
}
/**
This method sends the bytes from the range with given index.
If the resumeOffset is set and equal to lower bound of the given range it will create the object instead.
When created, a onObjectCreated() method will be called which will call this method again, now with the offset
parameter equal nil.
- parameter rangeIdx: Index of the range to be sent. The ranges were calculated using `calculateFirmwareRanges()`.
- parameter resumeOffset: If set, this method will send only the part of firmware from the range. The offset must
be inside the given range.
*/
private func sendDataObject(_ rangeIdx: Int, from resumeOffset: UInt32? = nil) {
var aRange = firmwareRanges![rangeIdx]
if let resumeOffset = resumeOffset {
if UInt32(aRange.lowerBound) == resumeOffset {
// We reached the end of previous object so a new one must be created
createDataObject(rangeIdx)
return
}
// This is a resuming object, recalculate location and size
let newLength = aRange.lowerBound + (aRange.upperBound - aRange.lowerBound) - Int(offset!)
aRange = Int(resumeOffset) ..< newLength + Int(resumeOffset)
}
peripheral.sendNextObject(from: aRange, of: firmware,
andReportProgressTo: initiator.progressDelegate, on: initiator.progressDelegateQueue)
// -> peripheralDidReceiveObject() will be called
}
}
| 45.988662 | 163 | 0.617524 |
8918a28ccd5e217f9a59adb458a030f68b596005 | 1,008 | //
// MediemWidgetView.swift
// social
//
// Created by Ahmed Ragab on 8/5/20.
// Copyright © 2020 Ahmed Ragab. All rights reserved.
//
import SwiftUI
struct MediemWidgetView: View {
@State var name = " "
var body: some View {
VStack (alignment:.leading,spacing:2){
Image("user1")
.resizable()
.cornerRadius(15)
.padding()
VStack(alignment:.center) {
Text("I am Student at FCIS ASU Write ios Native and BackEnd with Express FrameWork ")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(Color.secondary)
.padding([.leading,.trailing])
.frame(maxWidth:.infinity,maxHeight: 50)
}
}
}
}
struct MediemWidgetView_Previews: PreviewProvider {
static var previews: some View {
MediemWidgetView()
}
}
| 25.2 | 103 | 0.514881 |
e99028474aae80dee17b541210d7e3bca9087392 | 1,619 | import Cocoa
import SwiftUI
import KeyboardShortcuts
@NSApplicationMain
final class AppDelegate: NSObject, NSApplicationDelegate {
private var window: NSWindow!
func applicationDidFinishLaunching(_ notification: Notification) {
let contentView = ContentView()
window = NSWindow(
contentRect: CGRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [
.titled,
.closable,
.miniaturizable,
.fullSizeContentView,
.resizable
],
backing: .buffered,
defer: false
)
window.title = "KeyboardShortcuts Example"
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
createMenus()
}
func createMenus() {
let testMenuItem = NSMenuItem()
NSApp.mainMenu?.addItem(testMenuItem)
let testMenu = NSMenu()
testMenu.title = "Test"
testMenuItem.submenu = testMenu
let shortcut1 = NSMenuItem()
shortcut1.title = "Shortcut 1"
shortcut1.action = #selector(shortcutAction1)
shortcut1.setShortcut(for: .testShortcut1)
testMenu.addItem(shortcut1)
let shortcut2 = NSMenuItem()
shortcut2.title = "Shortcut 2"
shortcut2.action = #selector(shortcutAction2)
shortcut2.setShortcut(for: .testShortcut2)
testMenu.addItem(shortcut2)
}
@objc
func shortcutAction1(_ sender: NSMenuItem) {
let alert = NSAlert()
alert.messageText = "Shortcut 1 menu item action triggered!"
alert.runModal()
}
@objc
func shortcutAction2(_ sender: NSMenuItem) {
let alert = NSAlert()
alert.messageText = "Shortcut 2 menu item action triggered!"
alert.runModal()
}
}
| 23.463768 | 67 | 0.732551 |
67de8222a1a28eb660655f5f1b2c42d3b9ca24b2 | 1,054 | //
// PanoramaViewController.swift
// BEDemo
//
// Created by Sun YuLi on 2017/5/22.
// Copyright © 2017年 SODEC. All rights reserved.
//
import UIKit
class PanoramaViewController: UIViewController {
@IBOutlet weak var panoview: BEPanoramaView!
@IBAction func resetAction(_ sender: Any) {
panoview.resetAttitude()
}
@IBAction func handlePanAction(_ sender: Any) {
panoview.renderer.setCameraRotateMode(BECameraRotateAroundModelManual)
let pan = sender as! UIPanGestureRecognizer
let point = pan.translation(in: panoview)
panoview.renderer.rotateModel(byPanGesture: point)
}
override func viewDidLoad() {
super.viewDidLoad()
panoview.loadPanoramaTexture("panorama360.jpg")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
panoview.startDraw()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
panoview.stopDraw()
}
}
| 24.511628 | 78 | 0.666983 |