repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/defaultArguments/kt6382.kt | 2 | 301 | // WITH_RUNTIME
fun box(): String {
return if (A().run() == "Aabc") "OK" else "fail"
}
public class A {
fun run() =
with ("abc") {
show()
}
private fun String.show(p: Boolean = false): String = getName() + this
private fun getName() = "A"
}
| apache-2.0 | 60b4ae4efc71685646399efc75ddea60 | 17.8125 | 74 | 0.48505 | 3.5 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/AbstractCommitWorkflow.kt | 1 | 14153 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.CommonBundle.getCancelButtonText
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages.*
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ChangesUtil.getAffectedVcses
import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionAction.addUnversionedFilesToVcs
import com.intellij.openapi.vcs.changes.ui.SessionDialog
import com.intellij.openapi.vcs.checkin.BaseCheckinHandlerFactory
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinMetaHandler
import com.intellij.openapi.vcs.impl.CheckinHandlersManager
import com.intellij.openapi.vcs.impl.PartialChangesUtil.getPartialTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil.newUnmodifiableList
import com.intellij.util.containers.ContainerUtil.unmodifiableOrEmptySet
import com.intellij.util.containers.forEachLoggingErrors
import java.util.*
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private val LOG = logger<AbstractCommitWorkflow>()
internal fun CommitOptions.saveState() = allOptions.forEach { it.saveState() }
internal fun CommitOptions.restoreState() = allOptions.forEach { it.restoreState() }
private class CommitProperty<T>(private val key: Key<T>, private val defaultValue: T) : ReadWriteProperty<CommitContext, T> {
override fun getValue(thisRef: CommitContext, property: KProperty<*>): T = thisRef.getUserData(key) ?: defaultValue
override fun setValue(thisRef: CommitContext, property: KProperty<*>, value: T) = thisRef.putUserData(key, value)
}
fun commitProperty(key: Key<Boolean>): ReadWriteProperty<CommitContext, Boolean> = commitProperty(key, false)
fun <T> commitProperty(key: Key<T>, defaultValue: T): ReadWriteProperty<CommitContext, T> = CommitProperty(key, defaultValue)
private val IS_AMEND_COMMIT_MODE_KEY = Key.create<Boolean>("Vcs.Commit.IsAmendCommitMode")
var CommitContext.isAmendCommitMode: Boolean by commitProperty(IS_AMEND_COMMIT_MODE_KEY)
private val IS_CLEANUP_COMMIT_MESSAGE_KEY = Key.create<Boolean>("Vcs.Commit.IsCleanupCommitMessage")
var CommitContext.isCleanupCommitMessage: Boolean by commitProperty(IS_CLEANUP_COMMIT_MESSAGE_KEY)
interface CommitWorkflowListener : EventListener {
fun vcsesChanged()
fun executionStarted()
fun executionEnded()
fun beforeCommitChecksStarted()
fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult)
}
abstract class AbstractCommitWorkflow(val project: Project) {
private val eventDispatcher = EventDispatcher.create(CommitWorkflowListener::class.java)
private val commitEventDispatcher = EventDispatcher.create(CommitResultHandler::class.java)
private val commitCustomEventDispatcher = EventDispatcher.create(CommitResultHandler::class.java)
var isExecuting = false
private set
var commitContext: CommitContext = CommitContext()
private set
abstract val isDefaultCommitEnabled: Boolean
private val _vcses = mutableSetOf<AbstractVcs>()
val vcses: Set<AbstractVcs> get() = unmodifiableOrEmptySet(_vcses.toSet())
private val _commitExecutors = mutableListOf<CommitExecutor>()
val commitExecutors: List<CommitExecutor> get() = newUnmodifiableList(_commitExecutors)
private val _commitHandlers = mutableListOf<CheckinHandler>()
val commitHandlers: List<CheckinHandler> get() = newUnmodifiableList(_commitHandlers)
private val _commitOptions = MutableCommitOptions()
val commitOptions: CommitOptions get() = _commitOptions.toUnmodifiableOptions()
protected fun updateVcses(vcses: Set<AbstractVcs>) {
if (_vcses != vcses) {
_vcses.clear()
_vcses += vcses
eventDispatcher.multicaster.vcsesChanged()
}
}
internal fun initCommitExecutors(executors: List<CommitExecutor>) {
_commitExecutors.clear()
_commitExecutors += executors
}
internal fun initCommitHandlers(handlers: List<CheckinHandler>) {
_commitHandlers.clear()
_commitHandlers += handlers
}
internal fun disposeCommitOptions() {
_commitOptions.allOptions.filterIsInstance<Disposable>().forEach { Disposer.dispose(it) }
_commitOptions.clear()
}
internal fun initCommitOptions(options: CommitOptions) {
disposeCommitOptions()
_commitOptions.add(options)
}
internal fun clearCommitContext() {
commitContext = CommitContext()
}
internal fun startExecution(block: () -> Boolean) {
check(!isExecuting)
isExecuting = true
continueExecution {
eventDispatcher.multicaster.executionStarted()
block()
}
}
internal fun continueExecution(block: () -> Boolean) {
check(isExecuting)
runCatching(block)
.onFailure { endExecution() }
.onSuccess { continueExecution -> if (!continueExecution) endExecution() }
.getOrThrow()
}
internal fun endExecution(block: () -> Unit) =
continueExecution {
block()
false
}
internal fun endExecution() {
check(isExecuting)
isExecuting = false
eventDispatcher.multicaster.executionEnded()
}
protected fun getEndExecutionHandler(): CommitResultHandler = EndExecutionCommitResultHandler(this)
fun addListener(listener: CommitWorkflowListener, parent: Disposable) = eventDispatcher.addListener(listener, parent)
fun addCommitListener(listener: CommitResultHandler, parent: Disposable) = commitEventDispatcher.addListener(listener, parent)
fun addCommitCustomListener(listener: CommitResultHandler, parent: Disposable) = commitCustomEventDispatcher.addListener(listener, parent)
protected fun getCommitEventDispatcher(): CommitResultHandler = EdtCommitResultHandler(commitEventDispatcher.multicaster)
protected fun getCommitCustomEventDispatcher(): CommitResultHandler = commitCustomEventDispatcher.multicaster
fun addUnversionedFiles(changeList: LocalChangeList, unversionedFiles: List<VirtualFile>, callback: (List<Change>) -> Unit): Boolean {
if (unversionedFiles.isEmpty()) return true
FileDocumentManager.getInstance().saveAllDocuments()
return addUnversionedFilesToVcs(project, changeList, unversionedFiles, callback, null)
}
fun executeDefault(executor: CommitExecutor?): Boolean {
val beforeCommitChecksResult = runBeforeCommitChecksWithEvents(true, executor)
processExecuteDefaultChecksResult(beforeCommitChecksResult)
return beforeCommitChecksResult == CheckinHandler.ReturnResult.COMMIT
}
protected open fun processExecuteDefaultChecksResult(result: CheckinHandler.ReturnResult) = Unit
protected fun runBeforeCommitChecksWithEvents(isDefaultCommit: Boolean, executor: CommitExecutor?): CheckinHandler.ReturnResult {
fireBeforeCommitChecksStarted()
val result = runBeforeCommitChecks(executor)
fireBeforeCommitChecksEnded(isDefaultCommit, result)
return result
}
protected fun fireBeforeCommitChecksStarted() = eventDispatcher.multicaster.beforeCommitChecksStarted()
protected fun fireBeforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) =
eventDispatcher.multicaster.beforeCommitChecksEnded(isDefaultCommit, result)
private fun runBeforeCommitChecks(executor: CommitExecutor?): CheckinHandler.ReturnResult {
var result: CheckinHandler.ReturnResult? = null
var checks = Runnable {
ProgressManager.checkCanceled()
FileDocumentManager.getInstance().saveAllDocuments()
result = runBeforeCommitHandlersChecks(executor, commitHandlers)
}
commitHandlers.filterIsInstance<CheckinMetaHandler>().forEach { metaHandler ->
checks = wrapWithCommitMetaHandler(metaHandler, checks)
}
val task = Runnable {
try {
checks.run()
if (result == null) LOG.warn("No commit handlers result. Seems CheckinMetaHandler returned before invoking its callback.")
}
catch (ignore: ProcessCanceledException) {
}
catch (e: Throwable) {
LOG.error(e)
}
}
doRunBeforeCommitChecks(task)
return result ?: CheckinHandler.ReturnResult.CANCEL.also { LOG.debug("No commit handlers result. Cancelling commit.") }
}
protected open fun doRunBeforeCommitChecks(checks: Runnable) = checks.run()
protected fun wrapWithCommitMetaHandler(metaHandler: CheckinMetaHandler, task: Runnable): Runnable =
Runnable {
try {
LOG.debug("CheckinMetaHandler.runCheckinHandlers: $metaHandler")
metaHandler.runCheckinHandlers(task)
}
catch (e: ProcessCanceledException) {
LOG.debug("CheckinMetaHandler cancelled $metaHandler")
throw e
}
catch (e: Throwable) {
LOG.error(e)
task.run()
}
}
protected fun runBeforeCommitHandlersChecks(executor: CommitExecutor?, handlers: List<CheckinHandler>): CheckinHandler.ReturnResult {
handlers.forEachLoggingErrors(LOG) { handler ->
try {
val result = runBeforeCommitHandler(handler, executor)
if (result != CheckinHandler.ReturnResult.COMMIT) return result
}
catch (e: ProcessCanceledException) {
LOG.debug("CheckinHandler cancelled $handler")
return CheckinHandler.ReturnResult.CANCEL
}
}
return CheckinHandler.ReturnResult.COMMIT
}
protected open fun runBeforeCommitHandler(handler: CheckinHandler, executor: CommitExecutor?): CheckinHandler.ReturnResult {
if (!handler.acceptExecutor(executor)) return CheckinHandler.ReturnResult.COMMIT
LOG.debug("CheckinHandler.beforeCheckin: $handler")
return handler.beforeCheckin(executor, commitContext.additionalDataConsumer)
}
open fun canExecute(executor: CommitExecutor, changes: Collection<Change>): Boolean {
if (!executor.supportsPartialCommit()) {
val hasPartialChanges = changes.any { getPartialTracker(project, it)?.hasPartialChangesToCommit() ?: false }
if (hasPartialChanges) {
return YES == showYesNoDialog(
project, message("commit.dialog.partial.commit.warning.body", executor.getPresentableText()),
message("commit.dialog.partial.commit.warning.title"), executor.actionText, getCancelButtonText(),
getWarningIcon())
}
}
return true
}
abstract fun executeCustom(executor: CommitExecutor, session: CommitSession): Boolean
protected fun executeCustom(executor: CommitExecutor, session: CommitSession, changes: List<Change>, commitMessage: String): Boolean =
configureCommitSession(executor, session, changes, commitMessage) &&
run {
val beforeCommitChecksResult = runBeforeCommitChecksWithEvents(false, executor)
processExecuteCustomChecksResult(executor, session, beforeCommitChecksResult)
beforeCommitChecksResult == CheckinHandler.ReturnResult.COMMIT
}
private fun configureCommitSession(executor: CommitExecutor,
session: CommitSession,
changes: List<Change>,
commitMessage: String): Boolean {
val sessionConfigurationUi = session.getAdditionalConfigurationUI(changes, commitMessage) ?: return true
val sessionDialog = SessionDialog(executor.getPresentableText(), project, session, changes, commitMessage, sessionConfigurationUi)
if (sessionDialog.showAndGet()) return true
else {
session.executionCanceled()
return false
}
}
protected open fun processExecuteCustomChecksResult(executor: CommitExecutor,
session: CommitSession,
result: CheckinHandler.ReturnResult) = Unit
companion object {
@JvmStatic
fun getCommitHandlerFactories(vcses: Collection<AbstractVcs>): List<BaseCheckinHandlerFactory> =
CheckinHandlersManager.getInstance().getRegisteredCheckinHandlerFactories(vcses.toTypedArray())
@JvmStatic
fun getCommitHandlers(
vcses: Collection<AbstractVcs>,
commitPanel: CheckinProjectPanel,
commitContext: CommitContext
): List<CheckinHandler> =
getCommitHandlerFactories(vcses)
.map { it.createHandler(commitPanel, commitContext) }
.filter { it != CheckinHandler.DUMMY }
@JvmStatic
fun getCommitExecutors(project: Project, changes: Collection<Change>): List<CommitExecutor> =
getCommitExecutors(project, getAffectedVcses(changes, project))
internal fun getCommitExecutors(project: Project, vcses: Collection<AbstractVcs>): List<CommitExecutor> =
vcses.flatMap { it.commitExecutors } + ChangeListManager.getInstance(project).registeredExecutors +
LocalCommitExecutor.LOCAL_COMMIT_EXECUTOR.getExtensions(project)
}
}
class EdtCommitResultHandler(private val handler: CommitResultHandler) : CommitResultHandler {
override fun onSuccess(commitMessage: String) = runInEdt { handler.onSuccess(commitMessage) }
override fun onCancel() = runInEdt { handler.onCancel() }
override fun onFailure(errors: List<VcsException>) = runInEdt { handler.onFailure(errors) }
}
private class EndExecutionCommitResultHandler(private val workflow: AbstractCommitWorkflow) : CommitResultHandler {
override fun onSuccess(commitMessage: String) = workflow.endExecution()
override fun onCancel() = workflow.endExecution()
override fun onFailure(errors: List<VcsException>) = workflow.endExecution()
}
| apache-2.0 | a168ced0e036b633f238f2fa18479175 | 40.872781 | 140 | 0.761252 | 5.011686 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/editor/VcsLogEditor.kt | 7 | 2881 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.ui.editor
import com.intellij.diff.util.FileEditorBase
import com.intellij.icons.AllIcons
import com.intellij.ide.FileIconProvider
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorPolicy
import com.intellij.openapi.fileEditor.FileEditorProvider
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.impl.VcsLogEditorUtil.disposeLogUis
import com.intellij.vcs.log.ui.VcsLogPanel
import java.awt.BorderLayout
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
class VcsLogFileType private constructor() : FileType {
override fun getName(): String = "VcsLog"
override fun getDescription(): String = VcsLogBundle.message("filetype.vcs.log.description")
override fun getDefaultExtension(): String = ""
override fun getIcon(): Icon = AllIcons.Vcs.Branch
override fun isBinary(): Boolean = true
override fun isReadOnly(): Boolean = true
companion object {
val INSTANCE = VcsLogFileType()
}
}
abstract class VcsLogFile(name: String) : LightVirtualFile(name, VcsLogFileType.INSTANCE, "") {
init {
isWritable = false
}
abstract fun createMainComponent(project: Project): JComponent
}
class VcsLogIconProvider : FileIconProvider {
override fun getIcon(file: VirtualFile, flags: Int, project: Project?): Icon? = (file as? VcsLogFile)?.fileType?.icon
}
class VcsLogEditor(private val project: Project, private val vcsLogFile: VcsLogFile) : FileEditorBase() {
internal val rootComponent: JComponent = JPanel(BorderLayout()).also {
it.add(vcsLogFile.createMainComponent(project), BorderLayout.CENTER)
}
override fun getComponent(): JComponent = rootComponent
override fun getPreferredFocusedComponent(): JComponent? = VcsLogPanel.getLogUis(component).firstOrNull()?.mainComponent
override fun getName(): String = VcsLogBundle.message("vcs.log.editor.name")
override fun getFile() = vcsLogFile
}
class VcsLogEditorProvider : FileEditorProvider, DumbAware {
override fun accept(project: Project, file: VirtualFile): Boolean = file is VcsLogFile
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
return VcsLogEditor(project, file as VcsLogFile)
}
override fun getEditorTypeId(): String = "VcsLogEditor"
override fun getPolicy(): FileEditorPolicy = FileEditorPolicy.HIDE_DEFAULT_EDITOR
override fun disposeEditor(editor: FileEditor) {
editor.disposeLogUis()
super.disposeEditor(editor)
}
}
| apache-2.0 | 8bd1fe0c4d37cffca97c28e7ae8c8715 | 37.932432 | 140 | 0.787921 | 4.439137 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/property/valComplexFqType.kt | 4 | 298 | class Foo { class Int }
<warning descr="SSR">val foo1: List<Pair<String, (Foo.Int) -> kotlin.Int>> = listOf()</warning>
<warning descr="SSR">val foo2 = listOf("foo" to { _: Foo.Int -> 2 })</warning>
val bar1: List<Pair<String, (Int) -> Int>> = listOf()
val bar2 = listOf("bar" to { _: Int -> 2 }) | apache-2.0 | 532e3a12cb7856ce5b97744c19d9e1b8 | 41.714286 | 95 | 0.610738 | 2.893204 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/services/apirequests/ResetPasswordBody.kt | 1 | 843 | package com.kickstarter.services.apirequests
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class ResetPasswordBody private constructor(
private val email: String
) : Parcelable {
fun email() = this.email
@Parcelize
data class Builder(
private var email: String = ""
) : Parcelable {
fun email(email: String) = apply { this.email = email }
fun build() = ResetPasswordBody(
email = email
)
}
fun toBuilder() = Builder(
email = email
)
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is ResetPasswordBody) {
equals = email() == obj.email()
}
return equals
}
companion object {
@JvmStatic
fun builder() = Builder()
}
}
| apache-2.0 | fd56c058e2508c72de0a7522e8b3e9db | 21.184211 | 63 | 0.59312 | 4.484043 | false | false | false | false |
tensorflow/examples | lite/examples/object_detection/android_play_services/app/src/main/java/org/tensorflow/lite/examples/objectdetection/ObjectDetectorHelper.kt | 1 | 6655 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.objectdetection
import android.content.Context
import android.graphics.Bitmap
import android.os.SystemClock
import android.util.Log
import com.google.android.gms.tflite.client.TfLiteInitializationOptions
import com.google.android.gms.tflite.gpu.support.TfLiteGpu
import org.tensorflow.lite.support.image.ImageProcessor
import org.tensorflow.lite.support.image.TensorImage
import org.tensorflow.lite.support.image.ops.Rot90Op
import org.tensorflow.lite.task.core.BaseOptions
import org.tensorflow.lite.task.gms.vision.TfLiteVision
import org.tensorflow.lite.task.gms.vision.detector.Detection
import org.tensorflow.lite.task.gms.vision.detector.ObjectDetector
class ObjectDetectorHelper(
var threshold: Float = 0.5f,
var numThreads: Int = 2,
var maxResults: Int = 3,
var currentDelegate: Int = 0,
var currentModel: Int = 0,
val context: Context,
val objectDetectorListener: DetectorListener
) {
private val TAG = "ObjectDetectionHelper"
// For this example this needs to be a var so it can be reset on changes. If the ObjectDetector
// will not change, a lazy val would be preferable.
private var objectDetector: ObjectDetector? = null
private var gpuSupported = false
init {
TfLiteGpu.isGpuDelegateAvailable(context).onSuccessTask { gpuAvailable: Boolean ->
val optionsBuilder =
TfLiteInitializationOptions.builder()
if (gpuAvailable) {
optionsBuilder.setEnableGpuDelegateSupport(true)
}
TfLiteVision.initialize(context, optionsBuilder.build())
}.addOnSuccessListener {
objectDetectorListener.onInitialized()
}.addOnFailureListener{
objectDetectorListener.onError("TfLiteVision failed to initialize: "
+ it.message)
}
}
fun clearObjectDetector() {
objectDetector = null
}
// Initialize the object detector using current settings on the
// thread that is using it. CPU and NNAPI delegates can be used with detectors
// that are created on the main thread and used on a background thread, but
// the GPU delegate needs to be used on the thread that initialized the detector
fun setupObjectDetector() {
if (!TfLiteVision.isInitialized()) {
Log.e(TAG, "setupObjectDetector: TfLiteVision is not initialized yet")
return
}
// Create the base options for the detector using specifies max results and score threshold
val optionsBuilder =
ObjectDetector.ObjectDetectorOptions.builder()
.setScoreThreshold(threshold)
.setMaxResults(maxResults)
// Set general detection options, including number of used threads
val baseOptionsBuilder = BaseOptions.builder().setNumThreads(numThreads)
// Use the specified hardware for running the model. Default to CPU
when (currentDelegate) {
DELEGATE_CPU -> {
// Default
}
DELEGATE_GPU -> {
if (gpuSupported) {
baseOptionsBuilder.useGpu()
} else {
objectDetectorListener.onError("GPU is not supported on this device")
}
}
DELEGATE_NNAPI -> {
baseOptionsBuilder.useNnapi()
}
}
optionsBuilder.setBaseOptions(baseOptionsBuilder.build())
val modelName =
when (currentModel) {
MODEL_MOBILENETV1 -> "mobilenetv1.tflite"
MODEL_EFFICIENTDETV0 -> "efficientdet-lite0.tflite"
MODEL_EFFICIENTDETV1 -> "efficientdet-lite1.tflite"
MODEL_EFFICIENTDETV2 -> "efficientdet-lite2.tflite"
else -> "mobilenetv1.tflite"
}
try {
objectDetector =
ObjectDetector.createFromFileAndOptions(context, modelName, optionsBuilder.build())
} catch (e: Exception) {
objectDetectorListener.onError(
"Object detector failed to initialize. See error logs for details"
)
Log.e(TAG, "TFLite failed to load model with error: " + e.message)
}
}
fun detect(image: Bitmap, imageRotation: Int) {
if (!TfLiteVision.isInitialized()) {
Log.e(TAG, "detect: TfLiteVision is not initialized yet")
return
}
if (objectDetector == null) {
setupObjectDetector()
}
// Inference time is the difference between the system time at the start and finish of the
// process
var inferenceTime = SystemClock.uptimeMillis()
// Create preprocessor for the image.
// See https://www.tensorflow.org/lite/inference_with_metadata/
// lite_support#imageprocessor_architecture
val imageProcessor = ImageProcessor.Builder().add(Rot90Op(-imageRotation / 90)).build()
// Preprocess the image and convert it into a TensorImage for detection.
val tensorImage = imageProcessor.process(TensorImage.fromBitmap(image))
val results = objectDetector?.detect(tensorImage)
inferenceTime = SystemClock.uptimeMillis() - inferenceTime
objectDetectorListener.onResults(
results,
inferenceTime,
tensorImage.height,
tensorImage.width)
}
interface DetectorListener {
fun onInitialized()
fun onError(error: String)
fun onResults(
results: MutableList<Detection>?,
inferenceTime: Long,
imageHeight: Int,
imageWidth: Int
)
}
companion object {
const val DELEGATE_CPU = 0
const val DELEGATE_GPU = 1
const val DELEGATE_NNAPI = 2
const val MODEL_MOBILENETV1 = 0
const val MODEL_EFFICIENTDETV0 = 1
const val MODEL_EFFICIENTDETV1 = 2
const val MODEL_EFFICIENTDETV2 = 3
}
}
| apache-2.0 | 14114d6a5adca4a2786a13ba4ac4b93a | 36.178771 | 99 | 0.650939 | 4.570742 | false | false | false | false |
ingokegel/intellij-community | plugins/gradle/testSources/org/jetbrains/plugins/gradle/testFramework/fixtures/impl/GradleCodeInsightTestFixtureImpl.kt | 3 | 2016 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.testFramework.fixtures.impl
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.testFramework.common.runAll
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.testFramework.fixtures.impl.JavaCodeInsightTestFixtureImpl
import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl
import org.jetbrains.plugins.gradle.testFramework.fixtures.GradleCodeInsightTestFixture
import org.jetbrains.plugins.gradle.testFramework.fixtures.GradleTestFixture
class GradleCodeInsightTestFixtureImpl private constructor(
private val gradleFixture: GradleTestFixture,
override val codeInsightFixture: JavaCodeInsightTestFixture
) : GradleCodeInsightTestFixture, GradleTestFixture by gradleFixture {
constructor(fixture: GradleTestFixture) : this(fixture, createCodeInsightFixture(fixture))
override fun setUp() {
gradleFixture.setUp()
codeInsightFixture.setUp()
}
override fun tearDown() {
runAll(
{ codeInsightFixture.tearDown() },
{ gradleFixture.tearDown() }
)
}
companion object {
private fun createCodeInsightFixture(gradleFixture: GradleTestFixture): JavaCodeInsightTestFixture {
val tempDirFixture = TempDirTestFixtureImpl()
val projectFixture = object : IdeaProjectTestFixture {
override fun getProject(): Project = gradleFixture.project
override fun getModule(): Module = gradleFixture.module
override fun setUp() = Unit
override fun tearDown() = Unit
}
return object : JavaCodeInsightTestFixtureImpl(projectFixture, tempDirFixture) {
override fun shouldTrackVirtualFilePointers(): Boolean = false
init {
setVirtualFileFilter(null)
}
}
}
}
} | apache-2.0 | 4eb97912309896d6d1c6aa69a801a28f | 38.54902 | 120 | 0.777282 | 5.333333 | false | true | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ArtifactPropertiesEntityImpl.kt | 1 | 10053 | package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactPropertiesEntityImpl: ArtifactPropertiesEntity, WorkspaceEntityBase() {
companion object {
internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, ArtifactPropertiesEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
ARTIFACT_CONNECTION_ID,
)
}
override val artifact: ArtifactEntity
get() = snapshot.extractOneToManyParent(ARTIFACT_CONNECTION_ID, this)!!
@JvmField var _providerType: String? = null
override val providerType: String
get() = _providerType!!
@JvmField var _propertiesXmlTag: String? = null
override val propertiesXmlTag: String?
get() = _propertiesXmlTag
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ArtifactPropertiesEntityData?): ModifiableWorkspaceEntityBase<ArtifactPropertiesEntity>(), ArtifactPropertiesEntity.Builder {
constructor(): this(ArtifactPropertiesEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactPropertiesEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(ARTIFACT_CONNECTION_ID, this) == null) {
error("Field ArtifactPropertiesEntity#artifact should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] == null) {
error("Field ArtifactPropertiesEntity#artifact should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ArtifactPropertiesEntity#entitySource should be initialized")
}
if (!getEntityData().isProviderTypeInitialized()) {
error("Field ArtifactPropertiesEntity#providerType should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var artifact: ArtifactEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)]!! as ArtifactEntity
} else {
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)]!! as ArtifactEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(ARTIFACT_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value
}
changedProperty.add("artifact")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var providerType: String
get() = getEntityData().providerType
set(value) {
checkModificationAllowed()
getEntityData().providerType = value
changedProperty.add("providerType")
}
override var propertiesXmlTag: String?
get() = getEntityData().propertiesXmlTag
set(value) {
checkModificationAllowed()
getEntityData().propertiesXmlTag = value
changedProperty.add("propertiesXmlTag")
}
override fun getEntityData(): ArtifactPropertiesEntityData = result ?: super.getEntityData() as ArtifactPropertiesEntityData
override fun getEntityClass(): Class<ArtifactPropertiesEntity> = ArtifactPropertiesEntity::class.java
}
}
class ArtifactPropertiesEntityData : WorkspaceEntityData<ArtifactPropertiesEntity>() {
lateinit var providerType: String
var propertiesXmlTag: String? = null
fun isProviderTypeInitialized(): Boolean = ::providerType.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ArtifactPropertiesEntity> {
val modifiable = ArtifactPropertiesEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactPropertiesEntity {
val entity = ArtifactPropertiesEntityImpl()
entity._providerType = providerType
entity._propertiesXmlTag = propertiesXmlTag
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactPropertiesEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactPropertiesEntityData
if (this.entitySource != other.entitySource) return false
if (this.providerType != other.providerType) return false
if (this.propertiesXmlTag != other.propertiesXmlTag) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactPropertiesEntityData
if (this.providerType != other.providerType) return false
if (this.propertiesXmlTag != other.propertiesXmlTag) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + providerType.hashCode()
result = 31 * result + propertiesXmlTag.hashCode()
return result
}
} | apache-2.0 | 32326880a5db83aea5b3e467ab61dd97 | 41.601695 | 193 | 0.634239 | 6.133618 | false | false | false | false |
kivensolo/UiUsingListView | library/ui/src/main/java/com/module/views/img/SmartImageView.kt | 1 | 6110 | package com.module.views.img
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import com.module.views.R
/**
* author:ZekeWang
* date:2021/7/2
* description:
* - 支持自定义圆角
* - 支持圆角模式选择(Clip或者Xfermode)
*/
class SmartImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
companion object {
//Image render mode.
const val DEFAULT_MODE_CLIP = 0
const val DEFAULT_MODE_XFERMODE = 1 //此模式目前不支持每个圆角自定义
}
/**
* painter of all drawing things
*/
private var paint = Paint()
private var modeDST_IN: Xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN)
private var modeSRC_IN: Xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
private var circleBitmap: Bitmap? = null
private var roundRect: RectF = RectF()
private var bounds: RectF = RectF()
private var strokeOffset = 0f
var clipPath = Path()
// private var raduis = 0f
/**
* Default render mode is use clip.
*/
private var renderMode: Int = DEFAULT_MODE_CLIP
//-------- PropParsers --------
private var borderProparser: ParsedStyle_Border? = null
private var borderDashPattern: ParsedStyle_Border_Dash_Pattern? = null
private var borderEffect: DashPathEffect? = null
init {
setLayerType(View.LAYER_TYPE_SOFTWARE, null)
val ta = context.obtainStyledAttributes(attrs, R.styleable.SmartImageView)
renderMode = ta.getInt(R.styleable.SmartImageView_render_mode, 0)
val smartPropParser = SmartPropParser(context, ta)
borderProparser = smartPropParser.getParsedValue<ParsedStyle_Border>(R.styleable.SmartImageView_border)
borderDashPattern = smartPropParser.getParsedValue<ParsedStyle_Border_Dash_Pattern>(R.styleable.SmartImageView_border_dash)
ta.recycle()
borderEffect = if(borderProparser == null){
null
}else{
borderDashPattern?.getEffectObject()
}
paint.style = Paint.Style.STROKE
paint.color = Color.RED
paint.isDither = true
paint.isAntiAlias = true
paint.strokeWidth = borderProparser?.size?:0f
strokeOffset = paint.strokeWidth / 2
}
private fun createCircleBitmap(): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
if(borderProparser == null){
return bitmap
}
val canvas = Canvas(bitmap)
paint.style = Paint.Style.FILL
if (borderProparser?.radiiArrayMode != false) {
clipPath.addRoundRect(
bounds,
borderProparser?.radii,
Path.Direction.CW
)
} else {
clipPath.addRoundRect(
bounds,
borderProparser?.xRadius?:0f,
borderProparser?.yRadius?:0f,
Path.Direction.CW
)
}
canvas.drawPath(clipPath, paint)
return bitmap
}
override fun onDraw(canvas: Canvas) {
bounds.set(0f, 0f, width.toFloat(), height.toFloat())
roundRect.set(
0f + strokeOffset,
0f + strokeOffset,
width.toFloat() - strokeOffset,
height.toFloat() - strokeOffset
)
if (renderMode == DEFAULT_MODE_CLIP) {
val saveLayer = canvas.saveLayer(bounds, null)
if (borderProparser?.radiiArrayMode != false) {
clipPath.addRoundRect(
bounds,
borderProparser?.radii,
Path.Direction.CW
)
}else{
clipPath.addRoundRect(
bounds,
borderProparser?.xRadius?:0f,
borderProparser?.yRadius?:0f,
Path.Direction.CW
)
}
canvas.clipPath(clipPath)
super.onDraw(canvas)
clipPath.rewind()
drawBorders(canvas)
canvas.restoreToCount(saveLayer)
} else if (renderMode == DEFAULT_MODE_XFERMODE) {
if (circleBitmap == null) {
circleBitmap = createCircleBitmap()
}
val saveLayer = canvas.saveLayer(bounds, null)
super.onDraw(canvas)
paint.xfermode = modeDST_IN
paint.style = Paint.Style.FILL
canvas.drawBitmap(circleBitmap!!, 0f, 0f, paint)
paint.xfermode = modeSRC_IN
drawBorders(canvas)
paint.xfermode = null
canvas.restoreToCount(saveLayer)
}
}
private fun drawBorders(canvas: Canvas) {
if(borderProparser == null) return
val size: Int = if (borderProparser?.size != null) {
borderProparser!!.size.toInt()
} else {
0
}
drawRectFBorder(
canvas, size,
borderProparser!!.color,
bounds,
borderProparser!!.radii
)
if (borderEffect != null) {
paint.pathEffect = null
}
}
private fun drawRectFBorder(
canvas: Canvas, borderWidth: Int,
borderColor: Int, rectF: RectF,
radii: FloatArray
) {
if (borderWidth > 0.1f && (borderColor and 0xFF000000.toInt()) != 0) {
initBorderPaint(borderWidth, borderColor)
clipPath.addRoundRect(rectF, radii, Path.Direction.CCW)
canvas.drawPath(clipPath, paint)
clipPath.reset()
}
}
private fun initBorderPaint(borderWidth: Int, borderColor: Int) {
clipPath.reset()
if(borderEffect != null){
paint.pathEffect = borderEffect
}
paint.style = Paint.Style.STROKE
paint.strokeWidth = borderWidth.toFloat() * 2
paint.color = borderColor
}
} | gpl-2.0 | d591122c09bfc2fd02dc9c3f818c8260 | 30.962963 | 131 | 0.587252 | 4.497394 | false | false | false | false |
dpisarenko/econsim-tr01 | src/main/java/cc/altruix/econsimtr01/flourprod/FlourProduction.kt | 1 | 3639 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: dp@altruix.co
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* econsim-tr01 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.flourprod
import cc.altruix.econsimtr01.*
import cc.altruix.econsimtr01.ch03.AgriculturalSimParametersProvider
import cc.altruix.econsimtr01.ch03.PropertiesFileSimParametersProvider
import cc.altruix.econsimtr01.ch03.Shack
import org.joda.time.DateTime
/**
* @author Dmitri Pisarenko (dp@altruix.co)
* @version $Id$
* @since 1.0
*/
open class FlourProduction(val simParamProv:
PropertiesFileSimParametersProvider) :
IAction {
val shack = simParamProv.agents.find { it.id() == Shack.ID }
as DefaultAgent
override fun timeToRun(time: DateTime): Boolean =
businessDay(time) &&
evenHourAndMinute(time) &&
wheatInShack(shack)
open internal fun wheatInShack(shack: DefaultAgent): Boolean {
val grainInShack =
shack.amount(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id)
val grainInputPerHour = simParamProv.data["MillThroughput"].
toString().toDouble()
return grainInShack >= grainInputPerHour
}
open internal fun evenHourAndMinute(time: DateTime): Boolean =
time.evenHourAndMinute(8, 0)
open internal fun businessDay(time: DateTime): Boolean =
time.isBusinessDay()
open override fun run(time: DateTime) {
val grainToProcess = calculateGrainToProcess()
if (grainToProcess > 0.0) {
convertGrainToFlour(grainToProcess)
}
}
open internal fun convertGrainToFlour(grainToProcess: Double) {
shack.remove(AgriculturalSimParametersProvider
.RESOURCE_SEEDS.id, grainToProcess)
val convFactor = simParamProv.data["FlourConversionFactor"]
.toString().toDouble()
val flourQuantity = grainToProcess * convFactor
shack.put(FlourProductionSimulationParametersProvider
.RESOURCE_FLOUR.id, flourQuantity)
}
open internal fun calculateGrainToProcess(): Double {
val hourlyThroughPut = simParamProv.data["MillThroughput"].toString()
.toDouble()
val maxWorkingTimePerHour = simParamProv
.data["MillMaxWorkingTimePerDay"].toString().toDouble()
val maxPossibleGrainInput = hourlyThroughPut * maxWorkingTimePerHour
val grainInShack = shack.amount(AgriculturalSimParametersProvider
.RESOURCE_SEEDS.id)
val grainToProcess = Math.min(grainInShack, maxPossibleGrainInput)
return grainToProcess
}
override fun notifySubscribers(time: DateTime) {
}
override fun subscribe(subscriber: IActionSubscriber) {
}
}
| gpl-3.0 | 3dbf0d9b525fd124ed8cb1bf2643693a | 33.330097 | 77 | 0.686727 | 4.554443 | false | false | false | false |
chemickypes/Glitchy | app/src/main/java/me/bemind/glitchlibrary/MessagingFirebase.kt | 1 | 2875 | package me.bemind.glitchlibrary
import android.util.Log
import com.google.firebase.iid.FirebaseInstanceIdService
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.firebase.iid.FirebaseInstanceId
import android.content.Context.NOTIFICATION_SERVICE
import android.app.NotificationManager
import android.media.RingtoneManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v7.app.NotificationCompat
import com.kingfisher.easy_sharedpreference_library.SharedPreferencesManager
/**
* Created by angelomoroni on 02/07/17.
*/
class GlitchyFirebaseMessagingService: FirebaseMessagingService(){
private val TAG = "GlitchyFbMsgSrv"
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
remoteMessage?.let {
Log.d(TAG, "Message Notification Body: " + it.notification?.body)
// sendNotification(it.notification.title,it.notification.body)
}
}
private fun sendNotification(title:String?,messageBody: String?) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title?:"Glitchy")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}
}
class GlitchyFirebaseInstanceIDService: FirebaseInstanceIdService() {
private val TAG = "GlitchyFbInstanceIdSrv"
override fun onTokenRefresh() {
super.onTokenRefresh()
val refreshedToken = FirebaseInstanceId.getInstance().token
Log.d(TAG, "Refreshed token: " + refreshedToken!!)
//save to SharedPReferences
try{
SharedPreferencesManager.getInstance().putValue(Constants.FIREBASE_TOKEN,refreshedToken)
}catch (e:Exception){
try {
SharedPreferencesManager.init(this.applicationContext,true)
SharedPreferencesManager.getInstance().putValue(Constants.FIREBASE_TOKEN,refreshedToken)
}catch (e1:Exception){
e1.printStackTrace()
}
}
}
} | apache-2.0 | 5618c37ec7fdf31c60b22a99b849719a | 34.073171 | 104 | 0.710609 | 4.956897 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/OoAdministerProfilePage.kt | 1 | 12798 | package alraune
import alraune.entity.*
import alraune.entity.User.ProfileState.*
import pieces100.*
import vgrechka.*
import java.sql.Timestamp
class OoAdministerProfilePage {
companion object {
val path = "/administer-profile"
fun href(user: User, amend: (GetParams) -> Unit = {}) = makeUrlPart(path) {
it.userId.set(user.id)
amend(it)
}
}
init {checkUserKind_elseBailOutToSignInOrSayKissMyAss(AlUserKind.Admin)}
val getParams = GetParams()
val user = dbSelectUserOrBailOut(getParamOrBailOut(getParams.userId))
val writer = user.writer()
init {
ooPageHeaderAndSetDocumentTitle(t("TOTE", "Юзер ${AlText.numString(user.id)}: ${user.fullNameOrEmail()}"))
val pezdal = object : Tabopezdal() {
override fun hrefThunk() = HrefThunk(path) {
it.userId.set(getParams.userId.get())
}
}
val profile = writer.profile
if (profile != null) {
exhaustive=when (profile.state) {
WaitsApproval -> oo(composeProfileWaitingOrApprovalBanner(user))
Rejected -> oo(composeProfileRejectedBanner(user, path))
Approved -> {}
Draft -> {}
Editing -> {
oo(composeUserEditsProfileBanner())
}
}
}
pezdal.tabs += Tabopezdal.Tab("Profile", t("TOTE", "Профайл"),
ooNearTabs = {
val trc = TopRightControls()
UpdateProfilePencilButton()
.also {it.hrefAfterParamsUpdated = OoAdministerProfilePage.href(user)}
.addControl(trc, user)
oo(trc.compose())
},
ooContent = {
if (profile == null) {
oo(div(t("TOTE", "Юзер не заполнял нихера свой профайл еще")))
} else {
oo(composeWriterProfile(writer))
}
})
AddProfileHistoryTab(pezdal)
pezdal.ooShit()
btfStartStalenessWatcher()
debug_showModel {
it.fart("user", user, customRender = {if (it.fieldName == "resume") "..." else null})
}
}
private fun composeUserEditsProfileBanner() = div().with {
// 038c380b-81d4-42ac-910c-83232b0d2f58
oo(div().style("""
background: ${Color.Purple50};
border-left: 3px solid ${Color.Purple300};
height: 44.4px;
margin-bottom: 1rem;
padding-left: 1rem;
padding-right: 0;
padding-top: 0.5rem;
padding-bottom: 0.5rem;
display: flex;
align-items: center;""").with {
oo(tagi().className(FA.pencilSquareO.className).style("margin-right: 0.75rem;"))
oo(div().style("flex-grow: 1;").text(t("TOTE", "Юзер редактирует профайл")))
})
}
inner class AddProfileHistoryTab(pezdal: Tabopezdal) {
var comparisonBanner: AlTag? = null
init {
pezdal.tabs += Tabopezdal.Tab("History", t("TOTE", "История"),
ooNearTabs = {
val trc = TopRightControls()
trc.addOrderingSelect()
oo(trc.compose())
},
ooContent = {
oo(!ComposeUsualHistoryTabContent(
chloe = Chloe(
entity = user,
pedro = object : Chloe.Pedro {
override val entityFKColumnInOperationTable = Operation.Meta.userId
override fun ooOperationDetails(opdata: OperationData) {
opdata as User.Operation
ooUserComparison(opdata.userBefore, opdata.userAfter)
}
})))
})
}
}
}
// ee846287-6ccd-45ee-a222-619e71a9d5d4
class debug_showModel(title: String? = null, block: (debug_showModel) -> Unit) {
init {
btfDebugExpanderBelowFooter(title = title, shit = div().with {
block(this)
})
}
fun fart(title: String, obj: Any, customRender: (FreakingToString) -> String? = {null}) {
oo(div(title).style("background: ${Color.Gray300}; font-weight: bold;"))
val dump = FreakingToString(obj,
propSource = FreakingToString.PropSource.KotlinProps,
customRender = customRender)
oo(composePreWrapDiv(dump.result).appendStyle("font-family: monospace;"))
}
}
abstract class DoRejectOrApproveProfile(val user: User, val opDescr: String): Dancer<Unit> {
abstract fun fart(profile: User.Variant.Writer.Profile, insertingOperation: BeginInsertingUserOperation)
override fun dance() {
!object : UpdateUser(user, opDescr) {
override fun specificUpdates(now: Timestamp, insertingOperation: BeginInsertingUserOperation) {
val profile = writerProfile(user)
fart(profile, insertingOperation)
}
override fun afterUpdate() {
val task = dbSelectMaybeTaskById(user.writer().profile!!.approvalTaskId!!)!!
task.status = Task.Status.Closed
rctx0.al.db2.update(task)
}
}
}
}
fun doRejectProfile(user: User, fs: RejectionFields__killme) {
!object : DoRejectOrApproveProfile(user, "Reject profile") {
override fun fart(profile: User.Variant.Writer.Profile, insertingOperation: BeginInsertingUserOperation) {
profile.state = Rejected
profile.rejectionReason = fs.reason.value()
profile.lastRejectedByOperationId = insertingOperation.operationId
}
}
}
fun doApproveProfile(user: User) {
!object : DoRejectOrApproveProfile(user, "Approve profile") {
override fun fart(profile: User.Variant.Writer.Profile, insertingOperation: BeginInsertingUserOperation) {
profile.state = Approved
profile.rejectionReason = null
profile.wasRejectionReason = null
}
}
}
fun writerProfile(user: User): User.Variant.Writer.Profile {
val writer = user.writer()
return writer.profile!!
}
class UpdateProfilePencilButton : PencilButton<User>({imf()}) {
var hrefAfterParamsUpdated by notNullOnce<String>()
override fun makeFields() = WriterProfileFields()
override fun fieldSource(entity: User): FieldSource {
val profile = entity.writer().profile
return when {
profile != null -> FieldSource.DB(profile.fields)
else -> FieldSource.Initial()
}
}
override fun composeParamsModalBody(fields: BunchOfFields) =
composeWriterProfileForm(fields as WriterProfileFields, notYetSubmittingNotice = false)
override fun updateEntityParams(fields: BunchOfFields, forceOverwriteStale: Boolean) {
ConceptIndex_Pile.updateProfile
!DoUpdateWriterProfile(DoUpdateWriterProfile.Kind.Edit, entity, fields as WriterProfileFields)
}
override fun hrefAfterParamsUpdated() = hrefAfterParamsUpdated
override fun makeMidAirComparisonPageHref(ourFields: BunchOfFields): String {
ConceptIndex_Debug.genericDebugCode
val captureTestThunkVariant: String = null // "2"
?: return _makeMidAirComparisonPageHref(ourFields)
val file = tests.test1.thunkFile(captureTestThunkVariant)
file.writeText(AlGlobal0.xstream.toXML(tests.test1.Thunk(
receiver = this,
ourFields = ourFields)))
die("Captured test thunk to ${file.path}")
}
fun _makeMidAirComparisonPageHref(ourFields: BunchOfFields) = makeUsualMidAirComparisonPageHref_updatingUpdated {
imf()
updateEntityParams(ourFields, forceOverwriteStale = true)
val user1 = dbSelectUserOrBailOut(entity.id)
val user2 = entity
ooUserComparison(user1, user2)
}
object tests {
object test1 {
val name = this::class.qualifiedName!!.substring(this::class.java.`package`.name.length + 1)
fun thunkFile(variant: String) = AlDebug.tempFile("$name-$variant.xml")
class Thunk(
val receiver: UpdateProfilePencilButton,
val ourFields: BunchOfFields)
fun dance() {
val variant = GetParams().variant.get() ?: "default"
val file = thunkFile(variant)
if (!file.exists())
bailOutToLittleErrorPage("I want file ${file.path}")
val thunk: Thunk = AlGlobal0.xstream.fromXML(file).cast()
spitWindowOpenPage(thunk.receiver._makeMidAirComparisonPageHref(thunk.ourFields))
}
}
}
}
fun composeProfileWaitingOrApprovalBanner(user: User) = !object : ComposeWaitingOrApprovalBanner(
acceptButtonTitle = t("TOTE", "Принять"),
entityKindTitle = "заказ",
rejectButtonTitle = t("TOTE", "Завернуть"),
messageForUser = {t("TOTE", "Мы проверяем профайл и скоро с тобой свяжемся")},
questionForAdmin = {div().with {
oo(span(t("TOTE", "Что решаем по этому засранцу?")))
val taskId = user.writer().profile!!.approvalTaskId!!
oo(ComposeChevronLink.preset1("Это задача ${AlText.numString(taskId)}", OoAdminOneTaskPage.href(taskId)))
}}) {
override fun serveApproval() {
ConceptIndex_Pile.approveProfile
doApproveProfile(user)
btfEval(jsProgressyNavigate(OoAdministerProfilePage.href(user)))
}
override fun wasRejectionReason() = writerProfile(user).wasRejectionReason
override fun serveRejection(fs: RejectionFields__killme) {
ConceptIndex_Pile.rejectProfile
doRejectProfile(user, fs)
btfEval(jsProgressyNavigate(OoAdministerProfilePage.href(user)))
}
override fun composeBelowMessage(): AlTag? {
val profile = writerProfile(user)
val wasRejectionReason = wasRejectionReason()
if (!wasRejectionReason.isNullOrBlank()) {
return div().with {
oo(div().with {
oo(label().add(t("TOTE", "До этого профайл был завернут по причине")).style("text-decoration: underline;"))
val lastRejectedByOperationId = profile.lastRejectedByOperationId
ooWhatChangedLink(lastRejectedByOperationId!!)
})
oo(composePreWrapDiv(wasRejectionReason()!!))
}
}
val unlockedOpId = profile.lastUnlockedForEditingByOperationId
if (unlockedOpId != null) {
return div().with {
oo(label().add(t("TOTE", "Редактирование было начато операцией ${AlText.operationId(unlockedOpId)}")))
ooWhatChangedLink(unlockedOpId)
}
}
return null
}
fun ooWhatChangedLink(operationId1: Long) {
oo(ComposeChevronLink(
title = t("TOTE", "Что изменилось с того времени?"),
href = SpitCompareOperationsPage__killme.href(
id1 = operationId1,
id2 = user.data.lastOperationId))
.WithLeftMargin().newTab())
}
}
fun makeUsualMidAirComparisonPageHref_updatingUpdated(block: () -> Unit) = makeUsualMidAirComparisonPageHref0(
pageTitle = t("TOTE", "Сравниваем хрень"),
dataBeforeTitle = t("TOTE", "Сейчас в базе"),
dataAfterTitle = t("TOTE", "Мы хотим"),
block = block)
fun makeUsualMidAirComparisonPageHref_deletingUpdated(block: () -> Unit) = makeUsualMidAirComparisonPageHref0(
pageTitle = t("TOTE", "Что изменилось, пока мы не видели"),
dataBeforeTitle = t("TOTE", "Наше устаревшее"),
dataAfterTitle = t("TOTE", "Сейчас в базе"),
block = block)
fun makeUsualMidAirComparisonPageHref0(pageTitle: String, dataBeforeTitle: String, dataAfterTitle: String, block: () -> Unit): String {
return AdHocPage.makeAdHocPageHref {
// febb703a-7de6-4551-970b-251db40b3969
spitFreakingPage {
val c1 = Context1.get()
c1.skipWritingToDatabase = true
c1.propComparison.text.let {
it.before = dataBeforeTitle
it.after = dataAfterTitle
}
ooPageHeaderAndSetDocumentTitle(pageTitle)
block()
}
}
}
| apache-2.0 | 95320a5aa8cd6bf2e4fc47d9904cf471 | 33.217033 | 135 | 0.601365 | 4.122807 | false | false | false | false |
androidx/androidx | compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/DemoSettingsActivity.kt | 3 | 2328 | /*
* Copyright 2020 The Android Open Source Project
*
* 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.
*/
package androidx.compose.integration.demos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.integration.demos.DemoSettingsActivity.SettingsFragment
import androidx.compose.integration.demos.settings.DecorFitsSystemWindowsSetting
import androidx.compose.integration.demos.settings.DynamicThemeSetting
import androidx.compose.integration.demos.settings.SoftInputModeSetting
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.plusAssign
private val allSettings = listOf(
DynamicThemeSetting,
SoftInputModeSetting,
DecorFitsSystemWindowsSetting,
)
/**
* Shell [AppCompatActivity] around [SettingsFragment], as we need a FragmentActivity subclass
* to host the [SettingsFragment].
*/
class DemoSettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager
.beginTransaction()
.replace(android.R.id.content, SettingsFragment())
.commit()
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
val context = preferenceManager.context
val screen = preferenceManager.createPreferenceScreen(context)
val general = PreferenceCategory(context).apply {
title = "General options"
screen += this
}
allSettings.forEach {
general += it.createPreference(context)
}
preferenceScreen = screen
}
}
} | apache-2.0 | cd99a676a3ddbb0a2158482035f9ac39 | 34.830769 | 94 | 0.728952 | 5.266968 | false | false | false | false |
androidx/androidx | profileinstaller/integration-tests/init-macrobenchmark/src/androidTest/java/androidx/profileinstaller/integration/macrobenchmark/ProfileinstallerStartupBenchmark.kt | 3 | 1800 | /*
* Copyright 2021 The Android Open Source Project
*
* 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.
*/
package androidx.profileinstaller.integration.macrobenchmark
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.filters.LargeTest
import androidx.testutils.createStartupCompilationParams
import androidx.testutils.measureStartup
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
class ProfileinstallerStartupBenchmark(
private val startupMode: StartupMode,
private val compilationMode: CompilationMode
) {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun startup() = benchmarkRule.measureStartup(
compilationMode = compilationMode,
startupMode = startupMode,
packageName = "androidx.profileinstaller.integration.macrobenchmark.target"
) {
action = "profileinstaller.init.macrobenchmark.TARGET"
}
companion object {
@Parameterized.Parameters(name = "startup={0},compilation={1}")
@JvmStatic
fun parameters() = createStartupCompilationParams()
}
} | apache-2.0 | d90a52c73180c6d46a157316a2a6f6ac | 32.981132 | 83 | 0.761111 | 4.699739 | false | true | false | false |
Meisolsson/PocketHub | app/src/main/java/com/github/pockethub/android/ui/helpers/PagedListFetcher.kt | 1 | 3748 | package com.github.pockethub.android.ui.helpers
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.pockethub.android.R
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.meisolsson.githubsdk.model.Page
import com.xwray.groupie.Item
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
import retrofit2.Response
class PagedListFetcher<E>(
private val swipeRefreshLayout: SwipeRefreshLayout?,
private val lifecycle: Lifecycle,
private val itemListHandler: ItemListHandler,
private val showError: (Throwable) -> Unit,
private val loadPage: (page: Int) -> Single<Response<Page<E>>>,
private val createItem: (item: E) -> Item<*>
): LifecycleObserver {
/**
* Disposable for data load request.
*/
private var dataLoadDisposable: Disposable = Disposables.disposed()
private var isLoading = false
var hasMore: Boolean = true
var onPageLoaded: (MutableList<Item<*>>) -> MutableList<Item<*>> = { items -> items }
/**
* The current page.
*/
private var page: Int = 1
init {
lifecycle.addObserver(this)
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setOnRefreshListener(this::refresh)
swipeRefreshLayout.setColorSchemeResources(
R.color.pager_title_background_top_start,
R.color.pager_title_background_end,
R.color.text_link,
R.color.pager_title_background_end)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun onStart() {
refresh()
}
fun refresh() {
page = 1
hasMore = true
isLoading = false
if (swipeRefreshLayout != null) {
swipeRefreshLayout.isRefreshing = true
}
fetchPage()
}
fun fetchNext() {
if (!isLoading) {
page++
fetchPage()
}
}
private fun fetchPage() {
if (isLoading) {
return
}
if (!dataLoadDisposable.isDisposed) {
dataLoadDisposable.dispose()
}
isLoading = true
dataLoadDisposable = loadPage(page)
.map { it.body() }
.map { page ->
hasMore = page.next() != null
page
}
.flatMap { page ->
Observable.fromIterable<E>(page.items())
.map<Item<*>> { this.createItem(it) }
.toList()
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle<MutableList<Item<*>>>(lifecycle))
.subscribe(
{ this.onDataLoaded(it) },
{ this.onDataLoadError(it) }
)
}
private fun onDataLoaded(newItems: MutableList<Item<*>>) {
isLoading = false
if (swipeRefreshLayout != null) {
swipeRefreshLayout.isRefreshing = false
}
val items = onPageLoaded(newItems)
if (page == 1) {
itemListHandler.update(items)
} else {
itemListHandler.addItems(items)
}
}
private fun onDataLoadError(throwable: Throwable) {
isLoading = false
if (swipeRefreshLayout != null) {
swipeRefreshLayout.isRefreshing = false
}
showError(throwable)
}
} | apache-2.0 | 6e2661cd00e32a822af6c6dbdd81a6d7 | 27.18797 | 89 | 0.605656 | 4.970822 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/light/LightGitTracker.kt | 4 | 9604 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.light
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.lightEdit.LightEditorInfo
import com.intellij.ide.lightEdit.LightEditorListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationActivationListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.wm.IdeFrame
import com.intellij.util.EventDispatcher
import com.intellij.vcs.log.BaseSingleTaskController
import com.intellij.vcs.log.runInEdt
import com.intellij.vcs.log.sendRequests
import com.intellij.vcsUtil.VcsUtil
import git4idea.config.GitExecutable
import git4idea.config.GitExecutableManager
import git4idea.config.GitVersionIdentificationException
import git4idea.index.LightFileStatus
import git4idea.index.getFileStatus
import git4idea.util.lastInstance
import git4idea.util.toShortenedLogString
import git4idea.util.without
import org.jetbrains.annotations.NonNls
import java.util.*
private val LOG = Logger.getInstance("#git4idea.light.LightGitTracker")
class LightGitTracker : Disposable {
private val disposableFlag = Disposer.newCheckedDisposable()
private val lightEditService = LightEditService.getInstance()
private val lightEditorManager = lightEditService.editorManager
private val eventDispatcher = EventDispatcher.create(LightGitTrackerListener::class.java)
private val singleTaskController = MySingleTaskController()
private val listener = MyLightEditorListener()
private val highlighterManager: LightGitEditorHighlighterManager
val gitExecutable: GitExecutable
get() = GitExecutableManager.getInstance().getExecutable(null)
@Volatile
private var hasGit: Boolean = false
@Volatile
private var state: State = State.Blank
val currentLocation: String?
get() = state.location
val statuses: Map<VirtualFile, LightFileStatus>
get() = state.statuses
init {
lightEditorManager.addListener(listener, this)
ApplicationManager.getApplication().messageBus.connect(this).subscribe(ApplicationActivationListener.TOPIC,
MyFrameStateListener())
ApplicationManager.getApplication().messageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES,
MyBulkFileListener())
highlighterManager = LightGitEditorHighlighterManager(this)
Disposer.register(this, disposableFlag)
singleTaskController.request(Request.CheckGit)
runInEdt(disposableFlag) {
singleTaskController.sendRequests(locationRequest(lightEditService.selectedFile),
statusRequest(lightEditorManager.openFiles))
}
}
fun getFileStatus(file: VirtualFile): LightFileStatus {
return state.statuses[file] ?: LightFileStatus.Blank
}
private fun updateCurrentState(updater: StateUpdater) {
when (updater) {
StateUpdater.Clear -> {
val previousStatuses = state.statuses
val statusesChanged = previousStatuses.isNotEmpty() && previousStatuses.values.any { it != LightFileStatus.Blank }
val changed = statusesChanged || !(state.location.isNullOrBlank())
state = State.Blank
if (changed) eventDispatcher.multicaster.update()
if (statusesChanged) lightEditService.updateFileStatus(previousStatuses.keys)
}
is StateUpdater.Update -> {
val newState = updater.state
val statusesMap = lightEditorManager.openFiles.associateWith {
newState.statuses[it] ?: state.statuses[it] ?: LightFileStatus.Blank
}
val location = if (updater.updateLocation) newState.location else state.location
state = State(location, statusesMap)
eventDispatcher.multicaster.update()
if (newState.statuses.isNotEmpty()) lightEditService.updateFileStatus(newState.statuses.keys)
}
}
}
private fun checkGit() {
try {
val version = GitExecutableManager.getInstance().identifyVersion(gitExecutable)
hasGit = version.isSupported
}
catch (e: GitVersionIdentificationException) {
LOG.warn(e)
hasGit = false
}
}
private fun locationRequest(file: VirtualFile?): Request? {
if (file != null && file.parent != null) {
return Request.Location(file)
}
return null
}
private fun statusRequest(files: Collection<VirtualFile?>): Request? {
val filesForRequest = mutableListOf<VirtualFile>()
for (file in files) {
if (file?.parent != null) {
filesForRequest.add(file)
}
}
if (filesForRequest.isEmpty()) return null
return Request.Status(filesForRequest)
}
fun addUpdateListener(listener: LightGitTrackerListener, parent: Disposable) {
eventDispatcher.addListener(listener, parent)
}
override fun dispose() {
}
private inner class MyBulkFileListener : BulkFileListener {
override fun after(events: List<VFileEvent>) {
if (!hasGit) return
val targetFiles = events.filter { it.isFromSave || it.isFromRefresh }.mapNotNullTo(mutableSetOf()) { it.file }
singleTaskController.sendRequests(statusRequest(lightEditorManager.openFiles.intersect(targetFiles)))
}
}
private inner class MyFrameStateListener : ApplicationActivationListener {
override fun applicationActivated(ideFrame: IdeFrame) {
singleTaskController.sendRequests(Request.CheckGit,
locationRequest(lightEditService.selectedFile),
statusRequest(lightEditorManager.openFiles))
}
}
private inner class MyLightEditorListener : LightEditorListener {
override fun afterSelect(editorInfo: LightEditorInfo?) {
if (!hasGit) return
state = state.copy(location = null)
val selectedFile = editorInfo?.file
if (!singleTaskController.sendRequests(locationRequest(selectedFile), statusRequest(listOf(selectedFile)))) {
runInEdt(disposableFlag) { eventDispatcher.multicaster.update() }
}
}
override fun afterClose(editorInfo: LightEditorInfo) {
state = state.copy(statuses = state.statuses.without(editorInfo.file))
}
}
private inner class MySingleTaskController :
BaseSingleTaskController<Request, StateUpdater>("light.tracker", this::updateCurrentState, disposableFlag) {
override fun process(requests: List<Request>, previousResult: StateUpdater?): StateUpdater {
if (requests.contains(Request.CheckGit)) {
checkGit()
}
if (!hasGit) return StateUpdater.Clear
val locationFile = requests.lastInstance(Request.Location::class.java)?.file
val files = requests.filterIsInstance(Request.Status::class.java).flatMapTo(mutableSetOf()) { it.files }
val location: String? = if (locationFile != null) {
try {
getLocation(locationFile.parent, gitExecutable)
}
catch (_: VcsException) {
null
}
}
else previousResult?.state?.location
val updateLocation = locationFile != null || (previousResult as? StateUpdater.Update)?.updateLocation ?: false
val statuses = mutableMapOf<VirtualFile, LightFileStatus>()
previousResult?.state?.statuses?.let { statuses.putAll(it) }
for (file in files) {
try {
if (file != locationFile || location != null) {
statuses[file] = getFileStatus(file.parent, VcsUtil.getFilePath(file), gitExecutable)
}
}
catch (_: VcsException) {
}
}
return StateUpdater.Update(State(location, statuses), updateLocation)
}
}
private data class State(val location: String?, val statuses: Map<VirtualFile, LightFileStatus>) {
private constructor() : this(null, emptyMap())
companion object {
val Blank = State()
}
@NonNls
override fun toString(): @NonNls String {
return "State(location=$location, statuses=${statuses.toShortenedLogString()})"
}
}
private sealed class StateUpdater(val state: State) {
object Clear : StateUpdater(State.Blank) {
override fun toString(): @NonNls String = "Clear"
}
class Update(s: State, val updateLocation: Boolean) : StateUpdater(s) {
override fun toString(): @NonNls String {
return "Update(state=$state, updateLocation=$updateLocation)"
}
}
}
private sealed class Request {
class Location(val file: VirtualFile) : Request() {
override fun toString(): @NonNls String {
return "Location(file=$file)"
}
}
@NonNls
class Status(val files: Collection<VirtualFile>) : Request() {
override fun toString(): @NonNls String {
return "Status(files=${files.toShortenedLogString()}"
}
}
object CheckGit : Request() {
override fun toString(): @NonNls String = "CheckGit"
}
}
companion object {
fun getInstance(): LightGitTracker {
return ApplicationManager.getApplication().getService(LightGitTracker::class.java)
}
}
}
interface LightGitTrackerListener : EventListener {
fun update()
} | apache-2.0 | b521d98e8bf3ee3ff151c9f1b66fa070 | 34.70632 | 140 | 0.707414 | 4.782869 | false | false | false | false |
siosio/intellij-community | platform/lang-api/src/com/intellij/execution/runToolbar/RunToolbarRunProcess.kt | 1 | 834 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.execution.ExecutionBundle
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.ui.JBColor
class RunToolbarRunProcess : RunToolbarProcess {
override val ID: String = ToolWindowId.RUN
override val executorId: String = ToolWindowId.RUN
override val name: String = ExecutionBundle.message("run.toolbar.run")
override val actionId: String = "RunToolbarRunProcess"
override val moreActionSubGroupName: String = "RunToolbarRunMoreActionSubGroupName"
override val showInBar: Boolean = true
override val pillColor: JBColor = JBColor.namedColor("RunToolbar.Run.activeBackground", JBColor(0xBAEEBA, 0xBAEEBA))
} | apache-2.0 | 9b50576e007d41330bb565e8dfc2bf91 | 42.947368 | 140 | 0.803357 | 4.255102 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/decompiledDeclarations/KtLightEnumEntryForDecompiledDeclaration.kt | 2 | 2081 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.lightClasses.decompiledDeclarations
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.idea.caches.lightClasses.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.idea.caches.lightClasses.LightMemberOriginForCompiledField
import org.jetbrains.kotlin.idea.decompiler.classFile.KtClsFile
internal class KtLightEnumEntryForDecompiledDeclaration(
private val fldDelegate: PsiEnumConstant,
fldParent: KtLightClassForDecompiledDeclaration,
lightMemberOrigin: LightMemberOriginForCompiledField,
file: KtClsFile,
) : KtLightFieldForDecompiledDeclaration(
fldDelegate,
fldParent,
lightMemberOrigin
), PsiEnumConstant {
private val _initializingClass: PsiEnumConstantInitializer? by lazyPub {
fldDelegate.initializingClass?.let {
KtLightEnumClassForDecompiledDeclaration(
psiConstantInitializer = it,
enumConstant = this,
clsParent = fldParent,
file = file,
kotlinOrigin = null
)
}
}
override fun getArgumentList(): PsiExpressionList? = fldDelegate.argumentList
override fun resolveConstructor(): PsiMethod? = fldDelegate.resolveConstructor()
override fun resolveMethod(): PsiMethod? = fldDelegate.resolveMethod()
override fun resolveMethodGenerics(): JavaResolveResult = fldDelegate.resolveMethodGenerics()
override fun getInitializingClass(): PsiEnumConstantInitializer? = _initializingClass
override fun getOrCreateInitializingClass(): PsiEnumConstantInitializer =
_initializingClass ?: error("cannot create initializing class in light enum constant")
override fun equals(other: Any?): Boolean = other is KtLightEnumEntryForDecompiledDeclaration && super.equals(other)
override fun hashCode(): Int = super.hashCode()
} | apache-2.0 | 0b94b57eae456de9fcf141755e4e997f | 46.318182 | 158 | 0.760692 | 5.461942 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/experimental/toolbar/ExperimentalToolbarSettings.kt | 4 | 3180 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui.experimental.toolbar
import com.intellij.application.options.RegistryManager
import com.intellij.ide.ui.ExperimentalToolbarSettingsState
import com.intellij.ide.ui.ToolbarSettings
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
import org.jetbrains.annotations.ApiStatus
private const val REGISTRY_KEY = "ide.widget.toolbar"
private val logger = logger<ExperimentalToolbarSettings>()
@ApiStatus.Experimental
@State(name = "ToolbarSettingsService", storages = [(Storage(StoragePathMacros.NON_ROAMABLE_FILE))])
internal class ExperimentalToolbarSettings private constructor() : ToolbarSettings, UISettingsListener, Disposable {
private var toolbarState = ExperimentalToolbarSettingsState()
init {
ApplicationManager.getApplication().messageBus.connect(this).subscribe(UISettingsListener.TOPIC, this)
}
@Suppress("unused")
private class ToolbarRegistryListener : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) {
if (value.key != REGISTRY_KEY) {
return
}
val booleanValue = value.asBoolean()
logger.info("New registry value: $booleanValue")
ToolbarSettings.getInstance().isVisible = booleanValue
val uiSettings = UISettings.getInstance()
uiSettings.showNavigationBar = !booleanValue && uiSettings.showNavigationBar
uiSettings.fireUISettingsChanged()
}
}
override fun getState(): ExperimentalToolbarSettingsState = toolbarState
override fun loadState(state: ExperimentalToolbarSettingsState) {
toolbarState = state
}
override fun dispose() {}
override var isEnabled: Boolean
get() = RegistryManager.getInstance().`is`(REGISTRY_KEY)
set(value) = RegistryManager.getInstance().get(REGISTRY_KEY).setValue(value)
override var isVisible: Boolean
get() = toolbarState.showNewMainToolbar
set(value) {
toolbarState.showNewMainToolbar = value
hideClassicMainToolbarAndNavbarIfVisible()
}
override fun uiSettingsChanged(uiSettings: UISettings) {
logger.info("Dispatching UI settings change.")
hideClassicMainToolbarIfVisible()
}
private fun hideClassicMainToolbarIfVisible() {
if (isVisible) {
logger.info("Hiding Main Toolbar (Classic) because the new toolbar is visible.")
UISettings.getInstance().showMainToolbar = false
}
}
private fun hideClassicMainToolbarAndNavbarIfVisible() {
if (isVisible) {
hideClassicMainToolbarIfVisible()
logger.info("Hiding NavBar because the new toolbar is visible.")
UISettings.getInstance().showNavigationBar = false
}
}
}
| apache-2.0 | e369d49ec90ca5a1cca23488ef0f7aa2 | 35.976744 | 120 | 0.774214 | 4.825493 | false | false | false | false |
jwren/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/DeclarationAndUsagesLesson.kt | 5 | 5848 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson.general.navigation
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.find.FindBundle
import com.intellij.find.FindSettings
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.content.BaseLabel
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.ui.UIBundle
import com.intellij.ui.table.JBTable
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.util.isToStringContains
abstract class DeclarationAndUsagesLesson
: KLesson("Declaration and usages", LessonsBundle.message("declaration.and.usages.lesson.name")) {
abstract fun LessonContext.setInitialPosition()
abstract override val sampleFilePath: String
abstract val entityName: String
override val lessonContent: LessonContext.() -> Unit
get() = {
sdkConfigurationTasks()
setInitialPosition()
prepareRuntimeTask {
val focusManager = IdeFocusManager.getInstance(project)
if (focusManager.focusOwner != editor.contentComponent) {
focusManager.requestFocus(editor.contentComponent, true)
}
}
task("GotoDeclaration") {
text(LessonsBundle.message("declaration.and.usages.jump.to.declaration", action(it)))
trigger(it, { state() }) { before, _ ->
before != null && !isInsidePsi(before.target.navigationElement, before.position)
}
restoreIfModifiedOrMoved()
test { actions(it) }
}
task("GotoDeclaration") {
text(LessonsBundle.message("declaration.and.usages.show.usages", action(it)))
trigger(it, { state() }) l@{ before, now ->
if (before == null || now == null) {
return@l false
}
val navigationElement = before.target.navigationElement
return@l navigationElement == now.target.navigationElement &&
isInsidePsi(navigationElement, before.position) &&
!isInsidePsi(navigationElement, now.position)
}
restoreIfModifiedOrMoved()
test {
actions(it)
ideFrame {
waitComponent(JBTable::class.java, "ShowUsagesTable")
invokeActionViaShortcut("ENTER")
}
}
}
task("FindUsages") {
before {
closeAllFindTabs()
}
text(LessonsBundle.message("declaration.and.usages.find.usages", action(it)))
triggerAndFullHighlight().component { ui: BaseLabel ->
ui.javaClass.simpleName == "ContentTabLabel" && ui.text.isToStringContains(entityName)
}
restoreIfModifiedOrMoved()
test {
actions(it)
}
}
val pinTabText = UIBundle.message("tabbed.pane.pin.tab.action.name")
task {
test {
ideFrame {
previous.ui?.let { usagesTab -> jComponent(usagesTab).rightClick() }
}
}
triggerAndBorderHighlight().component { ui: ActionMenuItem ->
ui.text.isToStringContains(pinTabText)
}
restoreByUi()
text(LessonsBundle.message("declaration.and.usages.pin.motivation", strong(UIBundle.message("tool.window.name.find"))))
text(LessonsBundle.message("declaration.and.usages.right.click.tab",
strong(FindBundle.message("find.usages.of.element.in.scope.panel.title",
entityName, FindSettings.getInstance().defaultScopeName))))
}
task("PinToolwindowTab") {
trigger(it)
restoreByUi()
text(LessonsBundle.message("declaration.and.usages.select.pin.item", strong(pinTabText)))
test {
ideFrame {
jComponent(previous.ui!!).click()
}
}
}
task("HideActiveWindow") {
text(LessonsBundle.message("declaration.and.usages.hide.view", action(it)))
checkToolWindowState("Find", false)
test { actions(it) }
}
actionTask("ActivateFindToolWindow") {
LessonsBundle.message("declaration.and.usages.open.find.view",
action(it), strong(UIBundle.message("tool.window.name.find")))
}
}
private fun TaskRuntimeContext.state(): MyInfo? {
val flags = TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED
val currentEditor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
val target = TargetElementUtil.findTargetElement(currentEditor, flags) ?: return null
val file = PsiDocumentManager.getInstance(project).getPsiFile(currentEditor.document) ?: return null
val position = MyPosition(file,
currentEditor.caretModel.offset)
return MyInfo(target, position)
}
private fun isInsidePsi(psi: PsiElement, position: MyPosition): Boolean {
return psi.containingFile == position.file && psi.textRange.contains(position.offset)
}
private data class MyInfo(val target: PsiElement, val position: MyPosition)
private data class MyPosition(val file: PsiFile, val offset: Int)
override val suitableTips = listOf("GoToDeclaration", "ShowUsages")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("declaration.and.usages.help.link"),
LessonUtil.getHelpLink("navigating-through-the-source-code.html#go_to_declaration")),
)
}
| apache-2.0 | e6f8bf01fd7619423c9636a74d115fd7 | 36.729032 | 140 | 0.669289 | 4.829067 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/packaging/repository/PyPackageRepositoryUtil.kt | 2 | 1660 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("PyPackageRepositoryUtil")
package com.jetbrains.python.packaging.repository
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.RequestBuilder
import org.jetbrains.annotations.ApiStatus
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.util.*
@ApiStatus.Experimental
internal fun RequestBuilder.withBasicAuthorization(repository: PyPackageRepository?): RequestBuilder {
if (repository == null) return this
val password = repository.getPassword()
if (repository.login != null && password != null) {
val credentials = Base64.getEncoder().encode("${repository.login}:${password}".toByteArray()).toString(StandardCharsets.UTF_8)
this.tuner { connection -> connection.setRequestProperty("Authorization", "Basic $credentials") }
}
return this
}
@ApiStatus.Experimental
internal fun PyPackageRepository.checkValid(): Boolean {
return HttpRequests
.request(repositoryUrl!!)
.withBasicAuthorization(this)
.connectTimeout(3000)
.throwStatusCodeException(false)
.tryConnect() == 200
}
@ApiStatus.Experimental
internal fun encodeCredentialsForUrl(login: String, password: String): String {
return "${URLEncoder.encode(login, StandardCharsets.UTF_8)}:${URLEncoder.encode(password, StandardCharsets.UTF_8)}"
}
@ApiStatus.Experimental
object PyEmptyPackagePackageRepository : PyPackageRepository("empty repository", "", "")
@ApiStatus.Experimental
object PyPIPackageRepository : PyPackageRepository("PyPI", "https://pypi.python.org/simple", "") | apache-2.0 | 424221eae463aafd176fc310405f9469 | 38.547619 | 130 | 0.780723 | 4.486486 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/checkers/NamedParamAnnotationChecker.kt | 12 | 1267 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator.checkers
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.util.Pair
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.GROOVY_TRANSFORM_NAMED_PARAM
class NamedParamAnnotationChecker : CustomAnnotationChecker() {
override fun checkArgumentList(holder: AnnotationHolder, annotation: GrAnnotation): Boolean {
if (GROOVY_TRANSFORM_NAMED_PARAM != annotation.qualifiedName) return false
val annotationClass = ResolveUtil.resolveAnnotation(annotation) ?: return false
val r: Pair<PsiElement, String>? = checkAnnotationArguments(annotationClass, annotation.parameterList.attributes, false)
if (r?.getFirst() != null) {
val message = r.second // NON-NLS
holder.newAnnotation(HighlightSeverity.ERROR, message).range(r.first).create()
}
return true
}
}
| apache-2.0 | 96a17d5d70407e4e04bc7db32e272cf8 | 51.791667 | 140 | 0.797948 | 4.414634 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/navtab/MoreBottomSheetLoggedOutFragmentUnitTests.kt | 1 | 2421 | package fr.free.nrw.commons.navtab
import android.content.Context
import android.os.Looper
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.profile.ProfileActivity
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class MoreBottomSheetLoggedOutFragmentUnitTests {
private lateinit var fragment: MoreBottomSheetLoggedOutFragment
private lateinit var context: Context
@Before
fun setUp() {
context = RuntimeEnvironment.application.applicationContext
val activity = Robolectric.buildActivity(ProfileActivity::class.java).create().get()
fragment = MoreBottomSheetLoggedOutFragment()
val fragmentManager: FragmentManager = activity.supportFragmentManager
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(fragment, null)
fragmentTransaction.commit()
}
@Test
@Throws(Exception::class)
fun checkFragmentNotNull() {
Assert.assertNotNull(fragment)
}
@Test
@Throws(Exception::class)
fun testOnTutorialClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onTutorialClicked()
}
@Test
@Throws(Exception::class)
fun testOnSettingsClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onSettingsClicked()
}
@Test
@Throws(Exception::class)
fun testOnAboutClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onAboutClicked()
}
@Test
@Throws(Exception::class)
fun testOnFeedbackClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onFeedbackClicked()
}
@Test
@Throws(Exception::class)
fun testOnLogoutClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onLogoutClicked()
}
} | apache-2.0 | f34a84c7ff3c856f226f0e0cddfc9634 | 27.833333 | 92 | 0.736886 | 4.842 | false | true | false | false |
mhshams/yekan | kotlin-examples/src/main/kotlin/io/vertx/lang/kotlin/example/core/http/upload/ClientServer.kt | 2 | 1910 | package io.vertx.lang.kotlin.example.core.http.upload
import io.vertx.kotlin.core.Vertx
import io.vertx.kotlin.core.streams.Pump
import io.vertx.lang.kotlin.KotlinVerticle
import io.vertx.lang.kotlin.example.utils.deployCallback
import java.util.UUID
fun main(args: Array<String>) {
val vertx = Vertx.vertx()
vertx.deployVerticle(Server(), { deployCallback(vertx, Client(), it) })
}
class Server : KotlinVerticle() {
override fun start() {
vertx.createHttpServer().requestHandler { request ->
request.pause()
val filename = "${UUID.randomUUID()}.uploaded"
vertx.fileSystem().open(filename, mapOf()) { ares ->
val file = ares.result()
val pump = Pump.pump(request, file)
request.endHandler {
file.close {
println("Uploaded to $filename")
request.response().end()
}
}
pump.start()
request.resume()
}
}.listen(8080)
}
}
class Client : KotlinVerticle() {
override fun start() {
val request = vertx.createHttpClient(mapOf()).put(8080, "localhost", "/someurl") { response ->
println("Response ${response.statusCode()}")
}
val filename = "io/vertx/lang/kotlin/example/core/http/upload/upload.txt"
val filesystem = vertx.fileSystem()
filesystem.props(filename) { ares ->
val props = ares.result()
println("props is $props")
request.headers().set("content-length", props.size().toString())
filesystem.open(filename, mapOf()) { ares2 ->
val file = ares2.result()
val pump = Pump.pump(file, request)
file.endHandler { request.end() }
pump.start()
}
}
}
}
| apache-2.0 | b4547406a5b22ef6e4a79d38f8cd2ba0 | 30.833333 | 102 | 0.553927 | 4.431555 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/quiz/QuizActivityUnitTest.kt | 1 | 3178 | package fr.free.nrw.commons.quiz
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.RadioButton
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.soloader.SoLoader
import fr.free.nrw.commons.R
import fr.free.nrw.commons.TestCommonsApplication
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.powermock.api.mockito.PowerMockito.mock
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
class QuizActivityUnitTest {
private val SAMPLE_ALERT_TITLE_VALUE = "Title"
private val SAMPLE_ALERT_MESSAGE_VALUE = "Message"
private lateinit var activity: QuizActivity
private lateinit var positiveAnswer: RadioButton
private lateinit var negativeAnswer: RadioButton
private lateinit var view: View
private lateinit var context: Context
@Mock
private lateinit var quizController: QuizController
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
SoLoader.setInTestMode()
Fresco.initialize(RuntimeEnvironment.application.applicationContext)
activity = Robolectric.buildActivity(QuizActivity::class.java).create().get()
context = mock(Context::class.java)
view = LayoutInflater.from(activity)
.inflate(R.layout.answer_layout, null) as View
Mockito.`when`(context.getString(Mockito.any(Int::class.java)))
.thenReturn("")
quizController = QuizController()
quizController.initialize(context)
positiveAnswer = view.findViewById(R.id.quiz_positive_answer)
negativeAnswer = view.findViewById(R.id.quiz_negative_answer)
activity.positiveAnswer = positiveAnswer
activity.negativeAnswer = negativeAnswer
}
@Test
@Throws(Exception::class)
fun checkActivityNotNull() {
Assert.assertNotNull(activity)
Assert.assertNotNull(positiveAnswer)
Assert.assertNotNull(negativeAnswer)
}
@Test
@Throws(Exception::class)
fun testSetNextQuestionCaseDefault() {
activity.setNextQuestion()
}
@Test
@Throws(Exception::class)
fun testSetNextQuestion() {
activity.negativeAnswer.isChecked = true
activity.setNextQuestion()
}
@Test
@Throws(Exception::class)
fun testOnBackPressed() {
activity.onBackPressed()
}
@Test
@Throws(Exception::class)
fun testEvaluateScore() {
Whitebox.setInternalState(activity, "quiz", quizController.getQuiz())
Whitebox.setInternalState(activity, "questionIndex", 0)
activity.evaluateScore()
}
@Test
@Throws(Exception::class)
fun testCustomAlert() {
activity.customAlert(SAMPLE_ALERT_TITLE_VALUE, SAMPLE_ALERT_MESSAGE_VALUE)
}
} | apache-2.0 | 621c73d878b667f2751fb25e4134f66d | 30.475248 | 85 | 0.729704 | 4.527066 | false | true | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/serialization/xml/XmlEntities.kt | 2 | 977 | package com.jtransc.serialization.xml
import com.jtransc.ds.flip
import com.jtransc.text.transform
object XmlEntities {
// Predefined entities in XML 1.0
private val charToEntity = mapOf('"' to """, '\'' to "'", '<' to "<", '>' to ">", '&' to "&")
private val entities = StrReader.Literals.fromList(charToEntity.values.toTypedArray())
private val entityToChar = charToEntity.flip()
fun encode(str: String): String = str.transform { charToEntity[it] ?: "$it" }
fun decode(str: String): String {
val r = StrReader(str)
var out = ""
while (!r.eof) {
val c = r.readChar()
when (c) {
'&' -> {
val value = r.readUntilIncluded(';') ?: ""
val full = "&$value"
out += if (value.startsWith('#')) {
"${value.substring(1, value.length - 1).toInt().toChar()}"
} else if (entityToChar.contains(full)) {
"${entityToChar[full]}"
} else {
full
}
}
else -> out += c
}
}
return out
}
} | apache-2.0 | d8522fe29fb5234eaa73f4fa0a863d52 | 25.432432 | 114 | 0.594678 | 3.213816 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/Log.kt | 1 | 849 | package com.bixlabs.bkotlin
import android.util.Log
fun Log.v(message: String) = Log.v(TAG, message)
fun Log.d(message: String) = Log.d(TAG, message)
fun Log.i(message: String) = Log.i(TAG, message)
fun Log.w(message: String) = Log.w(TAG, message)
fun Log.e(message: String) = Log.e(TAG, message)
fun Log.wtf(message: String) = Log.wtf(TAG, message)
fun Log.v(message: String, throwable: Throwable) = Log.v(TAG, message, throwable)
fun Log.d(message: String, throwable: Throwable) = Log.d(TAG, message, throwable)
fun Log.i(message: String, throwable: Throwable) = Log.i(TAG, message, throwable)
fun Log.w(message: String, throwable: Throwable) = Log.w(TAG, message, throwable)
fun Log.e(message: String, throwable: Throwable) = Log.e(TAG, message, throwable)
fun Log.wtf(message: String, throwable: Throwable) = Log.wtf(TAG, message, throwable)
| apache-2.0 | 0073fad8711285a42ffc8c90a75b33ed | 48.941176 | 85 | 0.732627 | 3 | false | false | false | false |
Adven27/Exam | exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/utils/CheckType.kt | 1 | 421 | package io.github.adven27.concordion.extensions.exam.core.utils
enum class CheckType {
NUMBER, STRING, BOOLEAN;
fun suit(node: String): Boolean = when (this) {
NUMBER -> isNum(node)
BOOLEAN -> node.lowercase().let { "true" == it || "false" == it }
STRING -> !isNum(node)
}
private fun isNum(node: String): Boolean = node.toIntOrNull() != null || node.toDoubleOrNull() != null
}
| mit | b4c360f97acef2d6ee4499b91514bd45 | 31.384615 | 106 | 0.624703 | 3.692982 | false | false | false | false |
liu-yun/BJUTWiFi | app/src/main/kotlin/me/liuyun/bjutlgn/ui/GraphCard.kt | 1 | 1997 | package me.liuyun.bjutlgn.ui
import android.util.SparseIntArray
import android.widget.LinearLayout
import androidx.core.content.edit
import com.android.settings.graph.UsageView
import kotlinx.android.synthetic.main.graph_card.view.*
import me.liuyun.bjutlgn.App
import me.liuyun.bjutlgn.entity.Flow
import me.liuyun.bjutlgn.util.StatsUtils
import java.text.DateFormat
import java.util.*
class GraphCard(cardView: LinearLayout, private val app: App) {
val chart: UsageView = cardView.chart
fun show() {
val month = Calendar.getInstance().get(Calendar.MONTH)
if (app.prefs.getInt("current_month", -1) != month) {
app.prefs.edit { putInt("current_month", month) }
app.appDatabase.flowDao().deleteAll()
}
val flowList = app.appDatabase.flowDao().all()
chart.clearPaths()
chart.configureGraph(60 * 24 * endOfCurrentMonth.get(Calendar.DATE), StatsUtils.getPack(app) * 1024, true, true)
calcPoints(flowList)
val dateFormat = DateFormat.getDateInstance(DateFormat.SHORT)
chart.setBottomLabels(arrayOf(dateFormat.format(startOfCurrentMonth.time), dateFormat.format(endOfCurrentMonth.time)))
}
private fun calcPoints(flowList: List<Flow>) {
val startOfMonth = (startOfCurrentMonth.timeInMillis / 1000L).toInt() / 60
val points = SparseIntArray()
points.put(0, 0)
flowList.forEach { points.put((it.timestamp / 60 - startOfMonth).toInt(), it.flow / 1024) }
chart.addPath(points)
}
private val startOfCurrentMonth: Calendar
get() = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
clear(Calendar.MINUTE)
clear(Calendar.SECOND)
clear(Calendar.MILLISECOND)
set(Calendar.DAY_OF_MONTH, 1)
}
private val endOfCurrentMonth: Calendar
get() = Calendar.getInstance().apply {
set(Calendar.DATE, getActualMaximum(Calendar.DATE))
}
}
| mit | 156184e1804a5c198f5b07e40d48a1aa | 35.309091 | 126 | 0.676515 | 3.94664 | false | false | false | false |
Jire/Acelta | src/main/kotlin/com/acelta/packet/Packeteer.kt | 1 | 3168 | package com.acelta.packet
import com.acelta.util.nums.byte
import com.acelta.util.nums.int
import com.acelta.util.nums.usin
interface Packeteer {
enum class AccessMode { BYTE, BIT }
companion object {
private val bitMasks = arrayOf(
0, 0x1, 0x3, 0x7,
0xf, 0x1f, 0x3f, 0x7f,
0xff, 0x1ff, 0x3ff, 0x7ff,
0xfff, 0x1fff, 0x3fff, 0x7fff,
0xffff, 0x1ffff, 0x3ffff, 0x7ffff,
0xfffff, 0x1fffff, 0x3fffff, 0x7fffff,
0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff,
0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff,
-1
)
}
var readIndex: Int
operator fun get(index: Int): Byte
fun skip(bytes: Int)
val readable: Int
val byte: Byte
val short: Short
val int: Int
val long: Long
val boolean: Boolean
get() {
ensureAccessMode(AccessMode.BYTE)
return byte > 0
}
val medium: Int
get() {
ensureAccessMode(AccessMode.BYTE)
return (short.usin shl 8) or byte.usin
}
val smart: Int
get() {
ensureAccessMode(AccessMode.BYTE)
return if (this[readIndex].usin > Byte.MAX_VALUE)
short.usin + Short.MIN_VALUE else byte.usin
}
val string: String
var writeIndex: Int
fun clear(): Packeteer
fun ensureWritable(bytes: Int): Packeteer
operator fun set(index: Int, value: Int)
operator fun plus(values: ByteArray): Packeteer
operator fun plus(value: Packeteer): Packeteer
operator fun plus(value: Byte): Packeteer
operator fun plus(value: Short): Packeteer
operator fun plus(value: Int): Packeteer
operator fun plus(value: Long): Packeteer
operator fun plus(value: Boolean) = apply { plus(value.byte) }
operator fun plus(value: String) = apply {
ensureAccessMode(AccessMode.BYTE)
plus(value.toByteArray())
plus('\n'.toByte())
}
var accessMode: AccessMode
fun ensureAccessMode(accessMode: AccessMode) {
if (this.accessMode != accessMode)
throw IllegalStateException("Unexpected access mode (expected=$accessMode, actual=${this.accessMode})")
}
var bitIndex: Int
fun bitAccess() = apply {
bitIndex = writeIndex * 8
accessMode = AccessMode.BIT
}
fun finishBitAccess() = apply {
writeIndex = (bitIndex + 7) / 8
accessMode = AccessMode.BYTE
}
fun bits(numBits: Int, value: Int) = apply {
ensureAccessMode(AccessMode.BIT)
var numBits = numBits
var bytePos = bitIndex shr 3
var bitOffset = 8 - (bitIndex and 7)
bitIndex += numBits
var requiredSpace = bytePos - writeIndex + 1
requiredSpace += (numBits + 7) / 8
ensureWritable(requiredSpace)
while (numBits > bitOffset) {
var tmp = get(bytePos).toInt()
tmp = tmp and bitMasks[bitOffset].inv()
tmp = tmp or (value shr numBits - bitOffset and bitMasks[bitOffset])
set(bytePos++, tmp)
numBits -= bitOffset
bitOffset = 8
}
var tmp = get(bytePos).toInt()
if (numBits == bitOffset) {
tmp = tmp and bitMasks[bitOffset].inv()
tmp = tmp or (value and bitMasks[bitOffset])
set(bytePos, tmp)
} else {
tmp = tmp and (bitMasks[numBits] shl bitOffset - numBits).inv()
tmp = tmp or (value and bitMasks[numBits] shl bitOffset - numBits)
set(bytePos, tmp)
}
}
infix fun bit(value: Int) = bits(1, value)
infix fun bit(value: Boolean) = bits(1, value.int)
} | gpl-3.0 | fddfb953332e8516628ca8c5a96ac7d3 | 21.798561 | 106 | 0.692866 | 2.974648 | false | false | false | false |
evant/silent-support | silent-support/src/main/java/me/tatarka/silentsupport/SupportMetadataProcessor.kt | 1 | 3172 | package me.tatarka.silentsupport
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.io.Writer
import java.util.zip.ZipInputStream
class SupportMetadataProcessor(private val supportCompat: SupportCompat, private val outputDir: File) {
val metadataFile: File by lazy {
File(outputDir, "support-api-versions-${supportCompat.version}.xml")
}
fun process() {
if (!outputDir.exists()) {
outputDir.mkdirs()
}
metadataFile.writer().buffered().use { out ->
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<api version=\"2\">\n")
ZipInputStream(supportCompat.file.inputStream()).use {
it.entries().forEach { entry ->
val name = entry.name
if (name == "classes.jar") {
processClassesJar(it, out)
} else if (name.endsWith(".class")) {
readSupportClass(it.readBytes(), out)
}
}
}
out.write("</api>")
}
}
private fun processClassesJar(input: InputStream, out: Writer) {
ZipInputStream(input).let {
it.entries().forEach { entry ->
if (entry.name.endsWith(".class")) {
readSupportClass(it.readBytes(), out)
}
}
}
}
private fun readSupportClass(bytes: ByteArray, out: Writer) {
val visitor = object : ClassVisitor(Opcodes.ASM5) {
var inClass = false
override fun visit(version: Int, access: Int, name: String, signature: String?, superName: String?, interfaces: Array<out String>?) {
if (name.endsWith("Compat")) {
inClass = true
out.write(" <class name=\"$name\" since=\"2\">\n")
if (superName != null) {
out.write(" <extends name=\"$superName\" />\n")
}
}
}
override fun visitEnd() {
if (inClass) {
out.write(" </class>\n")
}
inClass = false
}
override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?): MethodVisitor? {
if (!inClass) {
return null
}
val acc = (Opcodes.ACC_STATIC or Opcodes.ACC_PUBLIC)
if ((access and acc) == acc) {
out.write(" <method name=\"$name$desc\" />\n")
}
return null
}
private fun descWithoutReceiver(desc: String): String =
desc.replaceFirst("\\(L.*?;".toRegex(), "(")
}
val classReader = ClassReader(bytes)
classReader.accept(visitor, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
}
}
| apache-2.0 | 29b787f8e08d0b36e6751d5dcab2aeee | 35.045455 | 147 | 0.519861 | 4.741405 | false | false | false | false |
mikkokar/styx | components/proxy/src/main/kotlin/com/hotels/styx/ServiceProviderMonitor.kt | 1 | 2557 | /*
Copyright (C) 2013-2020 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx;
import com.google.common.util.concurrent.Service
import com.google.common.util.concurrent.ServiceManager
import com.google.common.util.concurrent.ServiceManager.Listener
import com.hotels.styx.StyxServers.toGuavaService
import com.hotels.styx.api.extension.service.spi.AbstractStyxService
import com.hotels.styx.api.extension.service.spi.StyxService
import com.hotels.styx.routing.db.StyxObjectStore
import org.slf4j.LoggerFactory.getLogger
import java.lang.IllegalStateException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicReference
internal class ServiceProviderMonitor<T : StyxObjectRecord<out StyxService>>(name: String, val servicesDatabase: StyxObjectStore<T>)
: AbstractStyxService(name) {
companion object {
private val LOG = getLogger(ServiceProviderMonitor::class.java)
}
private val services = AtomicReference<Map<String, T>>()
private val manager = AtomicReference<ServiceManager>()
override fun startService(): CompletableFuture<Void> {
val future = CompletableFuture<Void>()
services.set(servicesDatabase.entrySet()
.map { it.key to it.value }
.toMap())
manager.set(ServiceManager(services.get().values.map { toGuavaService(it.styxService) }))
manager.get().addListener(object : Listener() {
override fun healthy() {
future.complete(null);
}
override fun failure(service: Service) {
future.completeExceptionally(service.failureCause())
}
})
manager.get().startAsync()
return future;
}
override fun stopService(): CompletableFuture<Void> = CompletableFuture.runAsync {
if (manager.get() == null) {
throw IllegalStateException("ServiceProviderMonitor ${serviceName()} is not RUNNING.")
}
manager.get().stopAsync().awaitStopped()
}
}
| apache-2.0 | 5b0289c685d21ec8f699cc09e51a892c | 36.057971 | 132 | 0.7149 | 4.566071 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/traktapi/GenericCheckInDialogFragment.kt | 1 | 5168 | package com.battlelancer.seriesguide.traktapi
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.lifecycle.lifecycleScope
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.DialogCheckinBinding
import com.battlelancer.seriesguide.traktapi.TraktTask.TraktActionCompleteEvent
import com.battlelancer.seriesguide.traktapi.TraktTask.TraktCheckInBlockedEvent
import com.battlelancer.seriesguide.util.Utils
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import kotlin.math.max
import kotlin.math.min
abstract class GenericCheckInDialogFragment : AppCompatDialogFragment() {
class CheckInDialogDismissedEvent
private var binding: DialogCheckinBinding? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogCheckinBinding.inflate(layoutInflater)
this.binding = binding
// Paste episode button
val itemTitle = requireArguments().getString(ARG_ITEM_TITLE)
val editTextMessage = binding.textInputLayoutCheckIn.editText
if (!itemTitle.isNullOrEmpty()) {
binding.buttonCheckInPasteTitle.setOnClickListener {
if (editTextMessage == null) {
return@setOnClickListener
}
val start = editTextMessage.selectionStart
val end = editTextMessage.selectionEnd
editTextMessage.text.replace(
min(start, end), max(start, end),
itemTitle, 0, itemTitle.length
)
}
}
// Clear button
binding.buttonCheckInClear.setOnClickListener {
if (editTextMessage == null) {
return@setOnClickListener
}
editTextMessage.text = null
}
// Checkin Button
binding.buttonCheckIn.setOnClickListener { checkIn() }
setProgressLock(false)
lifecycleScope.launchWhenStarted {
// immediately start to check-in if the user has opted to skip entering a check-in message
if (TraktSettings.useQuickCheckin(requireContext())) {
checkIn()
}
}
return MaterialAlertDialogBuilder(requireContext(), R.style.Theme_SeriesGuide_Dialog_CheckIn)
.setView(binding.root)
.create()
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
EventBus.getDefault().post(CheckInDialogDismissedEvent())
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
@Subscribe
fun onEvent(event: TraktActionCompleteEvent) {
// done with checking in, unlock UI
setProgressLock(false)
if (event.wasSuccessful) {
// all went well, dismiss ourselves
dismissAllowingStateLoss()
}
}
@Subscribe
fun onEvent(event: TraktCheckInBlockedEvent) {
// launch a check-in override dialog
TraktCancelCheckinDialogFragment
.show(parentFragmentManager, event.traktTaskArgs, event.waitMinutes)
}
private fun checkIn() {
// lock down UI
setProgressLock(true)
// connected?
if (Utils.isNotConnected(requireContext())) {
// no? abort
setProgressLock(false)
return
}
// launch connect flow if trakt is not connected
if (!TraktCredentials.ensureCredentials(requireContext())) {
// not connected? abort
setProgressLock(false)
return
}
// try to check in
val editText = binding?.textInputLayoutCheckIn?.editText
if (editText != null) {
checkInTrakt(editText.text.toString())
}
}
/**
* Start the Trakt check-in task.
*/
protected abstract fun checkInTrakt(message: String)
/**
* Disables all interactive UI elements and shows a progress indicator.
*/
private fun setProgressLock(lock: Boolean) {
val binding = binding ?: return
binding.progressBarCheckIn.visibility = if (lock) View.VISIBLE else View.GONE
binding.textInputLayoutCheckIn.isEnabled = !lock
binding.buttonCheckInPasteTitle.isEnabled = !lock
binding.buttonCheckInClear.isEnabled = !lock
binding.buttonCheckIn.isEnabled = !lock
}
companion object {
/**
* Title of episode or movie. **Required.**
*/
const val ARG_ITEM_TITLE = "itemtitle"
/**
* Movie TMDb id. **Required for movies.**
*/
const val ARG_MOVIE_TMDB_ID = "movietmdbid"
const val ARG_EPISODE_ID = "episodeid"
}
} | apache-2.0 | c7a824d56bad049b1507706dfd9c0abb | 30.711656 | 102 | 0.643189 | 5.22548 | false | false | false | false |
openbase/jul | module/transformation/src/main/java/org/openbase/rct/impl/mqtt/FrameTransformProcessor.kt | 1 | 3109 | package org.openbase.rct.impl.mqtt
import org.openbase.rct.Transform
import org.openbase.type.geometry.TransformLinksType.TransformLinks
import org.openbase.type.geometry.TransformLinkType
import org.openbase.type.geometry.TransformLinksType.TransformLinksOrBuilder
import javax.media.j3d.Transform3D
import javax.vecmath.Quat4d
import javax.vecmath.Vector3d
/*-
* #%L
* RCT
* %%
* Copyright (C) 2015 - 2022 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
class TransformLinkProcessor {
companion object {
@JvmStatic
fun convert(transformations: Collection<Transform>): TransformLinks = transformations
.asSequence()
.map { transform ->
val quat = transform.rotationQuat
val vec = transform.translation
val builder = TransformLinkType.TransformLink.newBuilder()
builder.authority = transform.authority
builder.timeBuilder.time = transform.time * 1000L
builder.childNode = transform.childNode
builder.parentNode = transform.parentNode
builder.transformBuilder.rotationBuilder.qw = quat.w
builder.transformBuilder.rotationBuilder.qx = quat.x
builder.transformBuilder.rotationBuilder.qy = quat.y
builder.transformBuilder.rotationBuilder.qz = quat.z
builder.transformBuilder.translationBuilder.x = vec.x
builder.transformBuilder.translationBuilder.y = vec.y
builder.transformBuilder.translationBuilder.z = vec.z
builder.build()
}
.toList()
.let { TransformLinks.newBuilder().addAllTransforms(it).build() }
@JvmStatic
fun convert(transformations: TransformLinksOrBuilder): List<Transform> =
transformations.transformsList
.asSequence()
.map { transform ->
val rstRot = transform.transform.rotation
val rstTrans = transform.transform.translation
val quat = Quat4d(rstRot.qx, rstRot.qy, rstRot.qz, rstRot.qw)
val vec = Vector3d(rstTrans.x, rstTrans.y, rstTrans.z)
val transform3d = Transform3D(quat, vec, 1.0)
Transform(transform3d, transform.parentNode, transform.childNode, transform.time.time / 1000L)
}.toList()
}
}
| lgpl-3.0 | aa5aa9b4aa70b518af9d35d2967ffa2c | 42.180556 | 114 | 0.657446 | 4.479827 | false | false | false | false |
AlmasB/FXGL | fxgl-core/src/main/kotlin/com/almasb/fxgl/core/math/PerlinNoiseGenerator.kt | 1 | 2779 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (almaslvl@gmail.com).
* See LICENSE for details.
*/
package com.almasb.fxgl.core.math
/**
* Adapted from https://github.com/CRYTEK/CRYENGINE/blob/release/Code/CryEngine/CryCommon/CryMath/PNoise3.h
*
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
class PerlinNoiseGenerator(seed: Long) {
// from CRYtek
private val NOISE_TABLE_SIZE = 256
private val NOISE_MASK = 255
// permutation table
private val p = IntArray(NOISE_TABLE_SIZE)
private val gx = FloatArray(NOISE_TABLE_SIZE)
private val gy = FloatArray(NOISE_TABLE_SIZE)
init {
setSeedAndReinitialize(seed)
}
private fun setSeedAndReinitialize(seed: Long) {
var i: Int
var j: Int
var nSwap: Int
val random = FXGLMath.getRandom(seed)
// Initialize the permutation table
i = 0
while (i < NOISE_TABLE_SIZE) {
p[i] = i
i++
}
i = 0
while (i < NOISE_TABLE_SIZE) {
j = FXGLMath.random(1, Int.MAX_VALUE) and NOISE_MASK
nSwap = p[i]
p[i] = p[j]
p[j] = nSwap
i++
}
// Generate the gradient lookup tables
for (i in 0..NOISE_TABLE_SIZE - 1) {
// Ken Perlin proposes that the gradients are taken from the unit
// circle/sphere for 2D/3D.
// So lets generate a good pseudo-random vector and normalize it
val v = Vec2()
// random is in the 0..1 range, so we bring to -0.5..0.5
v.x = random.nextFloat() - 0.5f
v.y = random.nextFloat() - 0.5f
v.normalizeLocal()
gx[i] = v.x
gy[i] = v.y
}
}
//! 1D quality noise generator, good for many situations like up/down movements, flickering/ambient lights etc.
//! A typical usage would be to pass system time multiplied by a frequency value, like:
//! float fRes=pNoise->Noise1D(fCurrentTime*fFreq);
//! the lower the frequency, the smoother the output
/**
* Generates a value in [0..1], t > 0.
*/
fun noise1D(t: Double): Double {
// Compute what gradients to use
var qx0 = Math.floor(t).toInt()
var qx1 = qx0 + 1
val tx0 = t - qx0
val tx1 = tx0 - 1
// Make sure we don't come outside the lookup table
qx0 = qx0 and NOISE_MASK
qx1 = qx1 and NOISE_MASK
// Compute the dotproduct between the vectors and the gradients
val v0 = gx[qx0] * tx0
val v1 = gx[qx1] * tx1
// Modulate with the weight function
val wx = (3 - 2 * tx0) * tx0 * tx0
return v0 - wx * (v0 - v1) + 0.5
}
} | mit | 2fd6ffd421bb8a86a657403ab45eff1c | 27.958333 | 115 | 0.564951 | 3.52665 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-core-bukkit/src/main/kotlin/com/rpkit/core/bukkit/reflect/ReflectionUtil.kt | 1 | 6279 | /*
* Copyright 2022 Ren Binden
*
* 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.
*/
package com.rpkit.core.bukkit.reflect
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import java.lang.reflect.Constructor
import java.lang.reflect.Field
import java.lang.reflect.Method
object ReflectionUtil {
/*
* The server version string to location NMS & OBC classes
*/
private var versionString: String? = null
/*
* Cache of NMS classes that we've searched for
*/
private val loadedNMSClasses: MutableMap<String, Class<*>?> = HashMap()
/*
* Cache of OBS classes that we've searched for
*/
private val loadedOBCClasses: MutableMap<String, Class<*>?> = HashMap()
/*
* Cache of methods that we've found in particular classes
*/
private val loadedMethods: MutableMap<Class<*>, MutableMap<String, Method?>> = HashMap()
/*
* Cache of fields that we've found in particular classes
*/
private val loadedFields: MutableMap<Class<*>, MutableMap<String, Field?>> = HashMap()
/**
* Gets the version string for NMS & OBC class paths
*
* @return The version string of OBC and NMS packages
*/
val version: String?
get() {
if (versionString == null) {
val name = Bukkit.getServer().javaClass.getPackage().name
versionString = name.substring(name.lastIndexOf('.') + 1) + "."
}
return versionString
}
/**
* Get an NMS Class
*
* @param nmsClassName The name of the class
* @return The class
*/
fun getNMSClass(nmsClassName: String): Class<*>? {
if (loadedNMSClasses.containsKey(nmsClassName)) {
return loadedNMSClasses[nmsClassName]
}
val clazzName = "net.minecraft.$nmsClassName"
val clazz = try {
Class.forName(clazzName)
} catch (t: Throwable) {
t.printStackTrace()
return loadedNMSClasses.put(nmsClassName, null)
}
loadedNMSClasses[nmsClassName] = clazz
return clazz
}
/**
* Get a class from the org.bukkit.craftbukkit package
*
* @param obcClassName the path to the class
* @return the found class at the specified path
*/
@Synchronized
fun getOBCClass(obcClassName: String): Class<*>? {
if (loadedOBCClasses.containsKey(obcClassName)) {
return loadedOBCClasses[obcClassName]
}
val clazzName = "org.bukkit.craftbukkit.$version$obcClassName"
val clazz: Class<*>
try {
clazz = Class.forName(clazzName)
} catch (t: Throwable) {
t.printStackTrace()
loadedOBCClasses[obcClassName] = null
return null
}
loadedOBCClasses[obcClassName] = clazz
return clazz
}
/**
* Get a Bukkit [Player] players NMS playerConnection object
*
* @param player The player
* @return The players connection
*/
fun getConnection(player: Player): Any? {
val getHandleMethod = getMethod(player.javaClass, "getHandle")
if (getHandleMethod != null) {
try {
val nmsPlayer = getHandleMethod.invoke(player)
val playerConField = getField(nmsPlayer.javaClass, "playerConnection")
return playerConField!![nmsPlayer]
} catch (e: Exception) {
e.printStackTrace()
}
}
return null
}
/**
* Get a classes constructor
*
* @param clazz The constructor class
* @param params The parameters in the constructor
* @return The constructor object
*/
fun getConstructor(clazz: Class<*>, vararg params: Class<*>?): Constructor<*>? {
return try {
clazz.getConstructor(*params)
} catch (e: NoSuchMethodException) {
null
}
}
/**
* Get a method from a class that has the specific paramaters
*
* @param clazz The class we are searching
* @param methodName The name of the method
* @param params Any parameters that the method has
* @return The method with appropriate paramaters
*/
fun getMethod(clazz: Class<*>, methodName: String, vararg params: Class<*>?): Method? {
if (!loadedMethods.containsKey(clazz)) {
loadedMethods[clazz] = HashMap()
}
val methods = loadedMethods[clazz]!!
return if (methods.containsKey(methodName)) {
methods[methodName]
} else try {
val method = clazz.getMethod(methodName, *params)
methods[methodName] = method
loadedMethods[clazz] = methods
method
} catch (e: Exception) {
e.printStackTrace()
methods[methodName] = null
loadedMethods[clazz] = methods
null
}
}
/**
* Get a field with a particular name from a class
*
* @param clazz The class
* @param fieldName The name of the field
* @return The field object
*/
fun getField(clazz: Class<*>, fieldName: String): Field? {
if (!loadedFields.containsKey(clazz)) {
loadedFields[clazz] = HashMap()
}
val fields = loadedFields[clazz]!!
return if (fields.containsKey(fieldName)) {
fields[fieldName]
} else try {
val field = clazz.getField(fieldName)
fields[fieldName] = field
loadedFields[clazz] = fields
field
} catch (e: Exception) {
e.printStackTrace()
fields[fieldName] = null
loadedFields[clazz] = fields
null
}
}
} | apache-2.0 | d1ef8248d681c7dca6930da0b6546acc | 30.4 | 92 | 0.59707 | 4.731726 | false | false | false | false |
mvarnagiris/mvp | mvp-test/src/test/kotlin/com/mvcoding/mvp/behaviors/InitializationBehaviorTest.kt | 1 | 1327 | package com.mvcoding.mvp.behaviors
import com.mvcoding.mvp.Presenter
import com.mvcoding.mvp.RxSchedulers
import com.mvcoding.mvp.trampolines
import io.reactivex.Single
import org.junit.Test
class InitializationBehaviorTest {
@Test
fun `initialization behavior test`() {
val loggedInAppUser = AppUser("token")
val notLoggedInAppUser = AppUser("")
testInitializationBehavior(
successResult = loggedInAppUser,
failureResult = notLoggedInAppUser,
getSuccess = { it.token },
getFailure = { "no token" },
mapError = { it }) { SplashPresenter(it, trampolines) }
}
private data class AppUser(val token: String) {
val isLoggedIn = token.isNotEmpty()
}
private class SplashPresenter(
getAppUser: () -> Single<AppUser>,
schedulers: RxSchedulers) : Presenter<SplashPresenter.View>(
InitializationBehavior(
getAppUser,
isSuccess = { it.isLoggedIn },
getSuccess = { it.token },
getFailure = { "no token" },
mapError = { it },
schedulers = schedulers)) {
interface View : InitializationBehavior.View<String, String, Throwable>
}
} | apache-2.0 | 33efd9b82b28a4e7d697a8b4d58af833 | 31.390244 | 79 | 0.590806 | 4.951493 | false | true | false | false |
Kotlin/anko | anko/library/generated/percent/src/main/java/Layouts.kt | 4 | 7558 | @file:JvmName("PercentLayoutsKt")
package org.jetbrains.anko.percent
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.FrameLayout
import android.support.percent.PercentFrameLayout
import android.view.View
import android.support.percent.PercentRelativeLayout
open class _PercentFrameLayout(ctx: Context): PercentFrameLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = PercentFrameLayout.LayoutParams(c!!, attrs!!)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(width, height)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = PercentFrameLayout.LayoutParams(width, height)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = PercentFrameLayout.LayoutParams(width, height, gravity)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: PercentFrameLayout.LayoutParams?,
init: PercentFrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: PercentFrameLayout.LayoutParams?
): T {
val layoutParams = PercentFrameLayout.LayoutParams(source!!)
this@lparams.layoutParams = layoutParams
return this
}
}
open class _PercentRelativeLayout(ctx: Context): PercentRelativeLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: PercentRelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(c!!, attrs!!)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: PercentRelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(width, height)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(width, height)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: PercentRelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(source!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(source!!)
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: PercentRelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(source!!)
layoutParams.init()
this@lparams.layoutParams = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = PercentRelativeLayout.LayoutParams(source!!)
this@lparams.layoutParams = layoutParams
return this
}
}
| apache-2.0 | bc7eb24161aed2cb43ef0f4b7f182336 | 31.86087 | 82 | 0.63575 | 4.962574 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/effects/BonusPerBoardElement.kt | 1 | 1205 | package org.luxons.sevenwonders.engine.effects
import org.luxons.sevenwonders.engine.Player
import org.luxons.sevenwonders.engine.boards.Board
import org.luxons.sevenwonders.model.boards.RelativeBoardPosition
import org.luxons.sevenwonders.model.cards.Color
enum class BoardElementType {
CARD,
BUILT_WONDER_STAGES,
DEFEAT_TOKEN,
}
internal data class BonusPerBoardElement(
val boards: List<RelativeBoardPosition>,
val type: BoardElementType,
val gold: Int = 0,
val points: Int = 0,
val colors: List<Color>? = null, // only relevant if type=CARD
) : Effect {
override fun applyTo(player: Player) = player.board.addGold(gold * nbMatchingElementsFor(player))
override fun computePoints(player: Player): Int = points * nbMatchingElementsFor(player)
private fun nbMatchingElementsFor(player: Player): Int = boards.sumBy { nbMatchingElementsIn(player.getBoard(it)) }
private fun nbMatchingElementsIn(board: Board): Int = when (type) {
BoardElementType.CARD -> board.getNbCardsOfColor(colors!!)
BoardElementType.BUILT_WONDER_STAGES -> board.wonder.nbBuiltStages
BoardElementType.DEFEAT_TOKEN -> board.military.nbDefeatTokens
}
}
| mit | 7f2ae08b430be705a9a0fa06867d40b6 | 35.515152 | 119 | 0.750207 | 3.874598 | false | false | false | false |
shiguredo/sora-android-sdk | sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/channel/signaling/message/Catalog.kt | 1 | 7564 | package jp.shiguredo.sora.sdk.channel.signaling.message
import com.google.gson.annotations.SerializedName
import jp.shiguredo.sora.sdk.util.SDKInfo
data class MessageCommonPart(
@SerializedName("type") val type: String?
)
data class PingMessage(
@SerializedName("type") val type: String = "ping",
@SerializedName("stats") val stats: Boolean?
)
data class PongMessage(
@SerializedName("type") val type: String = "pong",
@SerializedName("stats") val stats: List<SoraRTCStats>? = null
)
data class ConnectMessage(
@SerializedName("type") val type: String = "connect",
@SerializedName("role") var role: String,
@SerializedName("channel_id") val channelId: String,
@SerializedName("client_id") val clientId: String? = null,
@SerializedName("bundle_id") val bundleId: String? = null,
@SerializedName("metadata") val metadata: Any? = null,
@SerializedName("signaling_notify_metadata")
val signalingNotifyMetadata: Any? = null,
@SerializedName("multistream") val multistream: Boolean = false,
@SerializedName("spotlight") var spotlight: Any? = null,
@SerializedName("spotlight_number")
var spotlightNumber: Int? = null,
@SerializedName("spotlight_focus_rid") var spotlightFocusRid: String? = null,
@SerializedName("spotlight_unfocus_rid") var spotlightUnfocusRid: String? = null,
@SerializedName("simulcast") var simulcast: Boolean? = false,
@SerializedName("simulcast_rid")
var simulcastRid: String? = null,
@SerializedName("video") var video: Any? = null,
@SerializedName("audio") var audio: Any? = null,
@SerializedName("sora_client") val soraClient: String = SDKInfo.sdkInfo(),
@SerializedName("libwebrtc") val libwebrtc: String = SDKInfo.libwebrtcInfo(),
@SerializedName("environment") val environment: String = SDKInfo.deviceInfo(),
@SerializedName("sdp") val sdp: String? = null,
@SerializedName("data_channel_signaling")
val dataChannelSignaling: Boolean? = null,
@SerializedName("ignore_disconnect_websocket")
val ignoreDisconnectWebsocket: Boolean? = null,
@SerializedName("data_channels") val dataChannels: List<Map<String, Any>>? = null,
@SerializedName("redirect") var redirect: Boolean? = null
)
data class VideoSetting(
@SerializedName("codec_type") val codecType: String,
@SerializedName("bit_rate") var bitRate: Int? = null
)
data class AudioSetting(
@SerializedName("codec_type") val codecType: String?,
@SerializedName("bit_rate") var bitRate: Int? = null,
@SerializedName("opus_params") var opusParams: OpusParams? = null
)
data class OpusParams(
@SerializedName("channels") var channels: Int? = null,
@SerializedName("clock_rate") var clockRate: Int? = null,
@SerializedName("maxplaybackrate") var maxplaybackrate: Int? = null,
@SerializedName("stereo") var stereo: Boolean? = null,
@SerializedName("sprop_stereo") var spropStereo: Boolean? = null,
@SerializedName("minptime") var minptime: Int? = null,
@SerializedName("useinbandfec") var useinbandfec: Boolean? = null,
@SerializedName("usedtx") var usedtx: Boolean? = null
)
data class IceServer(
@SerializedName("urls") val urls: List<String>,
@SerializedName("credential") val credential: String,
@SerializedName("username") val username: String
)
data class OfferConfig(
@SerializedName("iceServers") val iceServers: List<IceServer>,
@SerializedName("iceTransportPolicy") val iceTransportPolicy: String
)
data class Encoding(
@SerializedName("rid") val rid: String?,
@SerializedName("active") val active: Boolean?,
@SerializedName("maxBitrate") val maxBitrate: Int?,
@SerializedName("maxFramerate") val maxFramerate: Int?,
@SerializedName("scaleResolutionDownBy") val scaleResolutionDownBy: Double?
)
data class RedirectMessage(
@SerializedName("type") val type: String = "redirect",
@SerializedName("location") val location: String
)
data class OfferMessage(
@SerializedName("type") val type: String = "offer",
@SerializedName("sdp") val sdp: String,
@SerializedName("client_id") val clientId: String,
@SerializedName("bundle_id") val bundleId: String? = null,
@SerializedName("connection_id") val connectionId: String,
@SerializedName("metadata") val metadata: Any?,
@SerializedName("config") val config: OfferConfig? = null,
@SerializedName("mid") val mid: Map<String, String>? = null,
@SerializedName("encodings") val encodings: List<Encoding>?,
@SerializedName("data_channels") val dataChannels: List<Map<String, Any>>? = null
)
data class SwitchedMessage(
@SerializedName("type") val type: String = "switched",
@SerializedName("ignore_disconnect_websocket") val ignoreDisconnectWebsocket: Boolean? = null
)
data class UpdateMessage(
@SerializedName("type") val type: String = "update",
@SerializedName("sdp") val sdp: String
)
data class ReOfferMessage(
@SerializedName("type") val type: String = "re-offer",
@SerializedName("sdp") val sdp: String
)
data class ReAnswerMessage(
@SerializedName("type") val type: String = "re-answer",
@SerializedName("sdp") val sdp: String
)
data class AnswerMessage(
@SerializedName("type") val type: String = "answer",
@SerializedName("sdp") val sdp: String
)
data class CandidateMessage(
@SerializedName("type") val type: String = "candidate",
@SerializedName("candidate") val candidate: String
)
data class PushMessage(
@SerializedName("type") val type: String = "push",
@SerializedName("data") var data: Any? = null
)
data class ReqStatsMessage(
@SerializedName("type") val type: String = "req-stats"
)
data class StatsMessage(
@SerializedName("type") val type: String = "stats",
@SerializedName("reports") val reports: List<SoraRTCStats>
)
data class NotificationMessage(
@SerializedName("type") val type: String = "notify",
@SerializedName("event_type") val eventType: String,
@SerializedName("role") val role: String?,
@SerializedName("client_id") val clientId: String,
@SerializedName("bundle_id") val bundleId: String?,
@SerializedName("connection_id") val connectionId: String?,
@SerializedName("audio") val audio: Boolean?,
@SerializedName("video") val video: Boolean?,
@SerializedName("metadata") val metadata: Any?,
@Deprecated("metadata_list は将来の Sora のリリースでフィールド名を data に変更する予定です。")
@SerializedName("metadata_list") val metadataList: Any?,
@SerializedName("minutes") val connectionTime: Long?,
@SerializedName("channel_connections") val numberOfConnections: Int?,
@SerializedName("channel_sendrecv_connections") val numberOfSendrecvConnections: Int?,
@SerializedName("channel_sendonly_connections") val numberOfSendonlyConnections: Int?,
@SerializedName("channel_recvonly_connections") val numberOfRecvonlyConnections: Int?,
@SerializedName("unstable_level") val unstableLevel: Int?,
@SerializedName("channel_id") val channelId: String?,
@SerializedName("spotlight_id") val spotlightId: String?,
@SerializedName("fixed") val fixed: Boolean?,
@SerializedName("authn_metadata") val authnMetadata: Any?,
@SerializedName("authz_metadata") val authzMetadata: Any?,
@SerializedName("data") val data: Any?,
@SerializedName("turn_transport_type") val turnTransportType: String?,
)
data class DisconnectMessage(
@SerializedName("type") val type: String = "disconnect",
@SerializedName("reason") val reason: String? = null
)
| apache-2.0 | 7fdd594c10fd0f725ba6bde09b168fc2 | 39.594595 | 97 | 0.714913 | 3.981972 | false | false | false | false |
BoD/Ticker | app/src/main/kotlin/org/jraf/android/ticker/app/main/MainActivity.kt | 1 | 20882 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2016-present Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.android.ticker.app.main
import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.location.Location
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Html
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Base64
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.postDelayed
import androidx.databinding.DataBindingUtil
import ca.rmen.sunrisesunset.SunriseSunset
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import org.jraf.android.ticker.R
import org.jraf.android.ticker.databinding.MainBinding
import org.jraf.android.ticker.glide.GlideApp
import org.jraf.android.ticker.pref.MainPrefs
import org.jraf.android.ticker.ticker.Ticker
import org.jraf.android.ticker.util.emoji.EmojiUtil.replaceEmojisWithImageSpans
import org.jraf.android.ticker.util.emoji.EmojiUtil.replaceEmojisWithSmiley
import org.jraf.android.ticker.util.location.IpApiClient
import org.jraf.android.ticker.util.ui.fadeIn
import org.jraf.android.ticker.util.ui.fadeOut
import org.jraf.android.util.log.Log
import java.util.Calendar
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.math.min
typealias TickerMessage = org.jraf.libticker.message.Message
@SuppressLint("ShowToast")
class MainActivity : AppCompatActivity() {
companion object {
private const val FONT_NAME = "RobotoCondensed-Regular-No-Ligatures.ttf"
private val UPDATE_BRIGHTNESS_RATE_MS = TimeUnit.MINUTES.toMillis(1)
private val CHECK_QUEUE_RATE_MS = TimeUnit.SECONDS.toMillis(14)
private val SHOW_IMAGE_DURATION_MEDIUM_MS = TimeUnit.SECONDS.toMillis(10)
private val SHOW_IMAGE_DURATION_LONG_MS = TimeUnit.SECONDS.toMillis(28)
private val SHOW_MINI_TICKER_DELAY_MS = TimeUnit.SECONDS.toMillis(2)
private val HIDE_MINI_TICKER_DELAY_MS = TimeUnit.SECONDS.toMillis(10)
private const val TYPEWRITER_EFFECT_DURATION_MS = 1800L
private const val MESSAGE_CHECK_QUEUE = 0
private const val MESSAGE_SHOW_TEXT = 1
private const val MESSAGE_HIDE_MINI_TICKER = 2
}
private lateinit var binding: MainBinding
private var location: Location? = null
private val mainPrefs by lazy {
MainPrefs(this)
}
@SuppressLint("InlinedApi", "CheckResult")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
binding = DataBindingUtil.setContentView(this, R.layout.main)
binding.root.systemUiVisibility = (View.SYSTEM_UI_FLAG_LOW_PROFILE
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LOW_PROFILE)
// Set the custom font
val typeface = Typeface.createFromAsset(assets, "fonts/$FONT_NAME")
binding.txtTicker.typeface = typeface
binding.txtMiniTicker.typeface = typeface
Ticker.messageQueue.addUrgent(
TickerMessage(
text = getString(R.string.main_httpConfUrl, Ticker.httpConf.getUrl()),
imageUri = "https://api.qrserver.com/v1/create-qr-code/?data=${Ticker.httpConf.getUrl()}"
)
)
binding.foregroundOpacity.setOnTouchListener(
adjustBrightnessAndBackgroundOpacityOnTouchListener
)
binding.webTicker.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
binding.imgImage.fadeOut()
binding.webTicker.fadeIn()
binding.txtTicker.fadeOut()
binding.txtMiniTicker.fadeOut()
}
}
}
override fun onResume() {
super.onResume()
thread {
location = IpApiClient().currentLocation
Log.d("location=$location")
}
Ticker.pluginManager.startAllManagedPlugins()
updateBrightnessAndBackgroundOpacityHandler.sendEmptyMessage(0)
checkMessageQueueHandler.sendEmptyMessage(MESSAGE_CHECK_QUEUE)
// Inform the ticker of the display size
val displayMetrics = DisplayMetrics()
@Suppress("DEPRECATION")
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
Ticker.pluginManager.globalConfiguration.run {
put("displayWidth", displayMetrics.widthPixels)
put("displayHeight", displayMetrics.heightPixels)
}
}
override fun onPause() {
Ticker.pluginManager.stopAllManagedPlugins()
updateBrightnessAndBackgroundOpacityHandler.removeCallbacksAndMessages(null)
checkMessageQueueHandler.removeCallbacksAndMessages(null)
super.onPause()
}
private fun adjustFontSize(tickerText: CharSequence) {
val rect = Rect()
window.decorView.getWindowVisibleDisplayFrame(rect)
val smallSide = min(rect.width(), rect.height())
// A font size of about ~1/8 to 1/10 screen small side is a sensible value for the starting font size
var fontSize = (smallSide / 10f).toInt()
binding.txtTicker.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize.toFloat())
binding.txtTicker.text = tickerText
binding.txtTicker.measure(
View.MeasureSpec.makeMeasureSpec(
rect.width(),
View.MeasureSpec.AT_MOST
), View.MeasureSpec.UNSPECIFIED
)
while (binding.txtTicker.measuredHeight < rect.height()) {
fontSize += 2
binding.txtTicker.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize.toFloat())
binding.txtTicker.measure(
View.MeasureSpec.makeMeasureSpec(
rect.width(),
View.MeasureSpec.AT_MOST
), View.MeasureSpec.UNSPECIFIED
)
}
fontSize -= 2
binding.txtTicker.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize.toFloat())
binding.txtTicker.text = null
}
private fun showMessageText(message: TickerMessage) {
val html = message.html
if (html != null) {
setTickerHtml(html)
} else {
setTickerText(message.textFormatted)
}
}
private fun setTickerText(text: String) {
binding.imgImage.fadeOut()
binding.webTicker.fadeOut()
binding.txtMiniTicker.fadeOut()
binding.txtTicker.fadeIn()
@Suppress("DEPRECATION")
val formattedText = Html.fromHtml(text)
// Adjust the font size to fit the screen.
// Before we do this, we replace emojis with '😀' which is a wide character.
// This allows for the ImageSpan sizes of the replaced emojis to be accounted for.
adjustFontSize(formattedText.replaceEmojisWithSmiley())
val textWithSpans: Spannable = formattedText.replaceEmojisWithImageSpans(binding.txtTicker)
// Change the color randomly
val hsv = FloatArray(3)
hsv[0] = (Math.random() * 360f).toFloat()
hsv[1] = .75f
hsv[2] = .75f
val color = Color.HSVToColor(hsv)
binding.txtTicker.setTextColor(color)
val delay =
if (textWithSpans.length <= 10) 0 else TYPEWRITER_EFFECT_DURATION_MS / textWithSpans.length
for (i in 0 until textWithSpans.length) {
binding.txtTicker.postDelayed({
val truncatedText = SpannableStringBuilder(textWithSpans)
truncatedText.setSpan(
ForegroundColorSpan(Color.TRANSPARENT),
i + 1,
textWithSpans.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
binding.txtTicker.text = truncatedText
}, delay * i)
}
}
private fun setTickerHtml(html: String) {
binding.webTicker.loadData(
Base64.encodeToString(html.toByteArray(), Base64.NO_PADDING),
"text/html; charset=utf-8",
"base64"
)
}
/**
* Handler to check the message queue periodically, and show the text and/or image.
*/
private val checkMessageQueueHandler =
@SuppressLint("HandlerLeak")
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(message: Message) {
when (message.what) {
MESSAGE_CHECK_QUEUE -> {
val newMessage = Ticker.messageQueue.getNext()
if (newMessage == null) {
// Check again later
sendEmptyMessageDelayed(MESSAGE_CHECK_QUEUE, CHECK_QUEUE_RATE_MS)
return
}
if (newMessage.imageUri != null) {
// There is an image: show it now, and show the text later (unless hint to show it on top of image is present)
val isCropAllowed = newMessage.hints["image.cropAllowed"] == "true"
val isLongDisplayDuration = newMessage.hints["image.displayDuration"] == "long"
val showTextOnTopOfImage = newMessage.hints["text.showOnTopOfImage"] == "true"
val delay = if (isLongDisplayDuration) SHOW_IMAGE_DURATION_LONG_MS else SHOW_IMAGE_DURATION_MEDIUM_MS
if (showTextOnTopOfImage) {
showImage(newMessage.imageUri!!, isCropAllowed, newMessage.text)
// Reschedule
sendEmptyMessageDelayed(MESSAGE_CHECK_QUEUE, delay)
} else {
showImage(newMessage.imageUri!!, isCropAllowed, null)
// Show the text later
sendMessageDelayed(
Message.obtain(this, MESSAGE_SHOW_TEXT, newMessage),
delay
)
}
} else {
// Just the text: show it now
showMessageText(newMessage)
// Reschedule
sendEmptyMessageDelayed(MESSAGE_CHECK_QUEUE, CHECK_QUEUE_RATE_MS)
}
}
MESSAGE_SHOW_TEXT -> {
showMessageText(message.obj as TickerMessage)
// Reschedule
sendEmptyMessageDelayed(MESSAGE_CHECK_QUEUE, CHECK_QUEUE_RATE_MS)
}
MESSAGE_HIDE_MINI_TICKER -> binding.txtMiniTicker.fadeOut()
}
}
}
private fun showImage(imageUri: String, cropAllowed: Boolean, text: String?) {
Log.d("imageUri=$imageUri cropAllowed=$cropAllowed text=$text")
var glideRequest = GlideApp.with(this).load(imageUri)
glideRequest = if (cropAllowed) {
glideRequest.centerCrop()
} else {
glideRequest.fitCenter()
}
glideRequest
.transition(DrawableTransitionOptions.withCrossFade())
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
binding.txtTicker.fadeOut()
binding.webTicker.fadeOut()
binding.imgImage.visibility = View.VISIBLE
binding.imgImage.alpha = 1F
binding.imgImage.setImageDrawable(null)
if (text == null) {
binding.txtMiniTicker.visibility = View.GONE
} else {
binding.txtMiniTicker.postDelayed(SHOW_MINI_TICKER_DELAY_MS) {
binding.txtMiniTicker.fadeIn()
binding.txtMiniTicker.text = text
checkMessageQueueHandler.sendEmptyMessageDelayed(MESSAGE_HIDE_MINI_TICKER, HIDE_MINI_TICKER_DELAY_MS)
}
}
return false
}
})
.into(binding.imgImage)
}
//--------------------------------------------------------------------------
// region Brightness and background opacity.
//--------------------------------------------------------------------------
@SuppressLint("ClickableViewAccessibility")
private val adjustBrightnessAndBackgroundOpacityOnTouchListener =
View.OnTouchListener { v, event ->
var y = event.y
val height = v.height.toFloat()
val safeZone = 1.8F
y = y * safeZone - (height * safeZone - height) / 2F
val x = event.x
val width = v.width
val ratio = (1F - y / height).coerceIn(0F..1F)
val left = x < width / 2
if (left) {
// Brightness
showBrightnessPanel(ratio)
setBrightness(ratio)
} else {
// Background opacity
showBackgroundOpacityPanel(ratio)
setBackgroundOpacity(ratio)
}
if (event.action == MotionEvent.ACTION_UP || event.action == MotionEvent.ACTION_CANCEL) {
if (left) {
persistBrightness(ratio)
} else {
persistBackgroundOpacity(ratio)
}
binding.txtBrightness.visibility = View.GONE
binding.txtBackgroundOpacity.visibility = View.GONE
}
true
}
private fun showBrightnessPanel(ratio: Float) {
with(binding.txtBrightness) {
visibility = View.VISIBLE
setBackgroundColor(
ContextCompat.getColor(
this@MainActivity,
R.color.infoPanelBackground
)
)
setTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.infoPanelSelected
)
)
text = getString(R.string.main_brightness, (ratio * 100).toInt())
}
with(binding.txtBackgroundOpacity) {
visibility = View.VISIBLE
setBackgroundColor(0)
setTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.infoPanelDefault
)
)
text = getString(
R.string.main_backgroundOpacity,
((if (isDay()) mainPrefs.backgroundOpacityDay else mainPrefs.backgroundOpacityNight) * 100).toInt()
)
}
}
private fun showBackgroundOpacityPanel(ratio: Float) {
with(binding.txtBackgroundOpacity) {
visibility = View.VISIBLE
setBackgroundColor(
ContextCompat.getColor(
this@MainActivity,
R.color.infoPanelBackground
)
)
setTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.infoPanelSelected
)
)
text = getString(R.string.main_backgroundOpacity, (ratio * 100).toInt())
}
with(binding.txtBrightness) {
visibility = View.VISIBLE
setBackgroundColor(0)
setTextColor(
ContextCompat.getColor(
this@MainActivity,
R.color.infoPanelDefault
)
)
text = getString(
R.string.main_brightness,
((if (isDay()) mainPrefs.brightnessDay else mainPrefs.brightnessNight) * 100).toInt()
)
}
}
/**
* Handler to update the brightness / background opacity periodically.
*/
private val updateBrightnessAndBackgroundOpacityHandler =
@SuppressLint("HandlerLeak")
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(message: Message) {
if (isDay()) {
setBrightness(mainPrefs.brightnessDay)
setBackgroundOpacity(mainPrefs.backgroundOpacityDay)
} else {
setBrightness(mainPrefs.brightnessNight)
setBackgroundOpacity(mainPrefs.backgroundOpacityNight)
}
// Reschedule
sendEmptyMessageDelayed(0, UPDATE_BRIGHTNESS_RATE_MS)
}
}
private fun persistBrightness(value: Float) {
if (isDay()) {
mainPrefs.brightnessDay = value
} else {
mainPrefs.brightnessNight = value
}
}
private fun persistBackgroundOpacity(value: Float) {
if (isDay()) {
mainPrefs.backgroundOpacityDay = value
} else {
mainPrefs.backgroundOpacityNight = value
}
}
private fun isDay(): Boolean {
val location = location
return if (location == null) {
val now = Calendar.getInstance()
val hour = now.get(Calendar.HOUR_OF_DAY)
hour in 8..22
} else {
SunriseSunset.isDay(location.latitude, location.longitude)
}
}
private fun setBrightness(value: Float) {
val sanitizedValue = value.coerceIn(0F, 1F)
val brightnessValue = (sanitizedValue - .5F).coerceAtLeast(0F) * 2F
val layout = window.attributes
layout.screenBrightness = brightnessValue
window.attributes = layout
val alphaValue = sanitizedValue.coerceAtMost(.5F) * 2F
binding.foregroundOpacity.setBackgroundColor(
Color.argb(
(255f * (1f - alphaValue)).toInt(),
0,
0,
0
)
)
}
private fun setBackgroundOpacity(value: Float) {
val sanitizedValue = value.coerceIn(0F, 1F)
binding.backgroundOpacity.setBackgroundColor(
Color.argb(
(255f * (1f - sanitizedValue)).toInt(),
0,
0,
0
)
)
}
// endregion
}
| gpl-3.0 | b68a6ca810327a29965f1c4f26d77d26 | 36.48474 | 138 | 0.575985 | 5.057897 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/manager/search/FriendSearchActivity.kt | 1 | 2749 | package uk.co.appsbystudio.geoshare.friends.manager.search
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.SearchView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_friend_search.*
import uk.co.appsbystudio.geoshare.R
import uk.co.appsbystudio.geoshare.friends.manager.search.adapter.FriendSearchAdapter
class FriendSearchActivity : AppCompatActivity(), FriendSearchView {
private var presenter: FriendSearchPresenter? = null
private var searchAdapter: FriendSearchAdapter? = null
private val userMap = LinkedHashMap<String, String>()
private var oldest: String = ""
private var current: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_friend_search)
presenter = FriendSearchPresenterImpl(this, FriendSearchInteractorImpl())
searchAdapter = FriendSearchAdapter(this, userMap, this)
image_back_button_search.setOnClickListener { finish() }
recycler_results_search.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@FriendSearchActivity)
adapter = searchAdapter
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (!recyclerView.canScrollVertically(1) && current != "") {
presenter?.scroll(oldest, current)
}
}
})
}
search_view_search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(s: String): Boolean {
presenter?.search(s)
current = s
return false
}
})
}
override fun onSendRequest(uid: String) {
presenter?.request(uid)
}
override fun add(uid: String, name: String) {
if (!userMap.contains(uid)) {
userMap[uid] = name
searchAdapter?.notifyDataSetChanged()
oldest = name
}
}
override fun clear() {
searchAdapter?.notifyItemRangeRemoved(0, userMap.size)
userMap.clear()
}
override fun updateRecycler() {
searchAdapter?.notifyDataSetChanged()
}
override fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
} | apache-2.0 | 9c33327ba7e79954e4cf88654076a68c | 31.738095 | 91 | 0.653692 | 5.14794 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/selection/GivenASavedExoPlayerPlaybackEngineType/WhenGettingThePlaybackEngineType.kt | 2 | 2180 | package com.lasthopesoftware.bluewater.client.playback.engine.selection.GivenASavedExoPlayerPlaybackEngineType
import androidx.test.core.app.ApplicationProvider
import com.lasthopesoftware.AndroidContext
import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineType
import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineTypeSelectionPersistence
import com.lasthopesoftware.bluewater.client.playback.engine.selection.SelectedPlaybackEngineTypeAccess
import com.lasthopesoftware.bluewater.client.playback.engine.selection.broadcast.PlaybackEngineTypeChangedBroadcaster
import com.lasthopesoftware.bluewater.settings.repository.ApplicationSettings
import com.lasthopesoftware.bluewater.settings.repository.access.HoldApplicationSettings
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.resources.FakeMessageBus
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WhenGettingThePlaybackEngineType : AndroidContext() {
private var playbackEngineType: PlaybackEngineType? = null
override fun before() {
val applicationSettings = mockk<HoldApplicationSettings>()
every { applicationSettings.promiseApplicationSettings() } returns Promise(ApplicationSettings(playbackEngineTypeName = "ExoPlayer"))
val playbackEngineTypeSelectionPersistence = PlaybackEngineTypeSelectionPersistence(
applicationSettings,
PlaybackEngineTypeChangedBroadcaster(FakeMessageBus(ApplicationProvider.getApplicationContext()))
)
playbackEngineTypeSelectionPersistence.selectPlaybackEngine(PlaybackEngineType.ExoPlayer)
val selectedPlaybackEngineTypeAccess = SelectedPlaybackEngineTypeAccess(applicationSettings) { Promise.empty() }
playbackEngineType =
selectedPlaybackEngineTypeAccess.promiseSelectedPlaybackEngineType().toFuture().get()
}
@Test
fun thenThePlaybackEngineTypeIsExoPlayer() {
assertThat(playbackEngineType).isEqualTo(PlaybackEngineType.ExoPlayer)
}
}
| lgpl-3.0 | 7dd0d554ee9608e2453abb8500375f4f | 53.5 | 135 | 0.841284 | 5.876011 | false | true | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/src/main/kotlin/com/github/shynixn/petblocks/bukkit/logic/business/listener/DependencyHeadDatabaseListener.kt | 1 | 2491 | package com.github.shynixn.petblocks.bukkit.logic.business.listener
import com.github.shynixn.petblocks.api.business.service.DependencyHeadDatabaseService
import com.google.inject.Inject
import me.arcaniax.hdb.api.PlayerClickHeadEvent
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerQuitEvent
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class DependencyHeadDatabaseListener @Inject constructor(private val headDatabaseService: DependencyHeadDatabaseService) : Listener {
/**
* Gets called from HeadDatabase and handles action to the inventory.
*/
@EventHandler
fun playerClickOnHeadEvent(event: PlayerClickHeadEvent) {
val player = event.player
if (event.head == null || event.head!!.type == Material.AIR) {
return
}
val cancelEvent = headDatabaseService.clickInventoryItem(player, event.head)
if (!event.isCancelled && cancelEvent) {
// Other plugins can modify this so check before manipulating.
event.isCancelled = cancelEvent
}
}
/**
* Gets called when the player quits.
*/
@EventHandler
fun onPlayerQuitEvent(event: PlayerQuitEvent) {
headDatabaseService.clearResources(event.player)
}
} | apache-2.0 | 70cafdca69691c90f7191cd50ed70eec | 37.338462 | 133 | 0.731032 | 4.40106 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/computer/RAM.kt | 2 | 2132 | package com.cout970.magneticraft.systems.computer
import com.cout970.magneticraft.api.computer.IRAM
/**
* Created by cout970 on 2016/09/30.
*/
class RAM(val size: Int, val littleEndian: Boolean) : IRAM {
val mem = ByteArray(size)
override fun readByte(addr: Int): Byte {
if (addr < 0 || addr >= memorySize) return 0
return mem[addr]
}
override fun writeByte(addr: Int, data: Byte) {
if (addr < 0 || addr >= memorySize) return
mem[addr] = data
}
override fun writeWord(pos: Int, data: Int) {
val a = (data and 0x000000FF).toByte()
val b = (data and 0x0000FF00 shr 8).toByte()
val c = (data and 0x00FF0000 shr 16).toByte()
val d = (data and 0xFF000000.toInt() shr 24).toByte()
if (littleEndian) {
writeByte(pos, a)
writeByte(pos + 1, b)
writeByte(pos + 2, c)
writeByte(pos + 3, d)
} else {
writeByte(pos, d)
writeByte(pos + 1, c)
writeByte(pos + 2, b)
writeByte(pos + 3, a)
}
}
override fun readWord(pos: Int): Int {
val a = readByte(pos)
val b = readByte(pos + 1)
val c = readByte(pos + 2)
val d = readByte(pos + 3)
return if (littleEndian) {
val ai = a.toInt() and 0xFF
val bi = b.toInt() and 0xFF shl 8
val ci = c.toInt() and 0xFF shl 16
val di = d.toInt() and 0xFF shl 24
ai or bi or ci or di
} else {
val di = d.toInt() and 0xFF
val ci = c.toInt() and 0xFF shl 8
val bi = b.toInt() and 0xFF shl 16
val ai = a.toInt() and 0xFF shl 24
ai or bi or ci or di
}
}
override fun isLittleEndian(): Boolean = littleEndian
override fun getMemorySize(): Int = size
override fun serialize(): Map<String, Any> {
return mapOf("mem" to mem.copyOf())
}
override fun deserialize(map: Map<String, Any>) {
val data = map["mem"] as ByteArray
System.arraycopy(data, 0, mem, 0, size)
}
} | gpl-2.0 | 19c84b562279ac774d6e346c51ef9632 | 25.6625 | 61 | 0.536585 | 3.707826 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/controlpanel/ControlPanelWifiManageNetworksFragment.kt | 1 | 7763 | package io.particle.mesh.ui.controlpanel
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.MainThread
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import io.particle.android.common.easyDiffUtilCallback
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.GetKnownNetworksReply
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.Security.NO_SECURITY
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.Security.UNRECOGNIZED
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.Security.WEP
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.Security.WPA2_PSK
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.Security.WPA_PSK
import io.particle.firmwareprotos.ctrl.wifi.WifiNew.Security.WPA_WPA2_PSK
import io.particle.mesh.common.QATool
import io.particle.mesh.common.truthy
import io.particle.mesh.setup.BarcodeData.CompleteBarcodeData
import io.particle.mesh.setup.connection.ProtocolTransceiver
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.flow.throwOnErrorOrAbsent
import io.particle.mesh.ui.R
import io.particle.mesh.ui.TitleBarOptions
import io.particle.mesh.ui.inflateRow
import kotlinx.android.synthetic.main.fragment_control_panel_wifi_manage_networks.*
import kotlinx.android.synthetic.main.p_mesh_row_wifi_scan.view.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.yield
class ControlPanelWifiManageNetworksFragment : BaseControlPanelFragment() {
override val titleBarOptions = TitleBarOptions(
R.string.p_control_panel_manage_wifi_title,
showBackButton = true,
showCloseButton = false
)
private lateinit var adapter: KnownWifiNetworksAdapter
private var barcode: CompleteBarcodeData? = null
private var transceiver: ProtocolTransceiver? = null
private val scopes = Scopes()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.fragment_control_panel_wifi_manage_networks,
container,
false
)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
adapter = KnownWifiNetworksAdapter(::onWifiNetworkSelected)
recyclerView.adapter = adapter
scopes.onMain {
startFlowWithBarcode { _, barcode ->
this@ControlPanelWifiManageNetworksFragment.barcode = barcode
reloadNetworks()
}
}
}
override fun onStart() {
super.onStart()
barcode?.let { reloadNetworks() }
}
override fun onDestroyView() {
super.onDestroyView()
scopes.cancelChildren()
}
@MainThread
private fun reloadNetworks() {
runWithTransceiver("Error reloading known networks") { xceiver, scopes ->
val reply = scopes.withWorker {
xceiver.sendGetKnownNetworksRequest().throwOnErrorOrAbsent()
}
onNetworksUpdated(reply.networksList)
}
}
@MainThread
private fun onNetworksUpdated(networks: List<GetKnownNetworksReply.Network>?) {
val list = networks?.asSequence()
?.filter { it.ssid.truthy() }
?.distinctBy { it.ssid }
?.map { KnownWifiNetwork(it.ssid, it) }
?.sortedBy { it.ssid }
?.sortedByDescending { it.ssid }
?.toList()
if (list?.isEmpty() == true) {
p_cp_emptyview.isVisible = true
recyclerView.isVisible = false
adapter.submitList(emptyList())
} else {
p_cp_emptyview.isVisible = false
recyclerView.isVisible = true
adapter.submitList(list)
}
}
private fun onWifiNetworkSelected(network: KnownWifiNetwork) {
MaterialDialog.Builder(this.requireContext())
.title("Remove Wi-Fi credentials?")
.content("Are you sure you want to remove Wi-Fi credentials for '${network.ssid}'?")
.positiveText("Remove")
.negativeText(android.R.string.cancel)
.onPositive { _, _ -> removeWifiNetwork(network) }
.show()
}
private fun removeWifiNetwork(toRemove: KnownWifiNetwork) {
flowSystemInterface.showGlobalProgressSpinner(true)
runWithTransceiver("Error removing network ${toRemove.ssid}") { xceiver, scopes ->
scopes.onWorker {
xceiver.sendStartListeningMode()
delay(100)
xceiver.sendRemoveKnownNetworkRequest(toRemove.ssid)
delay(1000)
xceiver.sendStopListeningMode()
scopes.onMain { reloadNetworks() }
}
}
}
private fun runWithTransceiver(
errorMsg: String,
toRun: suspend (ProtocolTransceiver, Scopes) -> Unit
) {
flowSystemInterface.showGlobalProgressSpinner(true)
var connected = false
scopes.onMain {
val xceiver = transceiver
try {
if (xceiver == null || !xceiver.isConnected) {
transceiver = flowRunner.getProtocolTransceiver(barcode!!, scopes)
}
connected = transceiver != null
flowSystemInterface.showGlobalProgressSpinner(true)
toRun(transceiver!!, scopes)
} catch (ex: Exception) {
QATool.log(ex.toString())
val error = if (connected) errorMsg else "Error connecting to device"
flowSystemInterface.dialogHack.newSnackbarRequest(error)
if (isAdded) {
findNavController().popBackStack()
}
} finally {
flowSystemInterface.showGlobalProgressSpinner(false)
}
}
}
}
private data class KnownWifiNetwork(
val ssid: String,
val network: GetKnownNetworksReply.Network?
)
private class KnownWifiNetworkHolder(var rowRoot: View) : RecyclerView.ViewHolder(rowRoot) {
val ssid = rowRoot.p_scanforwifi_ssid
val securityIcon = rowRoot.p_scanforwifi_security_icon
val strengthIcon = rowRoot.p_scanforwifi_strength_icon
init {
strengthIcon.isVisible = false
}
}
private class KnownWifiNetworksAdapter(
private val onItemClicked: (KnownWifiNetwork) -> Unit
) : ListAdapter<KnownWifiNetwork, KnownWifiNetworkHolder>(
easyDiffUtilCallback { rowEntry: KnownWifiNetwork -> rowEntry.ssid }
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KnownWifiNetworkHolder {
return KnownWifiNetworkHolder(parent.inflateRow(R.layout.p_mesh_row_wifi_scan))
}
override fun onBindViewHolder(holder: KnownWifiNetworkHolder, position: Int) {
val item = getItem(position)
holder.ssid.text = item.ssid
holder.securityIcon.isVisible = item.network?.isSecureNetwork ?: false
holder.rowRoot.setOnClickListener { onItemClicked(item) }
}
}
private val GetKnownNetworksReply.Network.isSecureNetwork: Boolean
get() {
return when (this.security) {
WEP,
WPA_PSK,
WPA2_PSK,
WPA_WPA2_PSK -> true
NO_SECURITY,
UNRECOGNIZED,
null -> false
}
} | apache-2.0 | a48ddef633eec8055b02625a34ee0b6f | 33.353982 | 100 | 0.669071 | 4.750918 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/core/logging/Logger.kt | 1 | 830 | package com.waz.zclient.core.logging
import android.util.Log
import com.waz.zclient.core.extension.empty
class Logger private constructor() {
companion object {
@JvmStatic
fun warn(tag: String, log: String) = Log.w(tag, log)
@JvmStatic
fun warn(tag: String, log: String, throwable: Throwable) = Log.w(tag, log, throwable)
@JvmStatic
fun info(tag: String, log: String) = Log.i(tag, log)
@JvmStatic
fun verbose(tag: String, log: String) = Log.v(tag, log)
@JvmStatic
fun debug(tag: String, log: String) = Log.d(tag, log)
@JvmStatic
fun error(tag: String, log: String) = Log.e(tag, log)
@JvmStatic
fun error(tag: String, log: String = String.empty(), throwable: Throwable) = Log.e(tag, log, throwable)
}
}
| gpl-3.0 | 97c0c39f73dd536916fb3e7174f9efb3 | 27.62069 | 111 | 0.615663 | 3.577586 | false | false | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/polyline/PolylineWidthControlFragment.kt | 1 | 2480 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kotlindemos.polyline
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.TextView
import com.example.kotlindemos.R
/**
* Fragment with "width" UI controls for Polylines, to be used in ViewPager.
*/
class PolylineWidthControlFragment : PolylineControlFragment(), SeekBar.OnSeekBarChangeListener {
private lateinit var widthBar: SeekBar
private lateinit var widthTextView: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?): View {
val view = inflater.inflate(R.layout.polyline_width_control_fragment, container, false)
widthBar = view.findViewById(R.id.widthSeekBar)
widthBar.max = WIDTH_MAX
widthBar.setOnSeekBarChangeListener(this)
widthTextView = view.findViewById(R.id.widthTextView)
return view
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
// Don't do anything here.
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
// Don't do anything here.
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
val polyline = polyline ?: return
polyline.width = progress.toFloat()
widthTextView.text = polyline.width.toString() + "px"
}
override fun refresh() {
val polyline = polyline
if (polyline == null) {
widthBar.isEnabled = false
widthBar.progress = 0
widthTextView.text = ""
return
}
widthBar.isEnabled = true
val width: Float = polyline.width
widthBar.progress = width.toInt()
widthTextView.text = width.toString() + "px"
}
companion object {
private const val WIDTH_MAX = 50
}
} | apache-2.0 | d6a1701b30d70e86f5125da25cb9f9b0 | 32.527027 | 103 | 0.691935 | 4.550459 | false | false | false | false |
bachhuberdesign/deck-builder-gwent | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/shared/base/BaseActivity.kt | 1 | 2038 | package com.bachhuberdesign.deckbuildergwent.features.shared.base
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.bachhuberdesign.deckbuildergwent.App
import com.bachhuberdesign.deckbuildergwent.inject.ActivityComponent
import com.bachhuberdesign.deckbuildergwent.inject.DaggerPersistedComponent
import com.bachhuberdesign.deckbuildergwent.inject.PersistedComponent
import com.bachhuberdesign.deckbuildergwent.inject.module.ActivityModule
import java.util.concurrent.atomic.AtomicLong
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
open class BaseActivity : AppCompatActivity() {
companion object {
@JvmStatic val TAG: String = BaseActivity::class.java.name
@JvmStatic private val NEXT_ID: AtomicLong = AtomicLong(0)
@JvmStatic private val components = HashMap<Long, PersistedComponent>()
}
var activityId: Long = 0
lateinit var activityComponent: ActivityComponent
lateinit var persistedComponent: PersistedComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityId = savedInstanceState?.getLong(TAG) ?: NEXT_ID.getAndIncrement()
if (!components.containsKey(activityId)) {
persistedComponent = DaggerPersistedComponent.builder()
.applicationComponent(App.applicationComponent)
.build()
components.put(activityId, persistedComponent)
} else {
persistedComponent = components[activityId] as PersistedComponent
}
activityComponent = persistedComponent.activitySubcomponent(ActivityModule(this))
activityComponent.inject(this)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putLong(TAG, activityId)
super.onSaveInstanceState(outState)
}
override fun onDestroy() {
when {
!isChangingConfigurations -> components.remove(activityId)
}
super.onDestroy()
}
}
| apache-2.0 | f14bae556efc62970f19937859cbcc56 | 33.542373 | 89 | 0.724239 | 5.307292 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/ui/AccountSettingsActivity.kt | 1 | 8959 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui
import android.accounts.Account
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.SyncStatusObserver
import android.os.Bundle
import android.provider.CalendarContract
import android.support.v4.app.LoaderManager
import android.support.v4.app.NavUtils
import android.support.v4.content.AsyncTaskLoader
import android.support.v4.content.Loader
import android.support.v7.preference.*
import android.text.TextUtils
import android.view.MenuItem
import com.etesync.syncadapter.AccountSettings
import com.etesync.syncadapter.App
import com.etesync.syncadapter.Constants.KEY_ACCOUNT
import com.etesync.syncadapter.InvalidAccountException
import com.etesync.syncadapter.R
import com.etesync.syncadapter.ui.setup.LoginCredentials
import com.etesync.syncadapter.ui.setup.LoginCredentialsChangeFragment
class AccountSettingsActivity : BaseActivity() {
private lateinit var account: Account
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
account = intent.getParcelableExtra(KEY_ACCOUNT)
title = getString(R.string.settings_title, account.name)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
if (savedInstanceState == null) {
val frag = AccountSettingsFragment()
frag.arguments = intent.extras
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, frag)
.commit()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
val intent = Intent(this, AccountActivity::class.java)
intent.putExtra(AccountActivity.EXTRA_ACCOUNT, account)
NavUtils.navigateUpTo(this, intent)
return true
} else
return false
}
class AccountSettingsFragment : PreferenceFragmentCompat(), LoaderManager.LoaderCallbacks<AccountSettings> {
internal lateinit var account: Account
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
account = arguments?.getParcelable(KEY_ACCOUNT)!!
loaderManager.initLoader(0, arguments, this)
}
override fun onCreatePreferences(bundle: Bundle, s: String) {
addPreferencesFromResource(R.xml.settings_account)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<AccountSettings> {
return AccountSettingsLoader(context!!, args!!.getParcelable(KEY_ACCOUNT) as Account)
}
override fun onLoadFinished(loader: Loader<AccountSettings>, settings: AccountSettings?) {
if (settings == null) {
activity!!.finish()
return
}
// category: authentication
val prefPassword = findPreference("password") as EditTextPreference
prefPassword.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val credentials = if (newValue != null) LoginCredentials(settings.uri, account.name, newValue as String) else null
LoginCredentialsChangeFragment.newInstance(account, credentials!!).show(fragmentManager!!, null)
loaderManager.restartLoader(0, arguments, this@AccountSettingsFragment)
false
}
// Category: encryption
val prefEncryptionPassword = findPreference("encryption_password")
prefEncryptionPassword.onPreferenceClickListener = Preference.OnPreferenceClickListener { _ ->
startActivity(ChangeEncryptionPasswordActivity.newIntent(activity!!, account))
true
}
// category: synchronization
val prefSyncContacts = findPreference("sync_interval_contacts") as ListPreference
val syncIntervalContacts = settings.getSyncInterval(App.addressBooksAuthority)
if (syncIntervalContacts != null) {
prefSyncContacts.value = syncIntervalContacts.toString()
if (syncIntervalContacts == AccountSettings.SYNC_INTERVAL_MANUALLY)
prefSyncContacts.setSummary(R.string.settings_sync_summary_manually)
else
prefSyncContacts.summary = getString(R.string.settings_sync_summary_periodically, prefSyncContacts.entry)
prefSyncContacts.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
settings.setSyncInterval(App.addressBooksAuthority, java.lang.Long.parseLong(newValue as String))
loaderManager.restartLoader(0, arguments, this@AccountSettingsFragment)
false
}
} else {
prefSyncContacts.isEnabled = false
prefSyncContacts.setSummary(R.string.settings_sync_summary_not_available)
}
val prefSyncCalendars = findPreference("sync_interval_calendars") as ListPreference
val syncIntervalCalendars = settings.getSyncInterval(CalendarContract.AUTHORITY)
if (syncIntervalCalendars != null) {
prefSyncCalendars.value = syncIntervalCalendars.toString()
if (syncIntervalCalendars == AccountSettings.SYNC_INTERVAL_MANUALLY)
prefSyncCalendars.setSummary(R.string.settings_sync_summary_manually)
else
prefSyncCalendars.summary = getString(R.string.settings_sync_summary_periodically, prefSyncCalendars.entry)
prefSyncCalendars.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
settings.setSyncInterval(CalendarContract.AUTHORITY, java.lang.Long.parseLong(newValue as String))
loaderManager.restartLoader(0, arguments, this@AccountSettingsFragment)
false
}
} else {
prefSyncCalendars.isEnabled = false
prefSyncCalendars.setSummary(R.string.settings_sync_summary_not_available)
}
val prefWifiOnly = findPreference("sync_wifi_only") as SwitchPreferenceCompat
prefWifiOnly.isChecked = settings.syncWifiOnly
prefWifiOnly.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, wifiOnly ->
settings.setSyncWiFiOnly(wifiOnly as Boolean)
loaderManager.restartLoader(0, arguments, this@AccountSettingsFragment)
false
}
val prefWifiOnlySSID = findPreference("sync_wifi_only_ssid") as EditTextPreference
val onlySSID = settings.syncWifiOnlySSID
prefWifiOnlySSID.text = onlySSID
if (onlySSID != null)
prefWifiOnlySSID.summary = getString(R.string.settings_sync_wifi_only_ssid_on, onlySSID)
else
prefWifiOnlySSID.setSummary(R.string.settings_sync_wifi_only_ssid_off)
prefWifiOnlySSID.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val ssid = newValue as String
settings.syncWifiOnlySSID = if (!TextUtils.isEmpty(ssid)) ssid else null
loaderManager.restartLoader(0, arguments, this@AccountSettingsFragment)
false
}
}
override fun onLoaderReset(loader: Loader<AccountSettings>) {}
}
private class AccountSettingsLoader(context: Context, internal val account: Account) : AsyncTaskLoader<AccountSettings>(context), SyncStatusObserver {
internal lateinit var listenerHandle: Any
override fun onStartLoading() {
forceLoad()
listenerHandle = ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, this)
}
override fun onStopLoading() {
ContentResolver.removeStatusChangeListener(listenerHandle)
}
override fun abandon() {
onStopLoading()
}
override fun loadInBackground(): AccountSettings? {
val settings: AccountSettings
try {
settings = AccountSettings(context, account)
} catch (e: InvalidAccountException) {
return null
}
return settings
}
override fun onStatusChanged(which: Int) {
App.log.fine("Reloading account settings")
forceLoad()
}
}
}
| gpl-3.0 | e2cb18947a95e0ab877bb4664089b172 | 42.901961 | 154 | 0.667597 | 5.481028 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/control/CommandLeaveGuild.kt | 1 | 948 | package me.mrkirby153.KirBot.command.control
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.AdminCommand
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.utils.Context
import net.dv8tion.jda.api.sharding.ShardManager
import javax.inject.Inject
class CommandLeaveGuild @Inject constructor(private val shardManager: ShardManager){
@Command(name = "leaveGuild", arguments = ["<guild:string>"])
@AdminCommand
fun execute(context: Context, cmdContext: CommandContext) {
val id = cmdContext.get<String>("guild")!!
if (shardManager.getGuildById(id) == null) {
throw CommandException("I am not a member of this guild")
}
shardManager.getGuildById(id)?.leave()?.queue {
context.success()
}
}
} | mit | b9495c5a07ff1499819cd9a63826c5cf | 31.724138 | 84 | 0.734177 | 4.086207 | false | false | false | false |
google/ksp | test-utils/testData/api/annotationWithJavaTypeValue.kt | 1 | 2189 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TEST PROCESSOR: AnnotationJavaTypeValueProcessor
// EXPECTED:
// JavaAnnotated
// JavaAnnotation ->
// primitives = [Character, Boolean, Byte, Short, Integer, Long, Float, Double]
// objects = [Character, Boolean, Byte, Short, Integer, Long, Float, Double]
// primitiveArrays = [Array<Character>, Array<Boolean>, Array<Byte>, Array<Short>, Array<Integer>, Array<Long>, Array<Float>, Array<Double>]
// objectArrays = [Array<Character>, Array<Boolean>, Array<Byte>, Array<Short>, Array<Integer>, Array<Long>, Array<Float>, Array<Double>, Array<String>, Array<Object>]
// END
// FILE: a.kt
// FILE: JavaAnnotation.java
public @ interface JavaAnnotation {
Class[] primitives(); // PsiPrimitiveType
Class[] objects(); // PsiType
Class[] primitiveArrays(); // PsiArrayType
Class[] objectArrays(); // PsiArrayType
}
// FILE: JavaAnnotated.java
import java.util.*;
@JavaAnnotation(
primitives = { char.class, boolean .class, byte.class, short.class, int.class, long.class, float.class, double.class },
objects = { Character.class, Boolean .class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class },
primitiveArrays = { char[].class, boolean [].class, byte[].class, short[].class, int[].class, long[].class, float[].class, double[].class },
objectArrays = { Character[].class, Boolean [].class, Byte[].class, Short[].class, Integer[].class, Long[].class, Float[].class, Double[].class, String[].class, Object[].class }
)
public class JavaAnnotated {
}
| apache-2.0 | 2e667c7fff3a03759bd179e6a6e5eecb | 43.673469 | 181 | 0.713568 | 3.840351 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdAttributeIdValueImpl.kt | 1 | 5022 | // Copyright (c) 2015-2020 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.tree.IElementType
import com.intellij.util.IncorrectOperationException
import com.intellij.util.Processor
import com.vladsch.flexmark.html.renderer.HtmlIdGenerator
import com.vladsch.md.nav.psi.reference.MdPsiReference
import com.vladsch.md.nav.psi.util.MdIndexUtil
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTypes
import icons.MdIcons
import javax.swing.Icon
class MdAttributeIdValueImpl(node: ASTNode) : MdNamedElementImpl(node), MdAttributeIdValue {
companion object {
@JvmStatic
fun normalizeReferenceText(referenceId: String?): String {
return referenceId ?: ""
}
}
override fun getReferenceId(): String {
return text
}
override fun normalizeReferenceId(referenceId: String?): String {
return normalizeReferenceText(referenceId)
}
override fun getReferenceIdentifier(): MdReferenceElementIdentifier? {
return this
}
override fun getReferenceDisplayName(): String {
return referenceId
}
override fun getAnchorReferenceElement(): PsiElement? {
return this
}
override fun getReferencingElementText(): String? {
return null
}
override fun isReferenceFor(referenceId: String?): Boolean {
return getReferenceId() == referenceId
}
override fun getReferenceType(): IElementType {
return MdTypes.ATTRIBUTE_ID_VALUE
}
override fun isReferenceFor(refElement: MdLinkAnchor?): Boolean {
if (refElement == null) return false
val refElementName = refElement.name
return refElementName.equals(anchorReferenceId, ignoreCase = true)
}
override fun getCompletionTypeText(): String {
val element = MdPsiImplUtil.findAncestorOfType(this, MdHeaderElement::class.java)
return if (element is MdHeaderElement) {
element.completionTypeText
} else {
"{#$text}"
}
}
override fun getAnchorReferenceId(): String? {
return referenceId
}
override fun getAnchorReferenceId(generator: HtmlIdGenerator?): String? {
return referenceId
}
override fun getAttributedAnchorReferenceId(): String? {
return referenceId
}
override fun getAttributedAnchorReferenceId(htmlIdGenerator: HtmlIdGenerator?): String? {
return referenceId
}
override fun getAttributesElement(): MdAttributes? {
return parent as MdAttributes?
}
override fun getIdValueAttribute(): MdAttributeIdValue? {
return this
}
override fun getReferenceElement(): PsiElement {
return this
}
@Throws(IncorrectOperationException::class)
override fun handleContentChange(range: TextRange, newContent: String): MdAttributeIdValue {
return handleContentChange(newContent)
}
@Throws(IncorrectOperationException::class)
override fun handleContentChange(newContent: String): MdAttributeIdValue {
return setName(newContent, MdNamedElement.REASON_FILE_RENAMED) as MdAttributeIdValue
}
override fun isReferenceFor(refElement: MdReferencingElement?): Boolean {
return refElement != null && isReferenceFor(refElement.referenceId)
}
override fun isReferenced(): Boolean {
var isReferenced = false
MdIndexUtil.processReferences(this, GlobalSearchScope.projectScope(project), Processor {
isReferenced = true
false
})
return isReferenced
}
override fun createReference(textRange: TextRange, exactReference: Boolean): MdPsiReference? {
return MdPsiReference(this, textRange, exactReference)
}
override fun getDisplayName(): String {
return name
}
override fun getIcon(flags: Int): Icon? {
return MdIcons.Element.ATTRIBUTE_ID_VALUE
}
override fun setName(newName: String, reason: Int): PsiElement? {
val element = MdPsiImplUtil.setAttributeIdValueName(parent as MdAttributeImpl, newName)
return element.attributeValueElement
}
override fun getTypeText(): String? {
val pos = text.indexOf(':')
if (pos > -1) {
return text.substring(0, pos)
}
return ""
}
override fun setType(newName: String, reason: Int): MdAttributeIdValue? {
val element = MdPsiImplUtil.setAttributeIdValueType(parent as MdAttributeImpl, newName)
return element.attributeValueElement as MdAttributeIdValue?
}
override fun toString(): String {
return "ID_ATTRIBUTE_VALUE '" + name + "' " + super.hashCode()
}
}
| apache-2.0 | 736936538ef2f27139961ccc47a67d67 | 30.78481 | 177 | 0.697332 | 4.972277 | false | false | false | false |
canou/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/extensions/File.kt | 1 | 3488 | package com.simplemobiletools.commons.extensions
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.media.MediaMetadataRetriever
import android.webkit.MimeTypeMap
import java.io.File
fun File.isImageVideoGif() = absolutePath.isImageFast() || absolutePath.isVideoFast() || absolutePath.isGif()
fun File.isGif() = absolutePath.endsWith(".gif", true)
fun File.isVideoFast() = absolutePath.videoExtensions.any { absolutePath.endsWith(it, true) }
fun File.isImageFast() = absolutePath.photoExtensions.any { absolutePath.endsWith(it, true) }
fun File.isImageSlow() = absolutePath.isImageFast() || getMimeType().startsWith("image")
fun File.isVideoSlow() = absolutePath.isVideoFast() || getMimeType().startsWith("video")
fun File.isAudioSlow() = getMimeType().startsWith("audio")
fun File.getMimeType(default: String = getDefaultMimeType()): String {
try {
val extension = MimeTypeMap.getFileExtensionFromUrl(absolutePath)
if (extension != null) {
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
}
} catch (ignored: Exception) {
}
return default
}
fun File.getDefaultMimeType() = if (isVideoFast()) "video/*" else if (isImageFast()) "image/*" else if (isGif()) "image/gif" else absolutePath.getMimeTypeFromPath()
fun File.getDuration(): String? {
try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(absolutePath)
val time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
val timeInMs = java.lang.Long.parseLong(time)
return (timeInMs / 1000).toInt().getFormattedDuration()
} catch (e: Exception) {
return null
}
}
fun File.getArtist(): String? {
try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(absolutePath)
return retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
} catch (ignored: Exception) {
return null
}
}
fun File.getAlbum(): String? {
try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(absolutePath)
return retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)
} catch (ignored: Exception) {
return null
}
}
fun File.getResolution(): Point {
return if (isImageFast() || isImageSlow()) {
getImageResolution()
} else if (isVideoFast() || isVideoSlow()) {
getVideoResolution()
} else {
return Point(0, 0)
}
}
fun File.getVideoResolution(): Point {
try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(absolutePath)
val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH).toInt()
val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT).toInt()
return Point(width, height)
} catch (ignored: Exception) {
}
return Point(0, 0)
}
fun File.getImageResolution(): Point {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(absolutePath, options)
return Point(options.outWidth, options.outHeight)
}
fun File.getCompressionFormat(): Bitmap.CompressFormat {
return when (extension.toLowerCase()) {
"png" -> Bitmap.CompressFormat.PNG
"webp" -> Bitmap.CompressFormat.WEBP
else -> Bitmap.CompressFormat.JPEG
}
}
| apache-2.0 | d40781dc63b1715ae67a92c0ddf19703 | 33.88 | 164 | 0.703842 | 4.613757 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/ui/base/BaseFragment.kt | 1 | 2939 | package com.booboot.vndbandroid.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.booboot.vndbandroid.App
import com.booboot.vndbandroid.extensions.home
import com.booboot.vndbandroid.extensions.openVN
import com.booboot.vndbandroid.extensions.removeFocus
import com.booboot.vndbandroid.extensions.startParentEnterTransition
import com.booboot.vndbandroid.extensions.toggle
import com.booboot.vndbandroid.model.vndb.VN
import com.booboot.vndbandroid.ui.vndetails.VNDetailsFragment
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.progress_bar.*
import kotlinx.android.synthetic.main.vn_card.view.*
import kotlinx.android.synthetic.main.vnlist_fragment.*
abstract class BaseFragment<T : BaseViewModel> : Fragment() {
abstract val layout: Int
open val softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
lateinit var rootView: View
lateinit var viewModel: T
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedElementEnterTransition = App.context.enterTransition
sharedElementReturnTransition = App.context.enterTransition
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (parentFragment !is BaseFragment<*>) {
activity?.window?.setSoftInputMode(softInputMode)
/* Hiding the keyboard when leaving a Fragment */
removeFocus()
}
rootView = inflater.inflate(layout, container, false)
return rootView
}
fun onError() {
startPostponedEnterTransition()
startParentEnterTransition()
}
open fun showError(message: String) {
onError()
val view = activity?.findViewById<View>(android.R.id.content) ?: return
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show()
}
open fun showLoading(loading: Int) {
progressBar?.visibility = if (loading > 0) View.VISIBLE else View.GONE
refreshLayout?.isRefreshing = loading > 0
}
@CallSuper
protected open fun onAdapterUpdate(empty: Boolean) {
backgroundInfo?.toggle(empty)
}
fun vnDetailsFragment() = parentFragment as? VNDetailsFragment
open fun scrollToTop() {}
fun onVnClicked(view: View, vn: VN?) {
vn ?: return
findNavController().openVN(vn, view.image)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (::viewModel.isInitialized) {
viewModel.saveState(outState)
}
}
fun finish() {
home()?.onSupportNavigateUp()
}
} | gpl-3.0 | 0582b2cf0a494b99b8ade9964799251f | 32.793103 | 115 | 0.726438 | 4.747981 | false | false | false | false |
JimSeker/ui | ListViews/ListviewFragmentDemo_kt/app/src/main/java/edu/cs4730/listviewfragmentdemo_kt/titlefrag.kt | 1 | 2407 | package edu.cs4730.listviewfragmentdemo_kt
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.widget.ArrayAdapter
import android.app.Activity
import android.content.Context
import android.view.View
import android.widget.ListView
import androidx.fragment.app.ListFragment
import java.lang.ClassCastException
/**
* this ia listfragment. All we need to do is setlistadapter in onCreateView (there is no layout)
* and override onListItemClick. Since we also have callbacks, also deal with those.
*/
class titlefrag : ListFragment() {
/**
* The fragment's current callback object, which is notified of list item clicks.
*/
private var mListener: OnFragmentInteractionListener? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.listfragment_layout, container, false)
val adapter =
ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, Shakespeare.TITLES)
listAdapter = adapter
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
val activity: Activity? = activity
mListener = try {
activity as OnFragmentInteractionListener?
} catch (e: ClassCastException) {
throw ClassCastException(
activity.toString()
+ " must implement OnFragmentInteractionListener"
)
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
override fun onListItemClick(listView: ListView, view: View, position: Int, id: Long) {
super.onListItemClick(listView, view, position, id)
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
if (mListener != null) mListener!!.onItemSelected(position)
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
interface OnFragmentInteractionListener {
/**
* Callback for when an item has been selected.
*/
fun onItemSelected(id: Int)
}
} | apache-2.0 | 299ea402ef60c5ce95082bce9532cf2e | 31.986301 | 100 | 0.672622 | 4.993776 | false | false | false | false |
Arasthel/SpannedGridLayoutManager | sample/src/main/java/com/arasthel/spannedgridlayoutmanager/sample/MainActivity.kt | 1 | 1879 | package com.arasthel.spannedgridlayoutmanager.sample
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import com.arasthel.spannedgridlayoutmanager.SpanSize
import com.arasthel.spannedgridlayoutmanager.SpannedGridLayoutManager
import com.arasthel.spannedgridlayoutmanager.SpannedGridLayoutManager.Orientation.*
/**
* Created by Jorge Martín on 24/5/17.
*/
class MainActivity: android.support.v7.app.AppCompatActivity() {
val recyclerview: RecyclerView by lazy { findViewById<RecyclerView>(R.id.recyclerView) }
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spannedGridLayoutManager = SpannedGridLayoutManager(orientation = VERTICAL, spans = 4)
spannedGridLayoutManager.itemOrderIsStable = true
recyclerview.layoutManager = spannedGridLayoutManager
recyclerview.addItemDecoration(SpaceItemDecorator(left = 10, top = 10, right = 10, bottom = 10))
val adapter = GridItemAdapter()
if (savedInstanceState != null && savedInstanceState.containsKey("clicked")) {
val clicked = savedInstanceState.getBooleanArray("clicked")!!
adapter.clickedItems.clear()
adapter.clickedItems.addAll(clicked.toList())
}
spannedGridLayoutManager.spanSizeLookup = SpannedGridLayoutManager.SpanSizeLookup { position ->
if (adapter.clickedItems[position]) {
SpanSize(2, 2)
} else {
SpanSize(1, 1)
}
}
recyclerview.adapter = adapter
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putBooleanArray("clicked", (recyclerview.adapter as GridItemAdapter).clickedItems.toBooleanArray())
}
} | mit | 2a33b388b5554e91b31bfc8e719b1ea5 | 33.796296 | 117 | 0.71246 | 5.061995 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/LocaleLinting.kt | 1 | 3946 | /*
* Copyright (c) 2022 David Allison <davidallisongithub@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki
import com.ichi2.testutils.EmptyApplication
import com.ichi2.testutils.LintTests
import com.ichi2.utils.LanguageUtil
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.not
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.experimental.categories.Category
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.ParameterizedRobolectricTestRunner.Parameters
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import timber.log.Timber
import java.util.*
/**
* Linting to ensure that all locales have valid strings
*/
@RunWith(ParameterizedRobolectricTestRunner::class)
@Category(LintTests::class) // not yet supported by gradle: https://issues.gradle.org/browse/GRADLE-2111
@Config(application = EmptyApplication::class) // no point in Application init if we don't use it
class LocaleLinting(private val locale: Locale) : RobolectricTest() {
@Before
override fun setUp() {
super.setUp()
RuntimeEnvironment.setQualifiers(locale.language)
}
companion object {
@Parameters(name = "{0}")
@JvmStatic // required for initParameters
@Suppress("unused")
fun initParameters(): Collection<Locale> {
return LanguageUtil.APP_LANGUAGES.map(::toLocale)
}
private fun toLocale(localeCode: String): Locale {
return if (localeCode.contains("_") || localeCode.contains("-")) {
try {
val localeParts: Array<String> = localeCode.split("[_-]".toRegex(), 2).toTypedArray()
Locale(localeParts[0], localeParts[1])
} catch (e: ArrayIndexOutOfBoundsException) {
Timber.w(e, "LanguageUtil::getLocale variant split fail, using code '%s' raw.", localeCode)
Locale(localeCode)
}
} else {
Locale(localeCode)
}
}
}
@Test
fun sample_answer_has_different_second_word() {
// the point of the sample answer is to show letter differences, not just extra words, for example:
// an example -> exomple
val sample = targetContext.getString(R.string.basic_answer_sample_text)
val sampleUser = targetContext.getString(R.string.basic_answer_sample_text_user)
assertThat(
"'$sample' should differ from '$sampleUser'. " +
"These strings are used in the type the answer diffs, and the user should see all examples of problems. " +
"see: basic_answer_sample_text and basic_answer_sample_text_user",
sample,
not(equalTo(sampleUser))
)
val lastWord = sample.split(" ").last()
assertThat(
"the last word of '$sample' should differ from '$sampleUser'. " +
"These are used in the type the answer diffs, and the user should see all examples of problems " +
"see: basic_answer_sample_text and basic_answer_sample_text_user",
lastWord,
not(equalTo(sampleUser))
)
}
}
| gpl-3.0 | d385f3f631bf8b0fa354b267009a1b15 | 39.680412 | 123 | 0.671313 | 4.463801 | false | true | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/ProcessInstance.kt | 1 | 54469 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine
import net.devrieze.util.*
import net.devrieze.util.collection.replaceBy
import net.devrieze.util.security.SYSTEMPRINCIPAL
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.IMessageService
import nl.adaptivity.process.ProcessConsts
import nl.adaptivity.process.engine.impl.*
import nl.adaptivity.process.engine.processModel.*
import nl.adaptivity.process.processModel.EndNode
import nl.adaptivity.process.processModel.Split
import nl.adaptivity.process.processModel.engine.*
import nl.adaptivity.process.util.Constants
import nl.adaptivity.process.util.Identified
import nl.adaptivity.process.util.writeHandleAttr
import nl.adaptivity.util.multiplatform.UUID
import nl.adaptivity.util.multiplatform.assert
import nl.adaptivity.util.multiplatform.initCauseCompat
import nl.adaptivity.util.multiplatform.randomUUID
import nl.adaptivity.util.security.Principal
import nl.adaptivity.xmlutil.*
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
import kotlin.jvm.JvmStatic
import kotlin.jvm.Synchronized
@RequiresOptIn("Not safe access to store stuff")
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
annotation class ProcessInstanceStorage
class ProcessInstance : MutableHandleAware<SecureObject<ProcessInstance>>, SecureObject<ProcessInstance>, IProcessInstance {
private class InstanceFuture<T : ProcessNodeInstance<*>, N : ExecutableProcessNode>(val origBuilder: ProcessNodeInstance.Builder<out ExecutableProcessNode, out T>) :
Future<T> {
private var cancelled = false
private var updated: T? = null
var origSetInvocation: Exception? = null
override fun isCancelled() = cancelled
override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
return if (updated != null || cancelled) return true else {
cancelled = true
true
}
}
override fun get(): T {
if (cancelled) throw CancellationException()
return updated ?: throw IllegalStateException("No value known yet")
}
override fun get(timeout: Long, unit: TimeUnit) = get()
fun set(value: T) {
if (cancelled) throw CancellationException()
if (updated != null) throw IllegalStateException("Value already set").apply {
origSetInvocation?.let { initCauseCompat(it) }
}
assert(run { origSetInvocation = Exception("Original set stacktrace"); true })
updated = value
}
override fun isDone() = updated != null
override fun toString(): String {
return "-> ${if (updated != null) "!$updated" else origBuilder.toString()}"
}
}
interface Builder : ProcessInstanceContext, IProcessInstance {
val generation: Int
val pendingChildren: List<Future<out ProcessNodeInstance<*>>>
override var handle: Handle<SecureObject<ProcessInstance>>
var parentActivity: Handle<SecureObject<ProcessNodeInstance<*>>>
var owner: Principal
override var processModel: ExecutableModelCommon
var instancename: String?
var uuid: UUID
var state: State
val children: List<Handle<SecureObject<ProcessNodeInstance<*>>>>
override val inputs: MutableList<ProcessData>
val outputs: MutableList<ProcessData>
fun build(data: MutableProcessEngineDataAccess): ProcessInstance
fun <T : ProcessNodeInstance<*>> storeChild(child: T): Future<T>
override fun getChildNodeInstance(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): IProcessNodeInstance =
allChildNodeInstances { it.handle == handle }.first()
fun getChildBuilder(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): ProcessNodeInstance.ExtBuilder<*, *>
fun <N : ExecutableProcessNode> getChildNodeInstance(node: N, entryNo: Int): ProcessNodeInstance.Builder<N, *>? =
getChildren(node).firstOrNull { it.entryNo == entryNo }
fun <N : ExecutableProcessNode> getChildren(node: N): Sequence<ProcessNodeInstance.Builder<N, *>>
fun <T : ProcessNodeInstance<*>> storeChild(child: ProcessNodeInstance.Builder<out ExecutableProcessNode, T>): Future<T>
fun <N : ExecutableProcessNode> updateChild(
node: N,
entryNo: Int,
body: ProcessNodeInstance.Builder<out ExecutableProcessNode, *>.() -> Unit
)
override fun allChildNodeInstances(): Sequence<IProcessNodeInstance>
fun allChildNodeInstances(childFilter: (IProcessNodeInstance) -> Boolean): Sequence<IProcessNodeInstance>
fun active(): Sequence<IProcessNodeInstance> {
return allChildNodeInstances { !it.state.isFinal }
}
/**
* Store the current instance to the database. This
*/
fun store(data: MutableProcessEngineDataAccess)
fun getDirectSuccessorsFor(predecessor: Handle<SecureObject<ProcessNodeInstance<*>>>): Sequence<IProcessNodeInstance> {
return allChildNodeInstances { predecessor in it.predecessors }
}
fun updateSplits(engineData: MutableProcessEngineDataAccess) {
for (split in allChildNodeInstances { !it.state.isFinal && it.node is Split }) {
if (split.state != NodeInstanceState.Pending) {
updateChild(split) {
if ((this as SplitInstance.Builder).updateState(engineData) && !state.isFinal) {
state = NodeInstanceState.Complete
startSuccessors(engineData, this) // XXX evaluate whether this is needed
engineData.queueTickle(this@Builder.handle)
}
}
}
}
}
fun updateState(engineData: MutableProcessEngineDataAccess) {
if (state == State.STARTED) {
if (active().none()) { // do finish
finish(engineData)
}
}
}
fun startSuccessors(engineData: MutableProcessEngineDataAccess, predecessor: IProcessNodeInstance) {
assert((predecessor.state.isFinal) || (predecessor !is SplitInstance)) {
"The predecessor $predecessor is not final when starting successors"
}
val startedTasks = ArrayList<ProcessNodeInstance.Builder<*, *>>(predecessor.node.successors.size)
val joinsToEvaluate = ArrayList<JoinInstance.Builder>()
val nodesToSkipSuccessorsOf = mutableListOf<ProcessNodeInstance.Builder<*, *>>()
val nodesToSkipPredecessorsOf = ArrayDeque<ProcessNodeInstance.Builder<*, *>>()
for (successorId in predecessor.node.successors) {
val nonRegisteredNodeInstance = processModel
.getNode(successorId.id)
.mustExist(successorId)
.createOrReuseInstance(engineData, this, predecessor, predecessor.entryNo, false)
val conditionResult = nonRegisteredNodeInstance.condition( this, predecessor)
if (conditionResult == ConditionResult.NEVER) {
nonRegisteredNodeInstance.state = NodeInstanceState.Skipped
if (nonRegisteredNodeInstance is JoinInstance.Builder &&
nonRegisteredNodeInstance.state.isSkipped) { // don't skip join if there are other valid paths
nodesToSkipPredecessorsOf.add(nonRegisteredNodeInstance)
}
nodesToSkipSuccessorsOf.add(nonRegisteredNodeInstance)
} else if (conditionResult == ConditionResult.TRUE) {
if (nonRegisteredNodeInstance is JoinInstance.Builder) {
joinsToEvaluate.add(nonRegisteredNodeInstance)
} else {
startedTasks.add(nonRegisteredNodeInstance)
}
}
storeChild(nonRegisteredNodeInstance)
}
store(engineData)
// Commit the registration of the follow up nodes before starting them.
engineData.commit()
for (node in nodesToSkipSuccessorsOf) {
skipSuccessors(engineData, node, NodeInstanceState.Skipped)
}
for (startedTask in startedTasks) {
when (predecessor.state) {
NodeInstanceState.Complete -> engineData.queueTickle(handle)//startedTask.provideTask(engineData)
NodeInstanceState.SkippedCancel,
NodeInstanceState.SkippedFail,
NodeInstanceState.Skipped -> startedTask.skipTask(engineData, predecessor.state)
NodeInstanceState.Cancelled -> startedTask.skipTask(engineData, NodeInstanceState.SkippedCancel)
NodeInstanceState.Failed -> startedTask.skipTask(engineData, NodeInstanceState.SkippedFail)
else -> throw ProcessException("Node $predecessor is not in a supported state to initiate successors")
}
}
for (join in joinsToEvaluate) {
join.startTask(engineData)
}
}
fun skipSuccessors(
engineData: MutableProcessEngineDataAccess,
predecessor: IProcessNodeInstance,
state: NodeInstanceState
) {
assert(predecessor.handle.isValid) {
"Successors can only be skipped for a node with a handle"
}
// this uses handles as updates can happen intermediately
val joinsToEvaluate = mutableListOf<Handle<SecureObject<ProcessNodeInstance<*>>>>()
for (successorNode in predecessor.node.successors.map { processModel.getNode(it.id)!! }.toList()) {
// Attempt to get the successor instance as it may already be final. In that case the system would attempt to
// create a new instance. We don't want to do that just to skip it.
val successorInstance = successorNode.createOrReuseInstance(
engineData,
this,
predecessor,
predecessor.entryNo,
true
).also { storeChild(it) }
if (!successorInstance.state.isFinal) { // If the successor is already final no skipping is possible.
if (successorInstance is JoinInstance.Builder) {
if (! successorInstance.handle.isValid) store(engineData)
assert(successorInstance.handle.isValid) // the above should make the handle valid
joinsToEvaluate.add(successorInstance.handle)
} else {
successorInstance.skipTask(engineData, state)
}
}
}
for (joinHandle in joinsToEvaluate) {
updateChild(joinHandle) {
startTask(engineData)
}
}
}
/**
* Trigger the instance to reactivate pending tasks.
* @param engineData The database data to use
*
* @param messageService The message service to use for messenging.
*/
fun tickle(engineData: MutableProcessEngineDataAccess, messageService: IMessageService<*>) {
val self = this
val children = allChildNodeInstances().toList()
// make a copy as the list may be changed due to tickling.
val nonFinalChildren = mutableListOf<Handle<SecureObject<ProcessNodeInstance<*>>>>()
val successorCounts = IntArray(children.size)
for (child in children) { // determine the children of interest
for (predHandle in child.predecessors) {
val predIdx = children.indexOfFirst { it.handle == predHandle }
successorCounts[predIdx]++
}
if (! child.state.isFinal) {
nonFinalChildren.add(child.handle)
}
}
for (hNodeInstance in nonFinalChildren) {
updateChild(hNodeInstance) {
tickle(engineData, messageService)
}
val newNodeInstance = engineData.nodeInstance(hNodeInstance).withPermission()
if (newNodeInstance.state.isFinal) {
handleFinishedState(engineData, newNodeInstance)
}
}
// If children don't have the needed amount of successors, we handle the finished state
// this should start those successors.
for ((idx, child) in children.withIndex()) {
if (child.state.isFinal && successorCounts[idx] < child.node.successors.size) {
handleFinishedState(engineData, child)
}
}
updateSplits(engineData)
updateState(engineData)
if (!state.isFinal && active().none()) {
self.finish(engineData)
}
}
// @Synchronized
private fun <N : IProcessNodeInstance> handleFinishedState(
engineData: MutableProcessEngineDataAccess,
nodeInstance: N
) {
// XXX todo, handle failed or cancelled tasks
try {
if (nodeInstance.node is EndNode) {
if (!state.isFinal) {
engineData.logger.log(
LogLevel.WARNING,
"Calling finish on a process instance that should already be finished."
)
finish(engineData).apply {
val h = nodeInstance.handle
assert(getChildNodeInstance(h).let { it.state.isFinal && it.node is ExecutableEndNode })
}
}
} else {
val state = nodeInstance.state
when {
state == NodeInstanceState.Complete ->
startSuccessors(engineData, nodeInstance)
state.isSkipped || state == NodeInstanceState.AutoCancelled ->
skipSuccessors(engineData, nodeInstance, NodeInstanceState.Skipped)
state == NodeInstanceState.Cancelled ->
skipSuccessors(engineData, nodeInstance, NodeInstanceState.SkippedCancel)
}
}
} catch (e: RuntimeException) {
engineData.rollback()
engineData.logger.log(LogLevel.WARNING, "Failure to start follow on task", e)
} catch (e: Exception) {
engineData.rollback()
engineData.logger.log(LogLevel.WARNING, "Failure to start follow on task", e)
}
}
fun finish(engineData: MutableProcessEngineDataAccess) {
// This needs to update first as at this point the node state may not be valid.
// TODO reduce the need to do a double update.
// TODO("Make the state dependent on the kind of child state")
val endNodes = allChildNodeInstances { it.state.isFinal && it.node is EndNode }.toList()
if (endNodes.count() >= processModel.endNodeCount) {
var multiInstanceEndNode = false
var success = 0
var cancelled = 0
var fail = 0
var skipped = 0
for (endNode in endNodes) {
if (endNode.node.isMultiInstance) {
multiInstanceEndNode = true
}
when (endNode.state) {
NodeInstanceState.Complete -> success++
NodeInstanceState.Cancelled -> cancelled++
NodeInstanceState.SkippedCancel -> {
skipped++; cancelled++
}
NodeInstanceState.SkippedFail -> {
skipped++; fail++
}
NodeInstanceState.SkippedInvalidated -> {
skipped++
}
NodeInstanceState.Failed -> fail++
NodeInstanceState.Skipped -> skipped++
else -> throw AssertionError("Unexpected state for end node: $endNode")
}
}
val active = active()
if (!multiInstanceEndNode || active.none()) {
active.forEach {
updateChild(it) {
cancelAndSkip(engineData)
}
}
when {
fail > 0 -> state = State.FAILED
cancelled > 0 -> state = State.CANCELLED
success > 0 -> state = State.FINISHED
skipped > 0 -> state = State.SKIPPED
else -> state = State.CANCELLED
}
}
store(engineData)
if (state == State.FINISHED) {
for (output in processModel.exports) {
val x = output.applyFromProcessInstance(this)
outputs.add(x)
}
// Storing here is essential as the updating of the node goes of the database, not the local
// state.
store(engineData)
}
if (parentActivity.isValid) {
val parentNodeInstance =
engineData.nodeInstance(parentActivity).withPermission() as CompositeInstance
engineData.updateInstance(parentNodeInstance.hProcessInstance) {
updateChild(parentNodeInstance) {
finishTask(engineData)
}
}
store(engineData)
}
engineData.commit()
// TODO don't remove old transactions
engineData.handleFinishedInstance(handle)
}
}
/**
* Get the output of this instance as an xml node or `null` if there is no output
*/
fun getOutputPayload(): ICompactFragment? {
if (outputs.isEmpty()) return null
return CompactFragment { xmlWriter ->
val xmlEncoder = XML
outputs.forEach { output ->
xmlEncoder.encodeToWriter(xmlWriter, output)
}
}
}
}
data class BaseBuilder(
override var handle: Handle<SecureObject<ProcessInstance>> = Handle.invalid(),
override var owner: Principal = SYSTEMPRINCIPAL,
override var processModel: ExecutableModelCommon,
override var instancename: String? = null,
override var uuid: UUID = randomUUID(),
override var state: State = State.NEW,
override var parentActivity: Handle<SecureObject<ProcessNodeInstance<*>>> /*= Handles.getInvalid()*/
) : Builder {
override var generation: Int = 0
private set
private val _pendingChildren = mutableListOf<InstanceFuture<out ProcessNodeInstance<*>, *>>()
override val pendingChildren: List<Future<out ProcessNodeInstance<*>>> get() = _pendingChildren
internal var rememberedChildren: MutableList<ProcessNodeInstance<*>> = mutableListOf()
override val children: List<Handle<SecureObject<ProcessNodeInstance<*>>>>
get() = rememberedChildren.map(ProcessNodeInstance<*>::handle)
override val inputs = mutableListOf<ProcessData>()
override val outputs = mutableListOf<ProcessData>()
override fun allChildNodeInstances(): Sequence<IProcessNodeInstance> {
return _pendingChildren.asSequence().map { it.origBuilder }
}
override fun allChildNodeInstances(childFilter: (IProcessNodeInstance) -> Boolean): Sequence<IProcessNodeInstance> {
return _pendingChildren.asSequence().map { it.origBuilder }.filter { childFilter(it) }
}
override fun build(data: MutableProcessEngineDataAccess): ProcessInstance {
return ProcessInstance(data, this)
}
override fun <T : ProcessNodeInstance<*>> storeChild(child: T): Future<T> {
@Suppress("UNCHECKED_CAST")
return storeChild(child.builder(this)) as Future<T>
}
override fun <T : ProcessNodeInstance<*>> storeChild(child: ProcessNodeInstance.Builder<out ExecutableProcessNode, T>): Future<T> {
return InstanceFuture<T, ExecutableProcessNode>(child).apply {
if (!handle.isValid) throw IllegalArgumentException("Storing a non-existing child")
_pendingChildren.firstOrNull { child.handle.isValid && it.origBuilder.handle == child.handle && it.origBuilder != child }
?.let { _ ->
throw ProcessException("Attempting to store a new child with an already existing handle")
}
if (_pendingChildren.none { it.origBuilder == child }) _pendingChildren.add(this)
}
}
override fun getChildBuilder(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): ProcessNodeInstance.ExtBuilder<*, *> {
val childNode = rememberedChildren.asSequence()
.filter { it.handle == handle }
.first()
val builder = childNode.builder(this)
_pendingChildren.add(InstanceFuture<ProcessNodeInstance<*>, ExecutableProcessNode>(builder))
return builder
}
@Suppress("UNCHECKED_CAST")
override fun <N : ExecutableProcessNode> getChildren(node: N): Sequence<ProcessNodeInstance.Builder<N, *>> {
return _pendingChildren.asSequence().filter { it.origBuilder.node == node }
.map { it.origBuilder as ProcessNodeInstance.Builder<N, *> }
}
override fun <N : ExecutableProcessNode> updateChild(
node: N,
entryNo: Int,
body: ProcessNodeInstance.Builder<out ExecutableProcessNode, *>.() -> Unit
) {
val existingBuilder = _pendingChildren
.firstOrNull { it.origBuilder.node == node && it.origBuilder.entryNo == entryNo }
?: throw ProcessException("Attempting to update a nonexisting child")
@Suppress("UNCHECKED_CAST")
(existingBuilder as ProcessNodeInstance.Builder<N, *>).apply(body)
}
override fun store(data: MutableProcessEngineDataAccess) {
val newInstance = build(data)
if (handle.isValid) data.instances[handle] = newInstance else handle = data.instances.put(newInstance)
generation = newInstance.generation + 1
rememberedChildren.replaceBy(newInstance.childNodes.map { it.withPermission() })
_pendingChildren.clear()
}
}
class ExtBuilder(base: ProcessInstance) : Builder {
@set:ProcessInstanceStorage
internal var base = base
private set(value) {
field = value
generation = value.generation+1
_pendingChildren.clear()
}
override var generation = base.generation + 1
private set(value) {
assert(value == base.generation+1)
field = value
}
private val _pendingChildren =
mutableListOf<InstanceFuture<out ProcessNodeInstance<*>, out ExecutableProcessNode>>()
override val pendingChildren: List<Future<out ProcessNodeInstance<*>>> get() = _pendingChildren
override var handle: Handle<SecureObject<ProcessInstance>> by overlay { base.handle }
override var parentActivity: Handle<SecureObject<ProcessNodeInstance<*>>> by overlay { base.parentActivity }
override var owner: Principal by overlay { base.owner }
override var processModel: ExecutableModelCommon by overlay { base.processModel }
override var instancename: String? by overlay { base.name }
override var uuid: UUID by overlay({ newVal ->
generation = 0; handle = Handle.invalid(); newVal
}) { base.uuid }
override var state: State by overlay(base = { base.state }, update = { newValue ->
if (base.state.isFinal) {
throw IllegalStateException("Cannot change from final instance state ${base.state} to ${newValue}")
}
newValue
})
override val children: List<Handle<SecureObject<ProcessNodeInstance<*>>>>
get() = base.childNodes.map {
it.withPermission()
.handle
}
override val inputs: MutableList<ProcessData> by lazy { base.inputs.toMutableList() }
override val outputs: MutableList<ProcessData> by lazy { base.outputs.toMutableList() }
override fun allChildNodeInstances(): Sequence<IProcessNodeInstance> {
val pendingChildren = _pendingChildren.asSequence().map { it.origBuilder }
val pendingHandles = pendingChildren.map { it.handle }.toSet()
return pendingChildren + base.childNodes.asSequence()
.map { it.withPermission() }
.filter { it.handle !in pendingHandles }
}
override fun allChildNodeInstances(childFilter: (IProcessNodeInstance) -> Boolean): Sequence<IProcessNodeInstance> {
val pendingHandles = mutableSetOf<Handle<SecureObject<ProcessNodeInstance<*>>>>()
val pendingChildren =
_pendingChildren.map { pendingHandles.add(it.origBuilder.handle); it.origBuilder }
.filter { childFilter(it) }
return pendingChildren.asSequence() + base.childNodes.asSequence()
.map { it.withPermission() }
.filter { it.handle !in pendingHandles && childFilter(it) }
}
override fun build(data: MutableProcessEngineDataAccess): ProcessInstance {
return ProcessInstance(data, this)
}
@Suppress("UNCHECKED_CAST")
override fun <T : ProcessNodeInstance<*>> storeChild(child: T) = storeChild(child.builder(this)) as Future<T>
override fun <T : ProcessNodeInstance<*>> storeChild(child: ProcessNodeInstance.Builder<out ExecutableProcessNode, T>): Future<T> {
return InstanceFuture<T, ExecutableProcessNode>(child).apply {
val existingIdx = _pendingChildren.indexOfFirst {
it.origBuilder == child ||
(child.handle.isValid && it.origBuilder.handle == child.handle) ||
(it.origBuilder.node == child.node && it.origBuilder.entryNo == child.entryNo)
}
if (existingIdx >= 0) {
_pendingChildren[existingIdx] = this
} else if (_pendingChildren.any { child.handle.isValid && it.origBuilder.handle == child.handle && it.origBuilder != child }) {
throw ProcessException("Attempting to store a new child with an already existing handle")
} else {
_pendingChildren.add(this)
}
}
}
override fun getChildBuilder(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): ProcessNodeInstance.ExtBuilder<*,*> {
if (! handle.isValid) throw IllegalArgumentException("Cannot look up with invalid handles")
_pendingChildren.asSequence()
.map { it.origBuilder as? ProcessNodeInstance.ExtBuilder }
.firstOrNull { it?.handle == handle }
?.let { return it }
return base.childNodes.asSequence()
.map { it.withPermission() }
.first { it.handle == handle }
.let {
it.builder(this).also { _pendingChildren.add(InstanceFuture(it)) }
}
}
@Suppress("UNCHECKED_CAST")
override fun <N : ExecutableProcessNode> getChildren(node: N): Sequence<ProcessNodeInstance.Builder<N, *>> {
return _pendingChildren.asSequence()
.filter { it.origBuilder.node == node }
.map { it.origBuilder as ProcessNodeInstance.Builder<N, *> } +
base.childNodes.asSequence()
.map { it.withPermission() }
.filter { child ->
child.node == node &&
_pendingChildren.none { pending ->
child.node == pending.origBuilder.node && child.entryNo == pending.origBuilder.entryNo
}
}
.map {
(it.builder(this) as ProcessNodeInstance.Builder<N, *>).also {
// The type stuff here is a big hack to avoid having to "know" what the instance type actually is
_pendingChildren.add(InstanceFuture<ProcessNodeInstance<*>, ExecutableProcessNode>(it))
}
}
}
override fun <N : ExecutableProcessNode> updateChild(
node: N,
entryNo: Int,
body: ProcessNodeInstance.Builder<out ExecutableProcessNode, out ProcessNodeInstance<*>>.() -> Unit
) {
@Suppress("UNCHECKED_CAST")
val existingBuilder = _pendingChildren.asSequence()
.map { it.origBuilder as ProcessNodeInstance.Builder<N, *> }
.firstOrNull { it.node == node && it.entryNo == entryNo }
if (existingBuilder != null) {
existingBuilder.apply(body); return
}
base.childNodes.asSequence()
.map { it.withPermission() }
.firstOrNull { it.node == node && it.entryNo == entryNo }
?.also {
it.builder(this).apply(body)
if (it.builder(this).changed) {
_pendingChildren.add(InstanceFuture<ProcessNodeInstance<*>, N>(it.builder(this)))
}
} ?: throw ProcessException("Attempting to update a nonexisting child")
}
@ProcessInstanceStorage
override fun store(data: MutableProcessEngineDataAccess) {
// TODO: monitor for changes
val newInstance = build(data)
data.instances[handle] = newInstance
base = newInstance
_pendingChildren.clear()
}
@ProcessInstanceStorage
@PublishedApi
internal fun __storeNewValueIfNeeded(
writableEngineData: MutableProcessEngineDataAccess,
newInstanceBuilderXX: ExtBuilder
): ProcessInstance {
val newInstance = build(writableEngineData)
val base = this.base
fun dataValid(): Boolean {
val stored = writableEngineData.instance(handle).withPermission()
assert(uuid == base.uuid) { "Uuid mismatch this: $uuid, base: ${base.uuid}" }
assert(stored.uuid == base.uuid) { "Uuid mismatch this: $uuid, stored: ${stored.uuid}" }
assert(newInstance.uuid == base.uuid) { "Uuid mismatch this: $uuid, new: ${newInstance.uuid}" }
assert(base.generation == stored.generation) {
"Generation mismatch this: ${base.generation} stored: ${stored.generation} - $base"
}
assert(base.generation + 1 == newInstance.generation) { "Generation mismatch this+1: ${base.generation + 1} new: ${newInstance.generation}" }
return newInstance.handle.isValid && handle.isValid
}
if (handle.isValid && handle.isValid) {
assert(dataValid()) { "Instance generations lost in the waves" }
writableEngineData.instances[handle] = newInstance
this.base = newInstance
return newInstance
}
this.base = newInstance
return newInstance
}
fun initialize() {
if (state != State.NEW || base.active.isNotEmpty() || _pendingChildren.any { !it.origBuilder.state.isFinal }) {
throw IllegalStateException("The instance already appears to be initialised")
}
processModel.startNodes.forEach { node ->
storeChild(
node.createOrReuseInstance(
this,
1
).build() as DefaultProcessNodeInstance
) // Start with sequence 1
}
state = State.INITIALIZED
}
@ProcessInstanceStorage
fun start(engineData: MutableProcessEngineDataAccess, payload: CompactFragment? = null) {
if (state == State.NEW) initialize()
state = State.STARTED
inputs.addAll(processModel.toInputs(payload))
store(engineData) // make sure we have a valid handle
for (task in active()) {
updateChild(task) {
provideTask(engineData)
}
}
}
}
enum class State {
NEW,
INITIALIZED,
STARTED,
FINISHED {
override val isFinal: Boolean get() = true
},
SKIPPED {
override val isFinal: Boolean get() = true
},
FAILED {
override val isFinal: Boolean get() = true
},
CANCELLED {
override val isFinal: Boolean get() = true
};
open val isFinal: Boolean get() = false
}
class ProcessInstanceRef(processInstance: ProcessInstance) : XmlSerializable {
val handle: Handle<SecureObject<ProcessInstance>> = processInstance.handle
val handleValue: Long get() = handle.handleValue
val processModel: Handle<ExecutableProcessModel> = processInstance.processModel.rootModel.handle
val name: String = processInstance.name.let {
if (it.isNullOrBlank()) {
buildString {
append(processInstance.processModel.rootModel.name)
if (processInstance.processModel !is ExecutableProcessModel) append(" child") else append(' ')
append("instance ").append(handleValue)
}
} else it
}
val parentActivity = processInstance.parentActivity
val uuid: UUID = processInstance.uuid
val state = processInstance.state
override fun serialize(out: XmlWriter) {
out.smartStartTag(Constants.PROCESS_ENGINE_NS, "processInstance", Constants.PROCESS_ENGINE_NS_PREFIX) {
writeHandleAttr("handle", handle)
writeHandleAttr("processModel", processModel)
writeHandleAttr("parentActivity", parentActivity)
writeAttribute("name", name)
writeAttribute("uuid", uuid)
writeAttribute("state", state)
}
}
}
val generation: Int
override val processModel: ExecutableModelCommon
val childNodes: Collection<SecureObject<ProcessNodeInstance<*>>>
val parentActivity: Handle<SecureObject<ProcessNodeInstance<*>>>
val children: Sequence<Handle<SecureObject<ProcessNodeInstance<*>>>>
get() = childNodes.asSequence().map { it.withPermission().handle }
val activeNodes
get() = childNodes.asSequence()
.map { it.withPermission() }
.filter { !it.state.isFinal }
val active: Collection<Handle<SecureObject<ProcessNodeInstance<*>>>>
get() = activeNodes
.map { it.handle }
.toList()
val finishedNodes
get() = childNodes.asSequence()
.map { it.withPermission() }
.filter { it.state.isFinal && it.node !is EndNode }
val finished: Collection<Handle<SecureObject<ProcessNodeInstance<*>>>>
get() = finishedNodes
.map { it.handle }
.toList()
val completedNodeInstances: Sequence<SecureObject<ProcessNodeInstance<*>>>
get() = childNodes.asSequence()
.map { it.withPermission() }
.filter { it.state.isFinal && it.node is EndNode }
val completedEndnodes: Collection<Handle<SecureObject<ProcessNodeInstance<*>>>>
get() = completedNodeInstances
.map { it.withPermission().handle }
.toList()
private val pendingJoinNodes
get() = childNodes.asSequence()
.map { it.withPermission() }
.filterIsInstance<JoinInstance>()
.filter { !it.state.isFinal }
private val pendingJoins: Map<ExecutableJoin, JoinInstance>
get() =
pendingJoinNodes.associateBy { it.node }
// private var _handle: Handle<SecureObject<ProcessInstance>>
override var handle: Handle<SecureObject<ProcessInstance>>
private set
/**
* Get the payload that was passed to start the instance.
* @return The process initial payload.
*/
override val inputs: List<ProcessData>
val outputs: List<ProcessData>
val name: String?
override val owner: Principal
val state: State
val uuid: UUID
val ref: ProcessInstanceRef
get() = ProcessInstanceRef(this)
private constructor(data: MutableProcessEngineDataAccess, builder: Builder) {
generation = builder.generation
name = builder.instancename
owner = builder.owner
uuid = builder.uuid
processModel = builder.processModel
state = builder.state
handle = builder.handle
parentActivity = builder.parentActivity
val pending = builder.pendingChildren.asSequence().map { it as InstanceFuture<*, *> }
val createdNodes = mutableListOf<ProcessNodeInstance<*>>()
val updatedNodes = mutableMapOf<Handle<SecureObject<ProcessNodeInstance<*>>>, ProcessNodeInstance<*>>()
for (future in pending) {
if (!future.origBuilder.handle.isValid) {
// Set the handle on the builder so that lookups in the future will be more correct.
createdNodes += data.putNodeInstance(future).also {
future.origBuilder.handle = it.handle
future.origBuilder.invalidateBuilder(data) // Actually invalidate the original builder/keep it valid
}
} else if((future.origBuilder as? ProcessNodeInstance.ExtBuilder)?.changed != false){
// We don't store unchanged extBuilders
assert(future.origBuilder.hProcessInstance == handle)
updatedNodes[future.origBuilder.handle] = data.storeNodeInstance(future)
}
}
val nodes = createdNodes + builder.children.asSequence().map { childHandle ->
updatedNodes.remove(childHandle) ?: data.nodeInstance(childHandle).withPermission()
}.toList()
assert(updatedNodes.isEmpty()) { "All updated nodes must be used, still missing: [${updatedNodes.values.joinToString()}]" }
childNodes = nodes
inputs = builder.inputs.toList()
outputs = builder.outputs.toList()
}
constructor(
data: MutableProcessEngineDataAccess,
processModel: ExecutableModelCommon,
parentActivity: Handle<SecureObject<ProcessNodeInstance<*>>>,
body: Builder.() -> Unit
) : this(data, BaseBuilder(processModel = processModel, parentActivity = parentActivity).apply(body))
override fun withPermission() = this
private fun checkOwnership(node: ProcessNodeInstance<*>) {
if (node.hProcessInstance != handle) throw ProcessException("The node is not owned by this instance")
}
@ProcessInstanceStorage
inline fun update(
writableEngineData: MutableProcessEngineDataAccess,
body: ExtBuilder.() -> Unit
): ProcessInstance {
val newValue = builder().apply(body)
return newValue.__storeNewValueIfNeeded(writableEngineData, newValue).apply {
assert(writableEngineData.instances[newValue.handle]?.withPermission() == this) {
"Process instances should match after storage"
}
}
}
fun builder() = ExtBuilder(this)
@OptIn(ProcessInstanceStorage::class)
@Synchronized
fun finish(engineData: MutableProcessEngineDataAccess): ProcessInstance {
// This needs to update first as at this point the node state may not be valid.
// TODO reduce the need to do a double update.
update(engineData) {}.let { newInstance ->
if (newInstance.completedNodeInstances.count() >= processModel.endNodeCount) {
// TODO mark and store results
return newInstance.update(engineData) {
state = State.FINISHED
}.apply {
if (parentActivity.isValid) {
val parentNode = engineData.nodeInstance(parentActivity).withPermission()
val parentInstance = engineData.instance(parentNode.hProcessInstance).withPermission()
parentInstance.update(engineData) {
updateChild(parentNode) {
finishTask(engineData, getOutputPayload())
}
}
}
engineData.commit()
// TODO don't remove old transactions
engineData.handleFinishedInstance(handle)
}
} else {
return newInstance
}
}
}
override fun getChildNodeInstance(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): ProcessNodeInstance<*> {
return childNodes
.asSequence()
.map { it.withPermission() }
.first { it.handle == handle }
}
override fun allChildNodeInstances(): Sequence<IProcessNodeInstance> {
return childNodes.asSequence().map { it.withPermission() }
}
@Synchronized
fun getNodeInstances(identified: Identified): Sequence<ProcessNodeInstance<*>> {
return childNodes.asSequence().map { it.withPermission() }.filter { it.node.id == identified.id }
}
@Synchronized
fun getNodeInstance(identified: Identified, entryNo: Int): ProcessNodeInstance<*>? {
return childNodes.asSequence().map { it.withPermission() }
.firstOrNull { it.node.id == identified.id && it.entryNo == entryNo }
}
@Synchronized
override fun setHandleValue(handleValue: Long) {
if (handle.handleValue != handleValue) {
if (handleValue == -1L) {
throw IllegalArgumentException("Setting the handle to invalid is not allowed")
}
if (handle.isValid) throw IllegalStateException("Handles are not allowed to change")
handle = if (handleValue < 0) Handle.invalid() else Handle(handleValue)
}
}
fun getChild(nodeId: String, entryNo: Int): SecureObject<ProcessNodeInstance<*>>? {
return childNodes.firstOrNull { it.withPermission().run { node.id == nodeId && this.entryNo == entryNo } }
}
/**
* Get the output of this instance as an xml node or `null` if there is no output
*/
fun getOutputPayload(): CompactFragment? {
if (outputs.isEmpty()) return null
val str = buildString {
for (output in outputs) {
append(generateXmlString(true) { writer ->
writer.smartStartTag(output.name!!.toQname()) {
output.content.serialize(this)
}
})
}
}
return CompactFragment(str)
}
@Synchronized
fun getActivePredecessorsFor(
engineData: ProcessEngineDataAccess,
join: JoinInstance
): Collection<ProcessNodeInstance<*>> {
return active.asSequence()
.map { engineData.nodeInstance(it).withPermission() }
.filter { it.node.isPredecessorOf(join.node) }
.toList()
}
@Synchronized
fun getDirectSuccessors(
engineData: ProcessEngineDataAccess,
predecessor: ProcessNodeInstance<*>
): Collection<Handle<SecureObject<ProcessNodeInstance<*>>>> {
checkOwnership(predecessor)
// TODO rewrite, this can be better with the children in the instance
val result = ArrayList<Handle<SecureObject<ProcessNodeInstance<*>>>>(predecessor.node.successors.size)
fun addDirectSuccessor(
candidate: ProcessNodeInstance<*>,
predecessor: Handle<SecureObject<ProcessNodeInstance<*>>>
) {
// First look for this node, before diving into it's children
if (candidate.predecessors.any { it.handleValue == predecessor.handleValue }) {
result.add(candidate.handle)
return
}
candidate.predecessors
.map { engineData.nodeInstance(it).withPermission() }
.forEach { successorInstance -> addDirectSuccessor(successorInstance, predecessor) }
}
val data = engineData
active.asSequence()
.map { data.nodeInstance(it).withPermission() }
.forEach { addDirectSuccessor(it, predecessor.handle) }
return result
}
@Synchronized
fun serialize(transaction: ProcessTransaction, writer: XmlWriter) {
//
writer.smartStartTag(Constants.PROCESS_ENGINE_NS, "processInstance", Constants.PROCESS_ENGINE_NS_PREFIX) {
writeHandleAttr("handle", handle)
writeAttribute("name", name)
when (processModel) {
is ExecutableProcessModel -> writeHandleAttr("processModel", processModel.handle)
else -> writeHandleAttr("parentActivity", parentActivity)
}
writeAttribute("owner", owner.getName())
writeAttribute("state", state.name)
smartStartTag(Constants.PROCESS_ENGINE_NS, "inputs") {
val xml = XML
inputs.forEach { xml.encodeToWriter(this, it) }
}
writer.smartStartTag(Constants.PROCESS_ENGINE_NS, "outputs") {
val xml = XML
outputs.forEach { xml.encodeToWriter(this, it) }
}
writeListIfNotEmpty(active, Constants.PROCESS_ENGINE_NS, "active") {
writeActiveNodeRef(transaction, it)
}
writeListIfNotEmpty(finished, Constants.PROCESS_ENGINE_NS, "finished") {
writeActiveNodeRef(transaction, it)
}
writeListIfNotEmpty(completedEndnodes, Constants.PROCESS_ENGINE_NS, "endresults") {
writeResultNodeRef(transaction, it)
}
}
}
private fun XmlWriter.writeActiveNodeRef(
transaction: ProcessTransaction,
handleNodeInstance: Handle<SecureObject<ProcessNodeInstance<*>>>
) {
val nodeInstance = transaction.readableEngineData.nodeInstance(handleNodeInstance).withPermission()
startTag(Constants.PROCESS_ENGINE_NS, "nodeinstance") {
writeNodeRefCommon(nodeInstance)
}
}
private fun XmlWriter.writeResultNodeRef(
transaction: ProcessTransaction,
handleNodeInstance: Handle<SecureObject<ProcessNodeInstance<*>>>
) {
val nodeInstance = transaction.readableEngineData.nodeInstance(handleNodeInstance).withPermission()
startTag(Constants.PROCESS_ENGINE_NS, "nodeinstance") {
writeNodeRefCommon(nodeInstance)
startTag(Constants.PROCESS_ENGINE_NS, "results") {
val xml = XML
nodeInstance.results.forEach { xml.encodeToWriter(this, it) }
}
}
}
override fun toString(): String {
return "ProcessInstance(handle=${handle.handleValue}, name=$name, state=$state, generation=$generation, childNodes=$childNodes)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.getClass() != getClass()) return false
other as ProcessInstance
if (generation != other.generation) return false
if (processModel != other.processModel) return false
if (childNodes != other.childNodes) return false
if (handle != other.handle) return false
if (inputs != other.inputs) return false
if (outputs != other.outputs) return false
if (name != other.name) return false
if (owner != other.owner) return false
if (state != other.state) return false
if (uuid != other.uuid) return false
return true
}
override fun hashCode(): Int {
var result = generation
result = 31 * result + processModel.hashCode()
result = 31 * result + childNodes.hashCode()
result = 31 * result + handle.hashCode()
result = 31 * result + inputs.hashCode()
result = 31 * result + outputs.hashCode()
result = 31 * result + (name?.hashCode() ?: 0)
result = 31 * result + owner.hashCode()
result = 31 * result + state.hashCode()
result = 31 * result + uuid.hashCode()
return result
}
companion object {
const val HANDLEELEMENTLOCALNAME = "instanceHandle"
@JvmStatic
val HANDLEELEMENTNAME = QName(ProcessConsts.Engine.NAMESPACE, HANDLEELEMENTLOCALNAME, ProcessConsts.Engine.NSPREFIX)
private val serialVersionUID = 1145452195455018306L
@Suppress("NOTHING_TO_INLINE")
private fun MutableProcessEngineDataAccess.putNodeInstance(value: InstanceFuture<*, *>): ProcessNodeInstance<*> {
fun <T : ProcessNodeInstance<T>> impl(value: InstanceFuture<*, *>): ProcessNodeInstance<*> {
val handle = (nodeInstances as MutableHandleMap).put(value.origBuilder.build())
value.origBuilder.handle =
handle // Update the builder handle as when merely storing the original builder will remain used and needs to be updated.
@Suppress("UNCHECKED_CAST") // Semantically this should always be valid
val newValue = nodeInstance(handle).withPermission() as T
@Suppress("UNCHECKED_CAST")
(value as InstanceFuture<T, *>).set(newValue)
return newValue
}
return impl<DefaultProcessNodeInstance>(value)
}
@JvmStatic
private fun MutableProcessEngineDataAccess.storeNodeInstance(value: InstanceFuture<*, *>): ProcessNodeInstance<*> {
fun <T : ProcessNodeInstance<T>> impl(value: InstanceFuture<*, *>): ProcessNodeInstance<*> {
val handle = value.origBuilder.handle
(nodeInstances as MutableHandleMap)[handle] = value.origBuilder.build()
@Suppress("UNCHECKED_CAST") // Semantically this should always be valid
return (nodeInstance(handle).withPermission() as T).also {
(value as InstanceFuture<T, *>).run {
set(it)
}
}
}
return impl<DefaultProcessNodeInstance>(value) // hack to work around generics issues
}
private fun XmlWriter.writeNodeRefCommon(nodeInstance: ProcessNodeInstance<*>) {
writeAttribute("nodeid", nodeInstance.node.id)
writeAttribute("handle", nodeInstance.getHandleValue())
attribute(null, "state", null, nodeInstance.state.toString())
if (nodeInstance.state === NodeInstanceState.Failed) {
val failureCause = nodeInstance.failureCause
val value =
if (failureCause == null) "<unknown>" else "${failureCause.getClass()}: " + failureCause.message
attribute(null, "failureCause", null, value)
}
}
}
}
inline fun ProcessInstance.Builder.updateChild(
childHandle: Handle<SecureObject<ProcessNodeInstance<*>>>,
body: ProcessNodeInstance.ExtBuilder<out ExecutableProcessNode, *>.() -> Unit
): ProcessNodeInstance.ExtBuilder<*, *> {
return getChildBuilder(childHandle).apply(body)
}
inline fun ProcessInstance.ExtBuilder.updateChild(
childHandle: Handle<SecureObject<ProcessNodeInstance<*>>>,
body: ProcessNodeInstance.ExtBuilder<out ExecutableProcessNode, *>.() -> Unit
): ProcessNodeInstance.ExtBuilder<*, *> {
return getChildBuilder(childHandle).apply(body)
}
inline fun ProcessInstance.Builder.updateChild(
node: IProcessNodeInstance,
body: ProcessNodeInstance.Builder<out ExecutableProcessNode, *>.() -> Unit
): ProcessNodeInstance.Builder<*, *> {
if (node is ProcessNodeInstance.Builder<*, *>) {
return node.apply(body)
} else {
return node.builder(this).apply {
body()
storeChild(this)
}
}
}
| lgpl-3.0 | 0c5c04a82ac6e262a8464129add27fff | 41.990529 | 169 | 0.594669 | 5.493596 | false | false | false | false |
tfcbandgeek/SmartReminders-android | smartreminderssave/src/main/java/jgappsandgames/smartreminderssave/priority/RepeatData.kt | 1 | 5887 | package jgappsandgames.smartreminderssave.priority
import jgappsandgames.me.poolutilitykotlin.PoolObjectCreator
import jgappsandgames.me.poolutilitykotlin.PoolObjectInterface
import jgappsandgames.smartreminderssave.repeats.RepeatableObject
import jgappsandgames.smartreminderssave.tasks.Task
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList
class RepeatData: PoolObjectInterface {
companion object {
private const val FILENAME = "a"
private const val META = "b"
private const val ID = "c"
private const val STATUS = "d"
private const val DOW = "e"
private const val WOM = "f"
private const val DOM = "g"
const val NONE: Byte = 0
const val DAILY: Byte = 1
const val WEEKLY: Byte = 1 shl 1
const val MONTHLY: Byte = 1 shl 2
const val WEEK_MONTHLY: Byte = 1 shl 3
const val YEARLY: Byte = 1 shl 4
const val MONDAY: Byte = 1
const val TUESDAY: Byte = 1 shl 1
const val WEDNESDAY: Byte = 1 shl 2
const val THURSDAY: Byte = 1 shl 3
const val FRIDAY: Byte = 1 shl 4
const val SATURDAY: Byte = 1 shl 5
const val SUNDAY: Byte = 1 shl 6
const val Z_MONDAY: Long = 1
const val Z_TUESDAY: Long = 1 shl 1
const val Z_WEDNESDAY: Long = 1 shl 2
const val Z_THURSDAY: Long = 1 shl 3
const val Z_FRIDAY: Long = 1 shl 4
const val Z_SATURDAY: Long = 1 shl 5
const val Z_SUNDAY: Long = 1 shl 6
const val F_MONDAY: Long = 1 shl 10
const val F_TUESDAY: Long = 1 shl 11
const val F_WEDNESDAY: Long = 1 shl 12
const val F_THURSDAY: Long = 1 shl 13
const val F_FRIDAY: Long = 1 shl 14
const val F_SATURDAY: Long = 1 shl 15
const val F_SUNDAY: Long = 1 shl 16
const val S_MONDAY: Long = 1 shl 2
const val S_TUESDAY: Long = 1 shl 21
const val S_WEDNESDAY: Long = 1 shl 22
const val S_THURSDAY: Long = 1 shl 23
const val S_FRIDAY: Long = 1 shl 24
const val S_SATURDAY: Long = 1 shl 25
const val S_SUNDAY: Long = 1 shl 26
const val T_MONDAY: Long = 1 shl 30
const val T_TUESDAY: Long = 1 shl 31
const val T_WEDNESDAY: Long = 1 shl 32
const val T_THURSDAY: Long = 1 shl 33
const val T_FRIDAY: Long = 1 shl 34
const val T_SATURDAY: Long = 1 shl 35
const val T_SUNDAY: Long = 1 shl 36
const val O_MONDAY: Long = 1 shl 40
const val O_TUESDAY: Long = 1 shl 41
const val O_WEDNESDAY: Long = 1 shl 42
const val O_THURSDAY: Long = 1 shl 43
const val O_FRIDAY: Long = 1 shl 44
const val O_SATURDAY: Long = 1 shl 45
const val O_SUNDAY: Long = 1 shl 46
const val I_MONDAY: Long = 1 shl 50
const val I_TUESDAY: Long = 1 shl 51
const val I_WEDNESDAY: Long = 1 shl 52
const val I_THURSDAY: Long = 1 shl 53
const val I_FRIDAY: Long = 1 shl 54
const val I_SATURDAY: Long = 1 shl 55
const val I_SUNDAY: Long = 1 shl 56
}
// Data ----------------------------------------------------------------------------------------
private var filename: String? = null
private var meta: JSONObject? = null
private var id: Int = 0
private var status: Byte = 0
private var dow: Byte = 0
private var wom: Long = 0
private var dom = ArrayList<Int>(4)
private var till: Calendar? = null
private var past: ArrayList<String> = ArrayList()
private var template: String? = null
private var future: ArrayList<String> = ArrayList()
// Management Methods --------------------------------------------------------------------------
fun create(): RepeatData {
return this
}
fun load(filename: String): RepeatData {
return this
}
fun load(data: JSONObject): RepeatData {
return this
}
fun save(): RepeatData {
return this
}
fun delete(): Boolean {
return false
}
override fun deconstruct() {}
// Getters -------------------------------------------------------------------------------------
fun getFilename(): String = filename ?: ""
fun getMeta(): JSONObject {
if (meta == null) {
meta = JSONObject()
}
return meta!!
}
override fun getID(): Int = id
fun getStatus(): Byte = status
fun getDOW(): Byte = dow
fun getWOM(): Long = wom
fun getDOM(): ArrayList<Int> = dom
fun getTill(): Calendar? = till
fun getPastTasks(): ArrayList<String> = past
fun getTemplateTask(): String {
if (template == null) {
throw NullPointerException()
} else {
return template!!
}
}
fun getFutureTasks(): ArrayList<String> = future
// Setters -------------------------------------------------------------------------------------
fun setMeta(data: JSONObject): RepeatData {
meta = data
return this
}
fun setStatus(nStatus: Byte): RepeatData {
status = nStatus
return this
}
fun setDOW(nDOW: Byte): RepeatData {
dow = nDOW
return this
}
fun setWOM(nWOM: Long): RepeatData {
wom = nWOM
return this
}
fun setDOM(nDOM: ArrayList<Int>): RepeatData {
dom = nDOM
return this
}
fun update(to: Calendar? = null): RepeatData {
val t: Calendar
if (to == null) {
t = Calendar.getInstance()
t.add(Calendar.WEEK_OF_YEAR, 1)
} else {
t = to
}
// TODO: Implement Check Methods
return this
}
}
class RepeatableCreator: PoolObjectCreator<RepeatData> {
override fun generatePoolObject(): RepeatData {
return RepeatData()
}
} | apache-2.0 | 7a6c34e6bad99490057debad7c970f80 | 28.44 | 100 | 0.554952 | 4.312821 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-core/src/main/kotlin/com/octaldata/core/StreamopsModule.kt | 1 | 8702 | package com.octaldata.core
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.octaldata.domain.ActionHandlerName
import com.octaldata.domain.DeploymentId
import com.octaldata.domain.DeploymentIdentifier
import com.octaldata.domain.DeploymentName
import com.octaldata.domain.topics.ConsumerGroupId
import com.octaldata.domain.topics.ConsumerGroupStatus
import com.octaldata.domain.DisplayNodeId
import com.octaldata.domain.topics.MemberId
import com.octaldata.domain.topics.NamespaceName
import com.octaldata.domain.BrokerId
import com.octaldata.domain.auth.UserId
import com.octaldata.domain.topics.PartitionId
import com.octaldata.domain.topics.TopicName
import com.octaldata.domain.topics.TenantName
import com.octaldata.domain.integrations.IntegrationId
import com.octaldata.domain.integrations.IntegrationName
import com.octaldata.domain.metrics.MetricCollectorId
import com.octaldata.domain.metrics.MetricId
import com.octaldata.domain.metrics.MetricKey
import com.octaldata.domain.monitoring.MonitorId
import com.octaldata.domain.monitoring.MonitorName
import com.octaldata.domain.pipelines.PipelineId
import com.octaldata.domain.pipelines.PipelineName
import com.octaldata.domain.pipelines.PipelineRunnerId
import com.octaldata.domain.pipelines.PipelineStatus
import com.octaldata.domain.query.ViewId
import com.octaldata.domain.query.ViewName
import com.octaldata.domain.registry.RegistryId
import com.octaldata.domain.schemas.SchemaId
import com.octaldata.domain.schemas.SchemaSubject
import com.octaldata.domain.schemas.SchemaType
import com.octaldata.domain.schemas.SchemaVersion
import com.octaldata.domain.security.DataPattern
import com.octaldata.domain.security.DetectionId
import com.octaldata.domain.security.FieldPattern
import com.octaldata.domain.security.ModelClass
import com.octaldata.domain.security.Redacted
import com.octaldata.domain.security.RuleId
import com.octaldata.domain.security.RuleName
import com.octaldata.domain.security.RuleSetId
import com.octaldata.domain.security.RuleSetName
import com.octaldata.domain.security.ScanId
import com.octaldata.domain.security.TablePattern
import com.octaldata.domain.structure.DataRecordUrn
import com.octaldata.domain.topics.TopicViewId
import com.octaldata.domain.topics.TopicViewName
import kotlin.reflect.KFunction1
object StreamopsModule : SimpleModule() {
private inline fun <reified T> addStringSerializer(crossinline f: (T) -> String) {
addSerializer(object : StdSerializer<T>(T::class.java) {
override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeString(f(value))
}
})
}
private inline fun <reified T> addLongSerializer(crossinline f: (T) -> Long) {
addSerializer(object : StdSerializer<T>(T::class.java) {
override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeNumber(f(value))
}
})
}
private inline fun <reified T> addIntSerializer(crossinline f: (T) -> Int) {
addSerializer(object : StdSerializer<T>(T::class.java) {
override fun serialize(value: T, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeNumber(f(value))
}
})
}
private inline fun <reified T> deserializer(f: KFunction1<String, T>) {
addDeserializer(T::class.java, object : JsonDeserializer<T>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T? =
p.valueAsString?.let { f.invoke(it) }
})
}
private inline fun <reified T> deserializeInt(f: KFunction1<Int, T>) {
addDeserializer(T::class.java, object : JsonDeserializer<T>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T? = f(p.intValue)
})
}
private inline fun <reified T> deserializeLong(f: KFunction1<Long, T>) {
addDeserializer(T::class.java, object : JsonDeserializer<T>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T? =
if (p.valueAsString == null) null else f.invoke(p.longValue)
})
}
private inline fun <reified T> deserializeDouble(f: KFunction1<Double, T>) {
addDeserializer(T::class.java, object : JsonDeserializer<T>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T? =
if (p.valueAsString == null) null else f.invoke(p.doubleValue)
})
}
private inline fun <reified T> deserializeBoolean(f: KFunction1<Boolean, T>) {
addDeserializer(T::class.java, object : JsonDeserializer<T>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T? =
if (p.valueAsString == null) null else f.invoke(p.booleanValue)
})
}
init {
addStringSerializer(DeploymentIdentifier::value)
addStringSerializer(DeploymentName::value)
addStringSerializer(DeploymentId::value)
addStringSerializer(BrokerId::value)
addStringSerializer(MonitorId::value)
addStringSerializer(MonitorName::value)
addStringSerializer(MetricId::value)
addStringSerializer(MetricCollectorId::value)
addStringSerializer(MetricKey::value)
addStringSerializer(IntegrationId::value)
addStringSerializer(IntegrationName::value)
addStringSerializer(DisplayNodeId::value)
addStringSerializer(TopicName::value)
addStringSerializer(ActionHandlerName::value)
addStringSerializer(ConsumerGroupId::value)
addStringSerializer(ConsumerGroupStatus::value)
addStringSerializer(MemberId::value)
addStringSerializer(RuleId::value)
addStringSerializer(RuleName::value)
addStringSerializer(FieldPattern::value)
addStringSerializer(DataPattern::value)
addStringSerializer(TablePattern::value)
addStringSerializer(RuleSetName::value)
addStringSerializer(RuleSetId::value)
addStringSerializer(DetectionId::value)
addStringSerializer(Redacted::value)
addStringSerializer(ModelClass::value)
addStringSerializer(ScanId::value)
addStringSerializer(PartitionId::value)
addStringSerializer(RegistryId::value)
addStringSerializer(SchemaId::value)
addStringSerializer(SchemaSubject::value)
addStringSerializer(SchemaType::value)
addStringSerializer(ViewId::value)
addStringSerializer(ViewName::value)
addStringSerializer(DataRecordUrn::value)
addStringSerializer(NamespaceName::value)
addStringSerializer(TenantName::value)
addStringSerializer(SchemaVersion::value)
addStringSerializer(TopicViewId::value)
addStringSerializer(TopicViewName::value)
addStringSerializer(PipelineId::value)
addStringSerializer(PipelineName::value)
addStringSerializer(UserId::value)
addStringSerializer(PipelineRunnerId::value)
deserializer(::DeploymentIdentifier)
deserializer(::DeploymentId)
deserializer(::DeploymentName)
deserializer(::MonitorName)
deserializer(::ViewId)
deserializer(::ViewName)
deserializer(::MonitorId)
deserializer(::MetricId)
deserializer(::MetricCollectorId)
deserializer(::MetricKey)
deserializer(::IntegrationId)
deserializer(::IntegrationName)
deserializer(::BrokerId)
deserializer(::DetectionId)
deserializer(::RuleName)
deserializer(::TopicName)
deserializer(::RuleId)
deserializer(::Redacted)
deserializer(::FieldPattern)
deserializer(::DataPattern)
deserializer(::TablePattern)
deserializer(::RuleSetName)
deserializer(::RuleSetId)
deserializer(::ModelClass)
deserializer(::ScanId)
deserializer(::PartitionId)
deserializer(::ConsumerGroupId)
deserializer(::MemberId)
deserializer(::RegistryId)
deserializer(::SchemaId)
deserializer(::RegistryId)
deserializer(::SchemaId)
deserializer(::SchemaSubject)
deserializer(::SchemaType)
deserializer(::DataRecordUrn)
deserializer(::NamespaceName)
deserializer(::TenantName)
deserializer(::SchemaVersion)
deserializer(::TopicViewId)
deserializer(::TopicViewName)
deserializer(::PipelineId)
deserializer(::PipelineName)
deserializer(::UserId)
deserializer(::PipelineRunnerId)
}
}
| apache-2.0 | 8292423b14867d1575abd606f634d660 | 40.241706 | 98 | 0.747414 | 4.599366 | false | false | false | false |
strykeforce/thirdcoast | src/main/kotlin/org/strykeforce/console/SSD1306.kt | 1 | 7273 | @file:Suppress("unused")
package org.strykeforce.console
import edu.wpi.first.wpilibj.I2C
import edu.wpi.first.wpilibj.Timer
import mu.KotlinLogging
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import kotlin.experimental.and
import kotlin.experimental.or
private val logger = KotlinLogging.logger {}
private const val DATA_TRANSFER_SIZE = 64
private const val DISPLAY_ADDRESS = 0x3C // 64-pixel tall
private const val DISPLAY_WIDTH = 128
private const val DISPLAY_HEIGHT = 64
private const val MAX_INDEX = DISPLAY_HEIGHT / 8 * DISPLAY_WIDTH
private const val SSD1306_SET_CONTRAST = 0x81
private const val SSD1306_DISPLAY_ALL_ON_RESUME = 0xA4
private const val SSD1306_DISPLAY_ALL_ON = 0xA5
private const val SSD1306_NORMAL_DISPLAY = 0xA6
private const val SSD1306_INVERT_DISPLAY = 0xA7
private const val SSD1306_DISPLAY_OFF = 0xAE
private const val SSD1306_DISPLAY_ON = 0xAF
private const val SSD1306_SET_DISPLAY_OFFSET = 0xD3
private const val SSD1306_SET_COMP_INS = 0xDA
private const val SSD1306_SET_VCOM_DETECT = 0xDB
private const val SSD1306_SET_DISPLAY_CLOCK_DIV = 0xD5
private const val SSD1306_SET_PRE_CHARGE = 0xD9
private const val SSD1306_SET_MULTIPLEX = 0xA8
private const val SSD1306_SET_LOW_COLUMN = 0x00
private const val SSD1306_SET_HIGH_COLUMN = 0x10
private const val SSD1306_SET_START_LINE = 0x40
private const val SSD1306_MEMORY_MODE = 0x20
private const val SSD1306_COLUMN_ADDR = 0x21
private const val SSD1306_PAGE_ADDR = 0x22
private const val SSD1306_COM_SCAN_INC = 0xC0
private const val SSD1306_COM_SCAN_DEC = 0xC8
private const val SSD1306_SEG_REMAP = 0xA0
private const val SSD1306_CHARGE_PUMP = 0x8D
private const val SSD1306_EXTERNAL_VCC = 0x1
private const val SSD1306_SWITCH_CAP_VCC = 0x2
@ExperimentalStdlibApi
class SSD1306 {
private val display = I2C(I2C.Port.kOnboard, DISPLAY_ADDRESS)
private val writeBuffer = ByteArray(DISPLAY_WIDTH * DISPLAY_HEIGHT / 8)
private val readBuffer = ByteArray(DISPLAY_WIDTH * DISPLAY_HEIGHT / 8)
private val rotation = Rotation.DEG_0
private val periodicTimer = Timer()
private var future: CompletableFuture<Void> = CompletableFuture.completedFuture(null)
init {
init()
periodicTimer.start()
}
fun periodic() {
if (periodicTimer.advanceIfElapsed(0.25) and future.isDone) {
future = CompletableFuture.runAsync(this::update)
// logger.debug { "periodicTimer advanced and future is done" }
}
}
val width = when (rotation) {
Rotation.DEG_90, Rotation.DEG_270 -> DISPLAY_HEIGHT
Rotation.DEG_0, Rotation.DEG_180 -> DISPLAY_WIDTH
}
val height = when (rotation) {
Rotation.DEG_90, Rotation.DEG_270 -> DISPLAY_WIDTH
Rotation.DEG_0, Rotation.DEG_180 -> DISPLAY_HEIGHT
}
private fun writeCommand(command: Int) {
if (display.write(0x00, command)) logger.error { "I2C transfer aborted for command: $command" }
}
fun setPixel(x: Int, y: Int, on: Boolean) {
when (rotation) {
Rotation.DEG_0 -> updateImageBuffer(x, y, on)
Rotation.DEG_90 -> updateImageBuffer(y, width - x - 1, on)
Rotation.DEG_180 -> updateImageBuffer(width - x - 1, height - y - 1, on)
Rotation.DEG_270 -> updateImageBuffer(height - y - 1, x, on)
}
}
fun drawChar(c: Char, font: Font, x: Int, y: Int, on: Boolean) {
font.drawChar(this, c, x, y, on)
}
fun drawString(string: String, font: Font, x: Int, y: Int, on: Boolean) {
var posX = x
var posY = y
for (c in string.toCharArray()) {
if (c == '\n') {
posY += font.outerHeight
posX = x
} else {
if (posX >= 0 && posX + font.width < width && posY >= 0 && posY + font.height < height) {
drawChar(c, font, posX, posY, on)
}
posX += font.outerWidth
}
}
}
fun drawStringCentered(string: String, font: Font, y: Int, on: Boolean) {
val strSizeX = string.length * font.outerWidth
val x: Int = (width - strSizeX) / 2
drawString(string, font, x, y, on)
}
fun clearRect(x: Int, y: Int, width: Int, height: Int, on: Boolean) {
for (posX in x until x + width) {
for (posY in y until y + height) {
setPixel(posX, posY, on)
}
}
}
fun clear() {
synchronized(this) {
Arrays.fill(writeBuffer, 0x00.toByte())
}
}
fun update() {
synchronized(this) {
System.arraycopy(writeBuffer, 0, readBuffer, 0, writeBuffer.size)
}
val setupCommands = byteArrayOfInt(0, SSD1306_COLUMN_ADDR, 0, DISPLAY_WIDTH - 1, SSD1306_PAGE_ADDR, 0, 7)
if (display.writeBulk(setupCommands)) logger.warn { "I2C command transfer interrupted" }
val chunk = ByteArray(DATA_TRANSFER_SIZE + 1)
chunk[0] = 0x40
for (i in 0 until DISPLAY_WIDTH * DISPLAY_HEIGHT / 8 / DATA_TRANSFER_SIZE) {
val start = i * DATA_TRANSFER_SIZE
readBuffer.copyInto(chunk, 1, start, start + DATA_TRANSFER_SIZE)
if (display.writeBulk(chunk)) logger.warn { "I2C data transfer interrupted" }
}
}
private fun init() {
writeCommand(SSD1306_DISPLAY_OFF)
writeCommand(SSD1306_SET_DISPLAY_CLOCK_DIV)
writeCommand(0x80) // default freq (8) and divide (0)
writeCommand(SSD1306_SET_MULTIPLEX)
writeCommand((DISPLAY_HEIGHT - 1))
writeCommand(SSD1306_SET_DISPLAY_OFFSET)
writeCommand(0) // default 0
writeCommand((SSD1306_SET_START_LINE or 0x0)) // default 0
writeCommand(SSD1306_CHARGE_PUMP)
writeCommand(0x14) // enable display charge pump, internal Vcc
writeCommand(SSD1306_MEMORY_MODE)
writeCommand(0) // horizontal addressing
writeCommand((SSD1306_SEG_REMAP or 0x1)) // column address 127 mapped to SEG0
writeCommand(SSD1306_COM_SCAN_DEC) // scan from COM[N-1] to COM0
writeCommand(SSD1306_SET_COMP_INS)
writeCommand(0x12) // default: alt. COM pin conf, disable LR remap, 128x64
writeCommand(SSD1306_SET_CONTRAST)
writeCommand(0xCF) // increased from default, internal Vcc
writeCommand(SSD1306_SET_PRE_CHARGE)
writeCommand(0xF1) // P1 period 15 DCLKs, P2 period 1 DCLK, internal Vcc
writeCommand(SSD1306_SET_VCOM_DETECT)
writeCommand(0x40)
writeCommand(SSD1306_DISPLAY_ALL_ON_RESUME)
writeCommand(SSD1306_NORMAL_DISPLAY)
writeCommand(SSD1306_DISPLAY_ON)
clear()
update()
}
private fun updateImageBuffer(x: Int, y: Int, on: Boolean) {
val pos = x + y / 8 * DISPLAY_WIDTH
if (pos in 0 until MAX_INDEX) {
synchronized(this) {
writeBuffer[pos] = if (on) {
writeBuffer[pos] or (1 shl (y and 0x07)).toByte()
} else {
writeBuffer[pos] and (1 shl (y and 0x07)).inv().toByte()
}
}
}
}
enum class Rotation {
DEG_0, DEG_90, DEG_180, DEG_270
}
}
| mit | 69d3afdaae915446ab80973943505dc8 | 33.966346 | 113 | 0.635226 | 3.5 | false | false | false | false |
IntershopCommunicationsAG/scmversion-gradle-plugin | src/main/kotlin/com/intershop/gradle/scm/task/ToVersion.kt | 1 | 5391 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.
*/
package com.intershop.gradle.scm.task
import com.intershop.gradle.scm.extension.ScmExtension
import com.intershop.gradle.scm.utils.BranchType
import com.intershop.gradle.scm.utils.ScmException
import com.intershop.release.version.ParserException
import com.intershop.release.version.VersionParser
import org.gradle.api.GradleException
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
/**
* This is the implementation of Gradle
* task to switch the branch to a special version.
*/
open class ToVersion: AbstractDryRunTask() {
init {
outputs.upToDateWhen { false }
description = "Moves the existing working copy to a specified version _tag_"
}
private var versionProp: String = ""
private var branchTypeProp: String = ""
private var featureExtProp: String = ""
/**
* This property is used if a special version should be specified.
*
* @property version
*/
@set:Option(option = "version", description = "Target version for the toVersion task.")
@get:Optional
@get:Input
var version: String
get() = versionProp
set(value) {
versionProp = value
}
/**
* This property is used for a special branch type.
*
* @property branchType
*/
@set:Option(option = "branchType", description = "Branch type for the toVersion task.")
@get:Optional
@get:Input
var branchType: String
get() = branchTypeProp
set(value) {
branchTypeProp = value
}
/**
* This property is used for a special branch type.
*
* @property feature
*/
@set:Option(option = "feature", description = "Feature extension for version tasks.")
@get:Optional
@get:Input
var feature: String
get() = featureExtProp
set(value) {
featureExtProp = value
}
private fun getProperty(propName: String): String {
return if( project.hasProperty(propName) ) { project.property(propName).toString() } else { "" }
}
private fun getBranchType(branchTypeStr: String, featureBranchStr: String): BranchType {
return when {
branchTypeStr.isNotEmpty() -> BranchType.valueOf(branchTypeStr)
featureBranchStr.isNotEmpty() -> BranchType.FEATUREBRANCH
else -> BranchType.BRANCH
}
}
/**
* Implementation of the task action.
*/
@Throws(GradleException::class)
@TaskAction
fun toVersionAction() {
val versionConfig = project.extensions.getByType(ScmExtension::class.java).version
project.logger.debug("Version is {} branch type is {}, Feature is {}",
versionProp, branchTypeProp, featureExtProp)
if(versionProp.isNotEmpty()) {
try {
val bType = getBranchType(branchTypeProp, featureExtProp)
var v = VersionParser.parseVersion(versionProp, versionConfig.versionType)
if (featureExtProp.isNotEmpty()) {
v = v.setBranchMetadata(featureExtProp)
}
project.logger.debug("Target version is {}", v.toString())
project.logger.debug("Branch type is {}", bType.toString())
val versionService = versionConfig.versionService
if(! dryRun) {
val revision = versionService.moveTo(v.toString(), bType)
project.logger.info("Working copy was switched to {} with revision id {}", v.toString(), revision)
} else {"""
|----------------------------------------------
| DryRun: Working copy will be switched
| to $v with for $bType
|----------------------------------------------""".trimMargin()
}
} catch(iex: IllegalArgumentException) {
project.logger.error("The branch type {} is not a valid type.", branchTypeProp)
throw GradleException("The branch type is not valid")
} catch( ex: ParserException) {
project.logger.error("The version {} is not a valid version.", versionProp)
throw GradleException("The target version is not valid")
} catch( ex: ScmException) {
project.logger.error( "It was not possible to switch the current working copy to the specifed version.",
ex)
throw GradleException( "It was not possible to switch the current working copy " +
"to the specifed version [${ex.message}].")
}
}
}
}
| apache-2.0 | 8a85614ed18d986eccc329f371d99222 | 35.673469 | 120 | 0.609349 | 4.720665 | false | false | false | false |
tmarsteel/bytecode-fiddle | common/src/main/kotlin/com/github/tmarsteel/bytecode/binary/Instruction.kt | 1 | 1933 | package com.github.tmarsteel.bytecode.binary
open class Instruction constructor(val opcode: Opcode, private val args: LongArray) {
init {
if (args.size != opcode.nArgs) {
throw IllegalArgumentException("Opcode ${opcode.name} is defined for ${opcode.nArgs} arguments, {$args.size} given.")
}
}
/**
* The number of long words (QWORD) this instruction occupies.
*/
val qWordSize: Int = opcode.qWordSize
operator fun get(argIndex: Int): Long {
return args[argIndex]
}
override fun toString(): String {
return opcode.name + " " + args.joinToString(" ")
}
enum class Opcode(val byteValue: Byte, val nArgs: Int) {
LOAD_CONSTANT(0, 2),
MOVE(1, 2),
ADD(2, 0),
STORE(3, 2),
RECALL(4, 2),
MUL(5, 0),
JUMP(6, 1),
CONDITIONAL_JUMP(7, 1),
EQUALS(8, 0),
GREATER_THAN(9, 0),
GREATER_THAN_OR_EQUAL(10, 0),
OR(11, 0),
AND(12, 0),
XOR(13, 0),
INCREMENT(14, 1),
TERMINATE(15, 0),
VARJUMP(16, 1),
CONDITIONAL_VARJUMP(17, 1),
DECREMENT(18, 1),
LESS_THAN(19, 0),
LESS_THAN_OR_EQUAL(20, 0),
DEBUG_CORE_STATE(21, 0),
DEBUG_MEMORY_RANGE(22, 0);
/** The number of long words (QWORD) an instruction with this opcode needs */
val qWordSize: Int = nArgs + 1
companion object {
/**
* Returns the opcode with the given value.
* @throws UnknownOpcodeException If the given byteValue does not map to an opcode.
*/
fun byByteValue(byteValue: Byte): Opcode {
return Opcode.values().find { it.byteValue == byteValue } ?: throw UnknownOpcodeException(byteValue)
}
}
}
}
class UnknownOpcodeException(val opcode: Byte) : RuntimeException("Unknown opcode $opcode") | lgpl-3.0 | 0bd1d13ef21fd7c06ab45806d5d73467 | 29.21875 | 129 | 0.561304 | 3.866 | false | false | false | false |
CajetanP/coding-exercises | Others/Kotlin/kotlin-koans/src/iii_conventions/MyDate.kt | 1 | 1448 | package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int = when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> dayOfMonth - other.dayOfMonth
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
class DateIterator(val dateRange: DateRange) : Iterator<MyDate> {
var current: MyDate = dateRange.start
override fun next(): MyDate {
val result = current
current = current.nextDay()
return result
}
override fun hasNext(): Boolean = current <= dateRange.endInclusive
}
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(override val start: MyDate, override val endInclusive: MyDate):
ClosedRange<MyDate>, Iterable<MyDate> {
override fun contains(value: MyDate): Boolean = value >= start && value <= endInclusive
override fun iterator(): Iterator<MyDate> = DateIterator(this)
}
class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)
operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number)
operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval, 1)
operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) = addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
| mit | 61dd2653ee1b57b35af3289be46ea016 | 33.47619 | 130 | 0.717541 | 4.567823 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/util/lock/StampedLock.kt | 1 | 2473 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.util.lock
import org.lanternpowered.api.util.uncheckedCast
import java.util.concurrent.locks.StampedLock
/**
* Performs a [read] function using the target [StampedLock].
*/
inline fun <R> StampedLock.read(read: () -> R): R {
var stamp = this.tryOptimisticRead()
var result: R? = null
if (stamp != 0L)
result = read()
if (stamp == 0L || !this.validate(stamp)) {
stamp = this.readLock()
try {
result = read()
} finally {
this.unlockRead(stamp)
}
}
return result.uncheckedCast()
}
/**
* Performs a [write] function using the target [StampedLock].
*/
inline fun <R> StampedLock.write(write: () -> R): R {
val stamp = this.writeLock()
try {
return write()
} finally {
this.unlockWrite(stamp)
}
}
/**
* Performs a [read] function using the target [StampedLock]. If the result was
* `null`, the [compute] function will be used to determine and write the value.
*/
inline fun <R : Any> StampedLock.computeIfNull(read: () -> R?, compute: () -> R): R =
this.computeIf(read, { it == null}, compute).uncheckedCast()
/**
* Performs a [read] function using the target [StampedLock]. If the result was
* `null`, the [compute] function will be used to determine and write the value.
*/
inline fun <R> StampedLock.computeIf(read: () -> R, shouldCompute: (R) -> Boolean, compute: () -> R): R {
var stamp = this.tryOptimisticRead()
if (stamp != 0L) {
val result = read()
if (this.validate(stamp)) {
if (!shouldCompute(result))
return result
stamp = this.writeLock()
try {
return compute()
} finally {
this.unlockWrite(stamp)
}
}
}
stamp = this.readLock()
try {
val result = read()
if (!shouldCompute(result))
return result
stamp = this.tryConvertToWriteLock(stamp)
if (stamp == 0L)
stamp = this.writeLock()
return compute()
} finally {
this.unlock(stamp)
}
}
| mit | cc5b0fe2c830b638768d8e4feb95ae72 | 28.094118 | 105 | 0.589972 | 3.804615 | false | false | false | false |
markspit93/Github-Feed-Sample | app/src/main/kotlin/com/github/feed/sample/util/DateUtils.kt | 1 | 689 | package com.github.feed.sample.util
import android.content.Context
import com.github.feed.sample.R
import java.text.SimpleDateFormat
import java.util.*
object DateUtils {
fun formatDate(ctx: Context, date: String): String {
var formattedDate: String
try {
var format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
val newDate = format.parse(date)
format = SimpleDateFormat("MMM dd, hh:mma", Locale.getDefault())
formattedDate = format.format(newDate)
} catch (e: Exception) {
formattedDate = ctx.getString(R.string.unavailable)
}
return formattedDate
}
} | apache-2.0 | 42550e0c1df2a956f9d6803ec0249af6 | 26.6 | 90 | 0.645864 | 4.253086 | false | false | false | false |
noseblowhorn/krog | src/main/kotlin/eu/fizzystuff/krog/model/DungeonLevel.kt | 1 | 2103 | package eu.fizzystuff.krog.model
import com.google.common.base.Preconditions
import com.googlecode.lanterna.TextCharacter
class DungeonLevel(width: Int, height: Int) {
public val width: Int
public val height: Int
private val tiles: Array<Array<Tile>>
val seen: Array<Array<Boolean>>
val visible: Array<Array<Boolean>>
val actors: MutableList<Actor>
val npcs: MutableList<Npc>
val transitionPoints: MutableList<DungeonTransitionPoint> = arrayListOf()
init {
this.width = width
this.height = height
tiles = Array(width, {i -> Array(height, {j -> Tile.Tiles.floorTile}) })
seen = Array(width, {i -> Array(height, {j -> false}) })
visible = Array(width, {i -> Array(height, {j -> false}) })
actors = mutableListOf()
npcs = mutableListOf()
}
public fun getTileAt(x: Int, y: Int): Tile {
Preconditions.checkState(x >= 0)
Preconditions.checkState(y >= 0)
Preconditions.checkState(x < width)
Preconditions.checkState(y < height)
return tiles[x][y]
}
public fun setTileAt(x: Int, y: Int, tile: Tile) {
Preconditions.checkState(x >= 0)
Preconditions.checkState(y >= 0)
Preconditions.checkState(x < width)
Preconditions.checkState(y < height)
tiles[x][y] = tile
}
public fun getPrintableEntityAt(x: Int, y: Int): WorldPrintableEntity {
return tiles[x][y].printableEntity
}
public fun setVisible(x: Int, y: Int, isVisible: Boolean) {
visible[x][y] = isVisible
if (isVisible) {
seen[x][y] = isVisible
}
}
public fun addActor(actor: Actor) {
actors.add(actor)
}
public fun getActorAt(x: Int, y: Int): Actor? {
return actors.filter { actor -> actor.x == x && actor.y == y }.firstOrNull()
}
public fun fillWithTile(tile: Tile) {
for (x in 0..width - 1) {
for (y in 0..height - 1) {
setTileAt(x, y, tile)
}
}
}
companion object DungeonLevels {
}
} | apache-2.0 | 5db4c23c85f85ff8cf21aab14b715b50 | 26.324675 | 84 | 0.592011 | 3.830601 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/services/BookmarkService.kt | 1 | 7825 | package com.pr0gramm.app.services
import android.content.SharedPreferences
import androidx.core.content.edit
import com.pr0gramm.app.Logger
import com.pr0gramm.app.MoshiInstance
import com.pr0gramm.app.feed.FeedFilter
import com.pr0gramm.app.feed.FeedType
import com.pr0gramm.app.model.bookmark.Bookmark
import com.pr0gramm.app.orm.asFeedFilter
import com.pr0gramm.app.orm.isImmutable
import com.pr0gramm.app.orm.link
import com.pr0gramm.app.orm.migrate
import com.pr0gramm.app.ui.base.AsyncScope
import com.pr0gramm.app.util.catchAll
import com.pr0gramm.app.util.doInBackground
import com.pr0gramm.app.util.getStringOrNull
import com.pr0gramm.app.util.tryEnumValueOf
import com.squareup.moshi.adapter
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.*
/**
*/
class BookmarkService(
private val preferences: SharedPreferences,
private val userService: UserService,
private val bookmarkSyncService: BookmarkSyncService) {
private val logger = Logger("BookmarkService")
private val bookmarks = MutableStateFlow<List<Bookmark>>(listOf())
private val updateQueue = Channel<suspend () -> Unit>(Channel.UNLIMITED)
val all: List<Bookmark>
get() = bookmarks.value
init {
// restore previous json
restoreFromSerialized(preferences.getStringOrNull("Bookmarks.json") ?: "[]")
AsyncScope.launch {
// serialize updates back to the preferences
bookmarks.drop(1)
.distinctUntilChanged()
.debounce(100)
.collect { persist(it) }
}
AsyncScope.launch {
userService.loginStates
.debounce(100)
.collect { updateQueue.send { update() } }
}
doInBackground {
for (action in updateQueue) {
catchAll { action() }
}
}
}
/**
* Fetches bookmarks from the remote api and publishes them locally.
*/
suspend fun update() {
mergeWith {
bookmarkSyncService.fetch()
}
}
private fun restoreFromSerialized(json: String) {
val bookmarks = MoshiInstance.adapter<List<Bookmark>>().fromJson(json) ?: listOf()
logger.debug { "Restored ${bookmarks.size} bookmarks" }
this.bookmarks.value = bookmarks.filter { it.title.length <= 255 }
}
private fun persist(bookmarks: List<Bookmark>) {
logger.debug { "Persisting ${bookmarks.size} bookmarks to storage" }
val json = MoshiInstance.adapter<List<Bookmark>>().toJson(bookmarks)
preferences.edit { putString("Bookmarks.json", json) }
}
/**
* Returns "true", if the item is bookmarkable.
*/
fun isBookmarkable(filter: FeedFilter): Boolean {
if (!canEdit || filter.isBasic || filter.collection != null)
return false
return byFilter(filter) == null
}
/**
* Observes change to the bookmarks
*/
fun observe(): Flow<List<Bookmark>> {
val comparator = compareBy<Bookmark> { !it.trending }.thenBy { it.title.lowercase(Locale.getDefault()) }
return bookmarks.map { it.sortedWith(comparator) }.distinctUntilChanged()
}
/**
* Deletes the given bookmark if it exists. Bookmarks are compared by their title.
*/
fun delete(bookmark: Bookmark) {
synchronized(bookmarks) {
// remove all matching bookmarks
val newValues = bookmarks.value.filterNot { it.hasTitle(bookmark.title) }
bookmarks.value = newValues
}
if (bookmarkSyncService.isAuthorized && bookmark.syncable) {
mergeWithAsync {
// also delete bookmarks on the server
bookmarkSyncService.delete(bookmark.title)
}
}
}
private fun mergeWithAsync(block: suspend () -> List<Bookmark>) {
updateQueue.trySendBlocking { mergeWith(block) }
}
private suspend fun mergeWith(block: suspend () -> List<Bookmark>) {
// do optimistic locking
val currentState = this.bookmarks.value
val updated = block()
synchronized(this.bookmarks) {
if (this.bookmarks.value === currentState) {
mergeCurrentState(updated)
}
}
}
private fun mergeCurrentState(update: List<Bookmark>) {
synchronized(bookmarks) {
// get the local ones that dont have a 'link' yet
val local = bookmarks.value.filter { it._link == null || it.notSyncable }
// and merge them together, with the local ones winning.
val merged = (local + update).distinctBy { it.title.lowercase(Locale.getDefault()) }
bookmarks.value = merged
}
}
/**
* Returns a bookmark that has a filter equal to the queried one.
*/
fun byFilter(filter: FeedFilter): Bookmark? {
return bookmarks.value.firstOrNull { bookmark -> filter == bookmark.asFeedFilter() }
}
fun byTitle(title: String): Bookmark? {
return bookmarks.value.firstOrNull { it.hasTitle(title) }
}
/**
* Save a bookmark to the database.
*/
fun save(bookmark: Bookmark) {
rename(bookmark, bookmark.title)
}
/**
* Rename a bookmark
*/
fun rename(existing: Bookmark, newTitle: String) {
val new = existing.copy(title = newTitle).let { if (it.notSyncable) it else it.migrate() }
synchronized(bookmarks) {
val values = bookmarks.value.toMutableList()
// replace the first bookmark that has the old title,
// or add the new bookmark to the end
val idx = values.indexOfFirst { it.hasTitle(existing.title) }
if (idx >= 0) {
values[idx] = new
} else {
values.add(0, new)
}
// dispatch changes
bookmarks.value = values
}
if (bookmarkSyncService.isAuthorized) {
if (new.notSyncable) {
if (existing.title != newTitle) {
mergeWithAsync {
bookmarkSyncService.delete(existing.title)
}
}
} else {
mergeWithAsync {
if (existing.title != newTitle) {
bookmarkSyncService.delete(existing.title)
}
bookmarkSyncService.add(new)
}
}
}
}
suspend fun restore() {
// get all default bookmarks
val defaults = bookmarkSyncService.fetch(anonymous = true).filter { !it.isImmutable }
// and save missing bookmarks remotely
defaults.filter { byTitle(it.title) == null }.forEach { bookmark ->
bookmarkSyncService.add(bookmark)
}
// then fetch the new remote list of bookmarks
update()
}
val canEdit: Boolean get() = bookmarkSyncService.canChange
private fun Bookmark.hasTitle(title: String): Boolean {
return this.title.equals(title, ignoreCase = false)
}
private val Bookmark.syncable: Boolean
get() {
// can not be synced if feed type is e.g. RANDOM, CONTROVERSIAL, etc
val feedType = tryEnumValueOf<FeedType>(filterFeedType)
if (feedType != null && feedType !in listOf(FeedType.NEW, FeedType.PROMOTED))
return false
// can only by synced if strings are short.
val link = this.link
return title.length < 255 && link.length < 255
}
private val Bookmark.notSyncable: Boolean get() = !syncable
} | mit | 356f9b917f14341507d9c9515b1a87d7 | 31.07377 | 112 | 0.605367 | 4.657738 | false | false | false | false |
gumil/basamto | data/src/main/kotlin/io/github/gumil/data/model/Link.kt | 1 | 2381 | /*
* The MIT License (MIT)
*
* Copyright 2017 Miguel Panelo
*
* 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.
*/
package io.github.gumil.data.model
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.TypeConverters
import com.squareup.moshi.Json
import io.github.gumil.data.persistence.Converters
@Entity
@TypeConverters(Converters::class)
data class Link(
@PrimaryKey
override val id: String,
override val name: String,
override val subreddit: String,
override val author: String,
override val created: Long,
@Json(name = "created_utc")
override val createdUtc: Long,
val title: String,
val url: String,
val domain: String,
val permalink: String,
val selftext: String?,
@Json(name = "selftext_html")
val selfTextHtml: String?,
@Json(name = "is_self")
val isSelf: Boolean,
@Json(name = "link_flair_text")
val linkFlairText: String?,
@Json(name = "num_comments")
val commentsCount: Int,
override val gilded: Int,
override val score: Int,
override val ups: Int,
val stickied: Boolean,
val thumbnail: String,
val preview: Preview? = null
) : Submission | mit | f5f6aa2a0769533ed7eb2100eac3557e | 33.028571 | 81 | 0.695086 | 4.368807 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-dessert-clicker | app/src/main/java/com/example/dessertclicker/MainActivity.kt | 1 | 10262 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* 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.
*/
package com.example.dessertclicker
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Share
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat.startActivity
import com.example.dessertclicker.data.Datasource.dessertList
import com.example.dessertclicker.ui.theme.DessertClickerTheme
import com.example.dessertclicker.model.Dessert
// tag for logging
private const val TAG = "MainActivity"
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate Called")
setContent {
DessertClickerTheme {
DessertClickerApp(desserts = dessertList)
}
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart Called")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume Called")
}
override fun onRestart() {
super.onRestart()
Log.d(TAG, "onRestart Called")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause Called")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop Called")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy Called")
}
}
/**
* Determine which dessert to show.
*/
fun determineDessertToShow(
desserts: List<Dessert>,
dessertsSold: Int
): Dessert {
var dessertToShow = desserts.first()
for (dessert in desserts) {
if (dessertsSold >= dessert.startProductionAmount) {
dessertToShow = dessert
} else {
// The list of desserts is sorted by startProductionAmount. As you sell more desserts,
// you'll start producing more expensive desserts as determined by startProductionAmount
// We know to break as soon as we see a dessert who's "startProductionAmount" is greater
// than the amount sold.
break
}
}
return dessertToShow
}
/**
* Share desserts sold information using ACTION_SEND intent
*/
private fun shareSoldDessertsInformation(intentContext: Context, dessertsSold: Int, revenue: Int) {
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(
Intent.EXTRA_TEXT,
intentContext.getString(R.string.share_text, dessertsSold, revenue)
)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
try {
startActivity(intentContext, shareIntent, null)
} catch (e: ActivityNotFoundException) {
Toast.makeText(
intentContext,
intentContext.getString(R.string.sharing_not_available),
Toast.LENGTH_LONG
).show()
}
}
@Composable
private fun DessertClickerApp(
desserts: List<Dessert>
) {
var revenue by rememberSaveable { mutableStateOf(0) }
var dessertsSold by rememberSaveable { mutableStateOf(0) }
val currentDessertIndex by rememberSaveable { mutableStateOf(0) }
var currentDessertPrice by rememberSaveable {
mutableStateOf(desserts[currentDessertIndex].price)
}
var currentDessertImageId by rememberSaveable {
mutableStateOf(desserts[currentDessertIndex].imageId)
}
Scaffold(
topBar = {
val intentContext = LocalContext.current
AppBar(
onShareButtonClicked = {
shareSoldDessertsInformation(
intentContext = intentContext,
dessertsSold = dessertsSold,
revenue = revenue
)
}
)
}
) { contentPadding ->
DessertClickerScreen(
revenue = revenue,
dessertsSold = dessertsSold,
dessertImageId = currentDessertImageId,
onDessertClicked = {
// Update the revenue
revenue += currentDessertPrice
dessertsSold++
// Show the next dessert
val dessertToShow = determineDessertToShow(desserts, dessertsSold)
currentDessertImageId = dessertToShow.imageId
currentDessertPrice = dessertToShow.price
},
modifier = Modifier.padding(contentPadding)
)
}
}
@Composable
private fun AppBar(
onShareButtonClicked: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.background(MaterialTheme.colors.primary),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(R.string.app_name),
modifier = Modifier.padding(start = 16.dp),
color = MaterialTheme.colors.onPrimary,
style = MaterialTheme.typography.h6,
)
IconButton(
onClick = onShareButtonClicked,
modifier = Modifier.padding(end = 16.dp),
) {
Icon(
imageVector = Icons.Filled.Share,
contentDescription = stringResource(R.string.share),
tint = MaterialTheme.colors.onPrimary
)
}
}
}
@Composable
fun DessertClickerScreen(
revenue: Int,
dessertsSold: Int,
@DrawableRes dessertImageId: Int,
onDessertClicked: () -> Unit,
modifier: Modifier = Modifier
) {
Box(modifier = modifier) {
Image(
painter = painterResource(R.drawable.bakery_back),
contentDescription = null,
contentScale = ContentScale.Crop
)
Column {
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
) {
Image(
painter = painterResource(dessertImageId),
contentDescription = null,
modifier = Modifier
.width(150.dp)
.height(150.dp)
.align(Alignment.Center)
.clickable { onDessertClicked() },
contentScale = ContentScale.Crop,
)
}
TransactionInfo(revenue = revenue, dessertsSold = dessertsSold)
}
}
}
@Composable
private fun TransactionInfo(
revenue: Int,
dessertsSold: Int,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.background(Color.White),
) {
DessertsSoldInfo(dessertsSold)
RevenueInfo(revenue)
}
}
@Composable
private fun RevenueInfo(revenue: Int, modifier: Modifier = Modifier) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = stringResource(R.string.total_revenue),
style = MaterialTheme.typography.h4
)
Text(
text = "$${revenue}",
textAlign = TextAlign.Right,
style = MaterialTheme.typography.h4
)
}
}
@Composable
private fun DessertsSoldInfo(dessertsSold: Int, modifier: Modifier = Modifier) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = stringResource(R.string.dessert_sold),
style = MaterialTheme.typography.h6
)
Text(
text = dessertsSold.toString(),
style = MaterialTheme.typography.h6
)
}
}
@Preview
@Composable
fun MyDessertClickerAppPreview() {
DessertClickerTheme {
DessertClickerApp(listOf(Dessert(R.drawable.cupcake, 5, 0)))
}
}
| apache-2.0 | 504d9cc85b0873d9f4712c71e771a37b | 29.360947 | 100 | 0.643637 | 4.687985 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-android | superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/XmlParser.kt | 1 | 4269 | package tv.superawesome.sdk.publisher.common.components
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.InputSource
import org.xml.sax.SAXException
import java.io.ByteArrayInputStream
import java.io.IOException
import java.util.ArrayList
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException
interface XmlParserType {
/**
* Function that parses a XML document
*
* @param xml xml string
* @return a Document object
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
fun parse(xml: String): Document
/**
* Method that returns a list of XML elements after performing a thorough search of all
* the node parameter's siblings and children, by a given "name".
*
* @param node the parent node
* @param name the name to search for
* @return a List of XML elements
*/
fun findAll(node: Node, name: String): List<Element>
/**
* Finds only the first instance of a XML element with given name by searching in all of
* the node parameter's siblings and children.
*
* @param node the parent node
* @param name the name to search for
* @return the first element found
*/
fun findFirst(node: Node, name: String): Element?
/**
* Method that checks if in all children and siblings of a XML node, there exists
* at least one element with given name
*
* @param node parent XML node
* @param name name to search for
* @return true if found any, false otherwise
*/
fun exists(node: Node, name: String): Boolean
}
/**
* Class that abstracts away the complexities of XML parsing into a series of utility methods
*/
class XmlParser : XmlParserType {
@Throws(ParserConfigurationException::class, IOException::class, SAXException::class)
override fun parse(xml: String): Document {
val dbf = DocumentBuilderFactory.newInstance()
val db = dbf.newDocumentBuilder()
val doc = db.parse(InputSource(ByteArrayInputStream(xml.toByteArray(charset("utf-8")))))
doc.documentElement.normalize()
return doc
}
override fun findAll(node: Node, name: String): List<Element> {
val list: MutableList<Element> = ArrayList()
searchSiblingsAndChildrenOf(node, name, list)
return list
}
override fun findFirst(node: Node, name: String): Element? {
val list = findAll(node, name)
return list.firstOrNull()
}
override fun exists(node: Node, name: String): Boolean {
val list = findAll(node, name)
return list.isNotEmpty()
}
/**
* Method that makes a search in the current node's siblings and children by a
* given "name" string parameter.
* It will return the result into the list of XML elements given as paramter.
*
* @param node the XML parent node
* @param name the XML name ot search for
* @param list a list of returned Elements
*/
private fun searchSiblingsAndChildrenOf(node: Node, name: String, list: MutableList<Element>) {
// get the sub-nodes
var subnodes: NodeList = object : NodeList {
override fun item(index: Int): Node? {
return null
}
override fun getLength(): Int {
return 0
}
}
if (node.nodeType == Node.ELEMENT_NODE) {
subnodes = (node as Element).getElementsByTagName(name)
}
if (node.nodeType == Node.DOCUMENT_NODE) {
subnodes = (node as Document).getElementsByTagName(name)
}
for (i in 0 until subnodes.length) {
if (subnodes.item(i).nodeType == Node.ELEMENT_NODE) {
// get element
val e = subnodes.item(i) as Element
// add elements
if (e.tagName == name) {
list.add(e)
}
// search recursively
if (e.firstChild != null) {
searchSiblingsAndChildrenOf(e.firstChild, name, list)
}
}
}
}
}
| lgpl-3.0 | 6cf8f7d742523192f606a6f7978b759e | 31.340909 | 99 | 0.623799 | 4.470157 | false | false | false | false |
NextFaze/dev-fun | devfun-internal/src/main/java/com/nextfaze/devfun/internal/log/Logging.kt | 1 | 2366 | @file:Suppress("unused")
package com.nextfaze.devfun.internal.log
import androidx.annotation.Keep
import androidx.annotation.RestrictTo
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Controls trace-level logging. Disabled (`false`) by default.
*
* Enabled automatically when library is a `-SNAPSHOT` build.
*/
var allowTraceLogs = false
/**
* Creates a new logger instance using the containing class' qualified name.
*
* @internal Intended for use across DevFun libraries.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <reified T : Any> T.logger(): Logger = LoggerFactory.getLogger(T::class.java.name)
/**
* Creates a new logger instance using [name].
*
* @internal Intended for use across DevFun libraries.
*/
@Keep
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun logger(name: String): Logger = LoggerFactory.getLogger(name)
/**
* Log `trace`.
*
* @internal Intended for use across DevFun libraries.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun Logger.t(t: Throwable? = null, predicate: Boolean = true, body: () -> String) {
if (allowTraceLogs && predicate && isTraceEnabled) {
trace(body.invoke(), t)
}
}
/**
* Log `debug`.
*
* @internal Intended for use across DevFun libraries.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun Logger.d(t: Throwable? = null, predicate: Boolean = true, body: () -> String) {
if (predicate && isDebugEnabled) {
debug(body.invoke(), t)
}
}
/**
* Log `info`.
*
* @internal Intended for use across DevFun libraries.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun Logger.i(t: Throwable? = null, predicate: Boolean = true, body: () -> String) {
if (predicate && isInfoEnabled) {
info(body.invoke(), t)
}
}
/**
* Log `warn`.
*
* @internal Intended for use across DevFun libraries.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun Logger.w(t: Throwable? = null, predicate: Boolean = true, body: () -> String) {
if (predicate && isWarnEnabled) {
warn(body.invoke(), t)
}
}
/**
* Log `error`.
*
* @internal Intended for use across DevFun libraries.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun Logger.e(t: Throwable? = null, predicate: Boolean = true, body: () -> String) {
if (predicate && isErrorEnabled) {
error(body.invoke(), t)
}
}
| apache-2.0 | ab67d9b339eabe7dee5eda8a3593dc3a | 24.717391 | 93 | 0.680473 | 3.557895 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ReturnCountSpec.kt | 1 | 15481 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
private const val MAX = "max"
private const val EXCLUDED_FUNCTIONS = "excludedFunctions"
private const val EXCLUDE_LABELED = "excludeLabeled"
private const val EXCLUDE_RETURN_FROM_LAMBDA = "excludeReturnFromLambda"
private const val EXCLUDE_GUARD_CLAUSES = "excludeGuardClauses"
class ReturnCountSpec : Spek({
describe("ReturnCount rule") {
context("a function without a body") {
val code = """
fun func() = Unit
"""
it("does not report violation by default") {
assertThat(ReturnCount(Config.empty).compileAndLint(code)).isEmpty()
}
}
context("a function with an empty body") {
val code = """
fun func() {}
"""
it("does not report violation by default") {
assertThat(ReturnCount(Config.empty).compileAndLint(code)).isEmpty()
}
}
context("a file with an if condition guard clause and 2 returns") {
val code = """
fun test(x: Int): Int {
if (x < 4) return 0
when (x) {
5 -> println("x=5")
4 -> return 4
}
return 6
}
"""
it("should not get flagged for if condition guard clauses") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "true")))
.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a file with an if condition guard clause with body and 2 returns") {
val code = """
fun test(x: Int): Int {
if (x < 4) {
println("x x is less than 4")
return 0
}
when (x) {
5 -> println("x=5")
4 -> return 4
}
return 6
}
"""
it("should not get flagged for if condition guard clauses") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "true")))
.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should get flagged without guard clauses") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "false")))
.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("reports a too-complicated if statement for being a guard clause") {
val code = """
fun test(x: Int): Int {
if (x < 4) {
println("x x is less than 4")
if (x < 2) {
println("x is also less than 2")
return 1
}
return 0
}
when (x) {
5 -> println("x=5")
4 -> return 4
}
return 6
}
"""
it("should report a too-complicated if statement for being a guard clause, with EXCLUDE_GUARD_CLAUSES on") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "true")))
.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a file with an ELVIS operator guard clause and 2 returns") {
val code = """
fun test(x: Int): Int {
val y = x ?: return 0
when (x) {
5 -> println("x=5")
4 -> return 4
}
return 6
}
"""
it("should not get flagged for ELVIS operator guard clauses") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "true")))
.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a file with 2 returns and an if condition guard clause which is not the first statement") {
val code = """
fun test(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
}
if (x < 4) return 0
return 6
}
"""
it("should get flagged for an if condition guard clause which is not the first statement") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "true")))
.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a file with 2 returns and an ELVIS guard clause which is not the first statement") {
val code = """
fun test(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
}
val y = x ?: return 0
return 6
}
"""
it("should get flagged for an ELVIS guard clause which is not the first statement") {
val findings = ReturnCount(TestConfig(mapOf(EXCLUDE_GUARD_CLAUSES to "true")))
.compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a file with multiple guard clauses") {
val code = """
fun multipleGuards(a: Int?, b: Any?, c: Int?) {
if(a == null) return
val models = b as? Int ?: return
val position = c?.takeIf { it != -1 } ?: return
if(b !is String) {
println("b is not a String")
return
}
return
}
"""
it("should not count all four guard clauses") {
val findings = ReturnCount(
TestConfig(
EXCLUDE_GUARD_CLAUSES to "true"
)
).compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should count all four guard clauses") {
val findings = ReturnCount(
TestConfig(
EXCLUDE_GUARD_CLAUSES to "false"
)
).compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a file with 3 returns") {
val code = """
fun test(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
3 -> return 3
}
return 6
}
"""
it("should get flagged by default") {
val findings = ReturnCount().compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should not get flagged when max value is 3") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "3"))).compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should get flagged when max value is 1") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "1"))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a file with 2 returns") {
val code = """
fun test(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
}
return 6
}
"""
it("should not get flagged by default") {
val findings = ReturnCount().compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not get flagged when max value is 2") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "2"))).compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should get flagged when max value is 1") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "1"))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a function is ignored") {
val code = """
fun test(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
3 -> return 3
}
return 6
}
"""
it("should not get flagged") {
val findings = ReturnCount(
TestConfig(
mapOf(
MAX to "2",
EXCLUDED_FUNCTIONS to "test"
)
)
).compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a subset of functions are ignored") {
val code = """
fun test1(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
3 -> return 3
}
return 6
}
fun test2(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
3 -> return 3
}
return 6
}
fun test3(x: Int): Int {
when (x) {
5 -> println("x=5")
4 -> return 4
3 -> return 3
}
return 6
}
"""
it("should flag none of the ignored functions") {
val findings = ReturnCount(
TestConfig(
mapOf(
MAX to "2",
EXCLUDED_FUNCTIONS to "test1,test2"
)
)
).compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("a function with inner object") {
val code = """
fun test(x: Int): Int {
val a = object {
fun test2(x: Int): Int {
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
}
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
"""
it("should not get flag when returns is in inner object") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "2"))).compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a function with 2 inner object") {
val code = """
fun test(x: Int): Int {
val a = object {
fun test2(x: Int): Int {
val b = object {
fun test3(x: Int): Int {
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
}
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
}
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
"""
it("should not get flag when returns is in inner object") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "2"))).compileAndLint(code)
assertThat(findings).isEmpty()
}
}
context("a function with 2 inner object and exceeded max") {
val code = """
fun test(x: Int): Int {
val a = object {
fun test2(x: Int): Int {
val b = object {
fun test3(x: Int): Int {
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
}
when (x) {
5 -> println("x=5")
else -> return 0
}
return 6
}
}
when (x) {
5 -> println("x=5")
4 -> return 4
3 -> return 3
else -> return 0
}
return 6
}
"""
it("should get flagged when returns is in inner object") {
val findings = ReturnCount(TestConfig(mapOf(MAX to "2"))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
}
context("function with multiple labeled return statements") {
val code = """
fun readUsers(name: String): Flowable<User> {
return userDao.read(name)
.flatMap {
if (it.isEmpty()) return@flatMap Flowable.empty<User>()
return@flatMap Flowable.just(it[0])
}
}
"""
it("should not count labeled returns from lambda by default") {
val findings = ReturnCount().lint(code)
assertThat(findings).isEmpty()
}
it("should count labeled returns from lambda when activated") {
val findings = ReturnCount(
TestConfig(mapOf(EXCLUDE_RETURN_FROM_LAMBDA to "false"))
).lint(code)
assertThat(findings).hasSize(1)
}
it("should be empty when labeled returns are de-activated") {
val findings = ReturnCount(
TestConfig(
mapOf(
EXCLUDE_LABELED to "true",
EXCLUDE_RETURN_FROM_LAMBDA to "false"
)
)
).lint(code)
assertThat(findings).isEmpty()
}
}
}
})
| apache-2.0 | 6f21acb435f752ac65aff5023621d7df | 32.436285 | 120 | 0.404819 | 5.542786 | false | true | false | false |
Ztiany/Repository | Kotlin/Kotlin-NoArgSample/src/main/java/me/ztiany/noarg/NoArgMain.kt | 2 | 1173 | package me.ztiany.noarg
import com.google.gson.Gson
import java.util.*
const val json1 = "{\"age\":20,\"name\":\"ztiany\"}"
const val json2 = "{\"age\":20}"
annotation class NoArg
@NoArg
data class DataA(
val name: String,
val age: Int
)
@NoArg
data class DataB(
var name: String = "DataB",
val age: Int
) {
//初始化逻辑
init {
name = "DataB"
}
}
data class DataC(
val name: String = "DataC",
val age: Int = 0
)
data class DataD(
val name: String = "DataD",
val age: Int
)
fun main(args: Array<String>) {
val gson = Gson()
println(gson.fromJson(json1, DataA::class.java))
println(gson.fromJson(json1, DataB::class.java))
println(gson.fromJson(json1, DataC::class.java))
println(gson.fromJson(json1, DataD::class.java))
println(gson.fromJson(json2, DataA::class.java))
println(gson.fromJson(json2, DataB::class.java))
println(gson.fromJson(json2, DataC::class.java))
println(gson.fromJson(json2, DataD::class.java))
println(DataB::class.java.newInstance())
println(Arrays.toString(DataB::class.java.constructors))
println(DataD::class.java.newInstance())
}
| apache-2.0 | ad3a6e25088dafa98b18c6624fa22995 | 20.145455 | 60 | 0.652623 | 3.143243 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/util/ParcelableUserListUtils.kt | 1 | 1777 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <mail@vanit.as>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.model.util
import android.text.TextUtils
import de.vanita5.twittnuker.model.ParcelableUserList
import de.vanita5.twittnuker.model.UserKey
object ParcelableUserListUtils {
fun check(userList: ParcelableUserList, accountKey: UserKey, listId: String?,
userKey: UserKey?, screenName: String?, listName: String?): Boolean {
if (userList.account_key != accountKey) return false
if (listId != null) {
return TextUtils.equals(listId, userList.id)
} else if (listName != null) {
if (!TextUtils.equals(listName, userList.name)) return false
if (userKey != null) {
return userKey == userList.user_key
} else if (screenName != null) {
return TextUtils.equals(screenName, userList.user_screen_name)
}
}
return false
}
} | gpl-3.0 | 09a154ca71c744f6d9da18dd4b18769f | 37.652174 | 83 | 0.688239 | 4.344743 | false | false | false | false |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/geometry/Position.kt | 1 | 1329 | package org.hildan.minecraft.mining.optimizer.geometry
val ONE_EAST: Distance3D = Distance3D.of(+1, 0, 0)
val ONE_WEST: Distance3D = Distance3D.of(-1, 0, 0)
val ONE_ABOVE: Distance3D = Distance3D.of(0, +1, 0)
val ONE_BELOW: Distance3D = Distance3D.of(0, -1, 0)
val ONE_SOUTH: Distance3D = Distance3D.of(0, 0, +1)
val ONE_NORTH: Distance3D = Distance3D.of(0, 0, -1)
/**
* A generic 3D vector.
*/
interface Vector3D {
val x: Int
val y: Int
val z: Int
val sqNorm: Int
get() = x * x + y * y + z * z
}
/**
* An immutable 3D position.
*/
interface Position : Vector3D {
companion object {
fun of(x: Int, y: Int, z: Int): Position = BasicVector.of(x, y, z)
}
}
/**
* An immutable 3D distance.
*/
interface Distance3D : Vector3D {
companion object {
fun of(dx: Int, dy: Int, dz: Int): Distance3D = BasicVector.of(dx, dy, dz)
}
}
private data class BasicVector(
override val x: Int,
override val y: Int,
override val z: Int,
) : Position, Distance3D {
companion object {
private val cache: MutableMap<Int, MutableMap<Int, MutableMap<Int, BasicVector>>> = HashMap()
fun of(x: Int, y: Int, z: Int): BasicVector {
return cache.getOrPut(x, ::HashMap).getOrPut(y, ::HashMap).getOrPut(z) { BasicVector(x, y, z) }
}
}
}
| mit | 5206ea6cefbd6a0f9a2240a52634d2f1 | 24.557692 | 107 | 0.61851 | 2.953333 | false | false | false | false |
mwudka/aftflight-alexa | src/main/kotlin/com/mwudka/aftflight/core/StationDatabase.kt | 1 | 1322 | package com.mwudka.aftflight.core
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
data class Station(
@JacksonXmlProperty(isAttribute = false, localName = "station_id") val stationId: String,
@JacksonXmlProperty(isAttribute = false, localName = "site") val site: String
)
data class StationInfo(@JacksonXmlProperty(isAttribute = false, localName = "data") val data: List<Station>)
class StationDatabase {
val size: Int
private val database: Map<StationIdentifier, Station>
fun getStationInfo(stationId: StationIdentifier): Station = database[stationId]!!
init {
val xmlMapper = XmlMapper()
xmlMapper.registerModule(JodaModule())
xmlMapper.registerModule(KotlinModule())
xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
val stationInfo = xmlMapper.readValue(this.javaClass.getResourceAsStream("/station_info.xml"), StationInfo::class.java)
database = stationInfo.data.map { Pair(StationIdentifier(it.stationId), it) }.toMap()
size = database.size
}
}
| mit | 15388f0c5789d9f58558a256151061e6 | 37.882353 | 127 | 0.755673 | 4.377483 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/modifier/ModifierLocalNode.kt | 3 | 7781 | /*
* Copyright 2022 The Android Open Source Project
*
* 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.
*/
package androidx.compose.ui.modifier
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.node.DelegatableNode
import androidx.compose.ui.node.Nodes
import androidx.compose.ui.node.visitAncestors
/**
* An opaque key-value holder of [ModifierLocal]s to be used with [ModifierLocalNode].
*
* @see modifierLocalMapOf
*/
@ExperimentalComposeUiApi
sealed class ModifierLocalMap() {
internal abstract operator fun <T> set(key: ModifierLocal<T>, value: T)
internal abstract operator fun <T> get(key: ModifierLocal<T>): T?
internal abstract operator fun contains(key: ModifierLocal<*>): Boolean
}
@OptIn(ExperimentalComposeUiApi::class)
internal class SingleLocalMap(
private val key: ModifierLocal<*>
) : ModifierLocalMap() {
private var value: Any? by mutableStateOf(null)
internal fun forceValue(value: Any?) {
this.value = value
}
override operator fun <T> set(key: ModifierLocal<T>, value: T) {
check(key === this.key)
this.value = value
}
override operator fun <T> get(key: ModifierLocal<T>): T? {
check(key === this.key)
@Suppress("UNCHECKED_CAST")
return value as? T?
}
override operator fun contains(key: ModifierLocal<*>): Boolean = key === this.key
}
@OptIn(ExperimentalComposeUiApi::class)
internal class BackwardsCompatLocalMap(
var element: ModifierLocalProvider<*>
) : ModifierLocalMap() {
override operator fun <T> set(key: ModifierLocal<T>, value: T) {
error("Set is not allowed on a backwards compat provider")
}
override operator fun <T> get(key: ModifierLocal<T>): T? {
check(key === element.key)
@Suppress("UNCHECKED_CAST")
return element.value as T
}
override operator fun contains(key: ModifierLocal<*>): Boolean = key === element.key
}
@OptIn(ExperimentalComposeUiApi::class)
internal class MultiLocalMap(
vararg entries: Pair<ModifierLocal<*>, Any?>
) : ModifierLocalMap() {
private val map = mutableStateMapOf<ModifierLocal<*>, Any?>()
init {
map.putAll(entries.toMap())
}
override operator fun <T> set(key: ModifierLocal<T>, value: T) {
map[key] = value
}
override operator fun <T> get(key: ModifierLocal<T>): T? {
@Suppress("UNCHECKED_CAST")
return map[key] as? T?
}
override operator fun contains(key: ModifierLocal<*>): Boolean = map.containsKey(key)
}
@OptIn(ExperimentalComposeUiApi::class)
internal object EmptyMap : ModifierLocalMap() {
override fun <T> set(key: ModifierLocal<T>, value: T) = error("")
override fun <T> get(key: ModifierLocal<T>): T? = error("")
override fun contains(key: ModifierLocal<*>): Boolean = false
}
/**
* A [androidx.compose.ui.Modifier.Node] that is capable of consuming and providing [ModifierLocal]
* values.
*
* This is the [androidx.compose.ui.Modifier.Node] equivalent of the [ModifierLocalConsumer]
* and [ModifierLocalProvider] interfaces.
*
* @sample androidx.compose.ui.samples.JustReadingOrProvidingModifierLocalNodeSample
*
* @see modifierLocalOf
* @see ModifierLocal
* @see androidx.compose.runtime.CompositionLocal
*/
@ExperimentalComposeUiApi
interface ModifierLocalNode : ModifierLocalReadScope, DelegatableNode {
/**
* The map of provided ModifierLocal <-> value pairs that this node is providing. This value
* must be overridden if you are going to provide any values. It should be overridden as a
* field-backed property initialized with values for all of the keys that it will ever possibly
* provide.
*
* By default, this property will be set to an empty map, which means that this node will only
* consume [ModifierLocal]s and will not provide any new values.
*
* If you would like to change a value provided in the map over time, you must use the [provide]
* API.
*
* @see modifierLocalMapOf
* @see provide
*/
val providedValues: ModifierLocalMap get() = EmptyMap
/**
* This method will cause this node to provide a new [value] for [key]. This can be called at
* any time on the UI thread, but in order to use this API, [providedValues] must be
* implemented and [key] must be a key that was included in it.
*
* By providing this new value, any [ModifierLocalNode] below it in the tree will read this
* [value] when reading [current], until another [ModifierLocalNode] provides a value for the
* same [key], however, consuming [ModifierLocalNode]s will NOT be notified that a new value
* was provided.
*/
fun <T> provide(key: ModifierLocal<T>, value: T) {
require(providedValues !== EmptyMap) {
"In order to provide locals you must override providedValues: ModifierLocalMap"
}
require(providedValues.contains(key)) {
"Any provided key must be initially provided in the overridden providedValues: " +
"ModifierLocalMap property. Key $key was not found."
}
providedValues[key] = value
}
/**
* Read a [ModifierLocal] that was provided by other modifiers to the left of this modifier,
* or above this modifier in the layout tree.
*/
override val <T> ModifierLocal<T>.current: T
get() {
require(node.isAttached)
val key = this
visitAncestors(Nodes.Locals) {
if (it.providedValues.contains(key)) {
@Suppress("UNCHECKED_CAST")
return it.providedValues[key] as T
}
}
return key.defaultFactory()
}
}
/**
* Creates an empty [ModifierLocalMap]
*/
@ExperimentalComposeUiApi
fun modifierLocalMapOf(): ModifierLocalMap = EmptyMap
/**
* Creates a [ModifierLocalMap] with a single key and value initialized to null.
*/
@ExperimentalComposeUiApi
fun <T> modifierLocalMapOf(
key: ModifierLocal<T>
): ModifierLocalMap = SingleLocalMap(key)
/**
* Creates a [ModifierLocalMap] with a single key and value. The provided [entry] should have
* [Pair::first] be the [ModifierLocal] key, and the [Pair::second] be the corresponding value.
*/
@ExperimentalComposeUiApi
fun <T> modifierLocalMapOf(
entry: Pair<ModifierLocal<T>, T>
): ModifierLocalMap = SingleLocalMap(entry.first).also { it[entry.first] = entry.second }
/**
* Creates a [ModifierLocalMap] with several keys, all initialized with values of null
*/
@ExperimentalComposeUiApi
fun modifierLocalMapOf(
vararg keys: ModifierLocal<*>
): ModifierLocalMap = MultiLocalMap(*keys.map { it to null }.toTypedArray())
/**
* Creates a [ModifierLocalMap] with multiple keys and values. The provided [entries] should have
* each item's [Pair::first] be the [ModifierLocal] key, and the [Pair::second] be the
* corresponding value.
*/
@ExperimentalComposeUiApi
fun modifierLocalMapOf(
vararg entries: Pair<ModifierLocal<*>, Any>
): ModifierLocalMap = MultiLocalMap(*entries)
| apache-2.0 | 6a13918a30158dae2747a0b856e3681c | 34.52968 | 100 | 0.692713 | 4.282334 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsExternalLinterInspection.kt | 2 | 10671 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInsight.daemon.impl.AnnotationHolderImpl
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ex.GlobalInspectionContextImpl
import com.intellij.codeInspection.ex.GlobalInspectionContextUtil
import com.intellij.codeInspection.reference.RefElement
import com.intellij.codeInspection.ui.InspectionToolPresentation
import com.intellij.lang.annotation.Annotation
import com.intellij.lang.annotation.AnnotationSession
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.profile.codeInspection.InspectionProjectProfileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.containers.ContainerUtil
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.cargo.runconfig.command.workingDirectory
import org.rust.cargo.toolchain.impl.Applicability
import org.rust.cargo.toolchain.tools.CargoCheckArgs
import org.rust.ide.annotator.RsExternalLinterResult
import org.rust.ide.annotator.RsExternalLinterUtils
import org.rust.ide.annotator.createAnnotationsForFile
import org.rust.ide.annotator.createDisposableOnAnyPsiChange
import org.rust.lang.core.crate.asNotFake
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.stdext.buildList
import java.util.*
class RsExternalLinterInspection : GlobalSimpleInspectionTool() {
override fun inspectionStarted(
manager: InspectionManager,
globalContext: GlobalInspectionContext,
problemDescriptionsProcessor: ProblemDescriptionsProcessor
) {
globalContext.putUserData(ANALYZED_FILES, ContainerUtil.newConcurrentSet())
}
override fun checkFile(
file: PsiFile,
manager: InspectionManager,
problemsHolder: ProblemsHolder,
globalContext: GlobalInspectionContext,
problemDescriptionsProcessor: ProblemDescriptionsProcessor
) {
if (file !is RsFile || file.containingCrate.asNotFake?.origin != PackageOrigin.WORKSPACE) return
val analyzedFiles = globalContext.getUserData(ANALYZED_FILES) ?: return
analyzedFiles.add(file)
}
override fun inspectionFinished(
manager: InspectionManager,
globalContext: GlobalInspectionContext,
problemDescriptionsProcessor: ProblemDescriptionsProcessor
) {
if (globalContext !is GlobalInspectionContextImpl) return
val analyzedFiles = globalContext.getUserData(ANALYZED_FILES) ?: return
val project = manager.project
val currentProfile = InspectionProjectProfileManager.getInstance(project).currentProfile
val toolWrapper = currentProfile.getInspectionTool(SHORT_NAME, project) ?: return
while (true) {
val disposable = project.messageBus.createDisposableOnAnyPsiChange()
.also { Disposer.register(project, it) }
val cargoProjects = run {
val allProjects = project.cargoProjects.allProjects
if (allProjects.size == 1) {
setOf(allProjects.first())
} else {
analyzedFiles.mapNotNull { it.cargoProject }.toSet()
}
}
val futures = cargoProjects.map {
ApplicationManager.getApplication().executeOnPooledThread<RsExternalLinterResult?> {
checkProjectLazily(it, disposable)?.value
}
}
val annotationResults = futures.mapNotNull { it.get() }
val exit = runReadAction {
ProgressManager.checkCanceled()
if (Disposer.isDisposed(disposable)) return@runReadAction false
if (annotationResults.size < cargoProjects.size) return@runReadAction true
for (annotationResult in annotationResults) {
val problemDescriptors = getProblemDescriptors(analyzedFiles, annotationResult)
val presentation = globalContext.getPresentation(toolWrapper)
presentation.addProblemDescriptors(problemDescriptors, globalContext)
}
true
}
if (exit) break
}
}
override fun getDisplayName(): String = "External Linter"
override fun getShortName(): String = SHORT_NAME
companion object {
const val SHORT_NAME: String = "RsExternalLinter"
private val ANALYZED_FILES: Key<MutableSet<RsFile>> = Key.create("ANALYZED_FILES")
private fun checkProjectLazily(
cargoProject: CargoProject,
disposable: Disposable
): Lazy<RsExternalLinterResult?>? = runReadAction {
RsExternalLinterUtils.checkLazily(
cargoProject.project.toolchain ?: return@runReadAction null,
cargoProject.project,
disposable,
cargoProject.workingDirectory,
CargoCheckArgs.forCargoProject(cargoProject)
)
}
/** TODO: Use [ProblemDescriptorUtil.convertToProblemDescriptors] instead */
private fun convertToProblemDescriptors(annotations: List<Annotation>, file: PsiFile): List<ProblemDescriptor> {
if (annotations.isEmpty()) return emptyList()
val problems = ArrayList<ProblemDescriptor>(annotations.size)
val quickFixMappingCache = IdentityHashMap<IntentionAction, LocalQuickFix>()
for (annotation in annotations) {
if (annotation.severity === HighlightSeverity.INFORMATION ||
annotation.startOffset == annotation.endOffset &&
!annotation.isAfterEndOfLine) {
continue
}
val (startElement, endElement) =
if (annotation.startOffset == annotation.endOffset && annotation.isAfterEndOfLine) {
val element = file.findElementAt(annotation.endOffset - 1)
Pair(element, element)
} else {
Pair(file.findElementAt(annotation.startOffset), file.findElementAt(annotation.endOffset - 1))
}
if (startElement == null || endElement == null) continue
val quickFixes = toLocalQuickFixes(annotation.quickFixes, quickFixMappingCache)
val highlightType = HighlightInfo.convertSeverityToProblemHighlight(annotation.severity)
val descriptor = ProblemDescriptorBase(
startElement,
endElement,
annotation.message,
quickFixes,
highlightType,
annotation.isAfterEndOfLine,
null,
true,
false
)
problems.add(descriptor)
}
return problems
}
private fun toLocalQuickFixes(
fixInfos: List<Annotation.QuickFixInfo>?,
quickFixMappingCache: IdentityHashMap<IntentionAction, LocalQuickFix>
): Array<LocalQuickFix> {
if (fixInfos == null || fixInfos.isEmpty()) return LocalQuickFix.EMPTY_ARRAY
return fixInfos.map { fixInfo ->
val intentionAction = fixInfo.quickFix
if (intentionAction is LocalQuickFix) {
intentionAction
} else {
var lqf = quickFixMappingCache[intentionAction]
if (lqf == null) {
lqf = ExternalAnnotatorInspectionVisitor.LocalQuickFixBackedByIntentionAction(intentionAction)
quickFixMappingCache[intentionAction] = lqf
}
lqf
}
}.toTypedArray()
}
private fun getProblemDescriptors(
analyzedFiles: Set<RsFile>,
annotationResult: RsExternalLinterResult
): List<ProblemDescriptor> = buildList {
for (file in analyzedFiles) {
if (!file.isValid) continue
@Suppress("UnstableApiUsage", "DEPRECATION")
val annotationHolder = AnnotationHolderImpl(AnnotationSession(file))
@Suppress("UnstableApiUsage")
annotationHolder.runAnnotatorWithContext(file) { _, holder ->
holder.createAnnotationsForFile(file, annotationResult, Applicability.MACHINE_APPLICABLE)
}
addAll(convertToProblemDescriptors(annotationHolder, file))
}
}
private fun InspectionToolPresentation.addProblemDescriptors(
descriptors: List<ProblemDescriptor>,
context: GlobalInspectionContext
) {
if (descriptors.isEmpty()) return
val problems = hashMapOf<RefElement, MutableList<ProblemDescriptor>>()
for (descriptor in descriptors) {
val element = descriptor.psiElement ?: continue
val refElement = getProblemElement(element, context) ?: continue
val elementProblems = problems.getOrPut(refElement) { mutableListOf() }
elementProblems.add(descriptor)
}
for ((refElement, problemDescriptors) in problems) {
val descriptions = problemDescriptors.toTypedArray<CommonProblemDescriptor>()
addProblemElement(refElement, false, *descriptions)
}
}
private fun getProblemElement(element: PsiElement, context: GlobalInspectionContext): RefElement? {
val problemElement = element.ancestorOrSelf<RsFile>()
val refElement = context.refManager.getReference(problemElement)
return if (refElement == null && problemElement != null) {
GlobalInspectionContextUtil.retrieveRefElement(element, context)
} else {
refElement
}
}
}
}
| mit | e9f7b8ecf93019e603042e4f0ccdd869 | 42.733607 | 120 | 0.652329 | 5.688166 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/builtin/PlayerInventorySlotManager.kt | 1 | 1947 | package com.teamwizardry.librarianlib.facade.container.builtin
import com.teamwizardry.librarianlib.facade.container.slot.SlotManager
import com.teamwizardry.librarianlib.facade.container.slot.SlotRegion
import net.minecraft.entity.EquipmentSlot
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.util.Hand
public class PlayerInventorySlotManager(inventory: PlayerInventory): SlotManager(inventory) {
public val armor: SlotRegion = all[36..39]
public val head: SlotRegion = all[39]
public val chest: SlotRegion = all[38]
public val legs: SlotRegion = all[37]
public val feet: SlotRegion = all[36]
public val hotbar: SlotRegion = all[0..8]
public val main: SlotRegion = all[9..35]
public val offhand: SlotRegion = all[40]
public val mainhand: SlotRegion = if(inventory.selectedSlot in 0..8) all[inventory.selectedSlot] else SlotRegion.EMPTY
init {
head.setFactory { inv, i -> PlayerEquipmentSlot(inv, i, inventory.player, EquipmentSlot.HEAD) }
chest.setFactory { inv, i -> PlayerEquipmentSlot(inv, i, inventory.player, EquipmentSlot.CHEST) }
legs.setFactory { inv, i -> PlayerEquipmentSlot(inv, i, inventory.player, EquipmentSlot.LEGS) }
feet.setFactory { inv, i -> PlayerEquipmentSlot(inv, i, inventory.player, EquipmentSlot.FEET) }
}
public fun getHandSlot(hand: Hand): SlotRegion {
return when(hand) {
Hand.MAIN_HAND -> getEquipmentSlot(EquipmentSlot.MAINHAND)
Hand.OFF_HAND -> getEquipmentSlot(EquipmentSlot.OFFHAND)
}
}
private fun getEquipmentSlot(slotType: EquipmentSlot): SlotRegion {
return when(slotType) {
EquipmentSlot.MAINHAND -> mainhand
EquipmentSlot.OFFHAND -> offhand
EquipmentSlot.FEET -> feet
EquipmentSlot.LEGS -> legs
EquipmentSlot.CHEST -> chest
EquipmentSlot.HEAD -> head
}
}
} | lgpl-3.0 | 20820a38e913945beaefe9d5abd9eba4 | 41.347826 | 122 | 0.700565 | 4.169165 | false | false | false | false |
matt-richardson/TeamCity.Node | common/src/com/jonnyzzz/teamcity/plugins/node/common/Extensions.kt | 2 | 2831 | /*
* Copyright 2013-2013 Eugene Petrenko
*
* 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.
*/
package com.jonnyzzz.teamcity.plugins.node.common
import java.io.File
import org.apache.log4j.Logger
import java.io.IOException
import jetbrains.buildServer.util.FileUtil
import java.io.Closeable
import java.util.HashMap
/**
* Created by Eugene Petrenko (eugene.petrenko@gmail.com)
* Date: 12.01.13 0:41
*/
fun String?.isEmptyOrSpaces() : Boolean = com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces(this)
fun String.splitHonorQuotes() : List<String> = jetbrains.buildServer.util.StringUtil.splitHonorQuotes(this).filterNotNull()
fun String.n(s:String) : String = this + "\n" + s
fun String?.fetchArguments() : Collection<String> {
if (this == null || this.isEmptyOrSpaces()) return listOf()
return this
.split("[\\r\\n]+")
.map { it.trim() }
.filter { !it.isEmptyOrSpaces() }
.flatMap{ it.splitHonorQuotes() }
}
fun File.resolve(relativePath : String) : File = jetbrains.buildServer.util.FileUtil.resolvePath(this, relativePath)
data class TempFileName(val prefix : String, val suffix : String)
fun File.tempFile(details : TempFileName) : File = com.intellij.openapi.util.io.FileUtil.createTempFile(this, details.prefix, details.suffix, true) ?: throw IOException("Failed to create temp file under ${this}")
fun File.smartDelete() = com.intellij.openapi.util.io.FileUtil.delete(this)
//we define this category to have plugin logging without logger configs patching
fun log4j<T>(clazz : Class<T>) : Logger = Logger.getLogger("jetbrains.buildServer.${clazz.getName()}")!!
fun File.div(child : String) : File = File(this, child)
fun String.trimStart(x : String) : String = if (startsWith(x)) substring(x.length()) else this
inline fun <T, S:Closeable>using(stream:S, action:(S)->T) : T {
try {
return action(stream)
} finally {
FileUtil.close(stream)
}
}
inline fun <T, S:Closeable>catchIO(stream:S, error:(IOException) -> Throwable, action:(S)->T) : T =
using(stream) {
try {
action(stream)
} catch(e: IOException) {
throw error(e)
}
}
fun <K,V,T:MutableMap<K, V>> T.plus(m:Map<K, V>) : T {
this.putAll(m)
return this
}
fun <K : Any, T:Iterable<K>> T.firstOrEmpty() : K? {
for(k in this) return k
return null
}
| apache-2.0 | 0539f0b2169ec098916fd932d32d75b3 | 32.305882 | 212 | 0.706464 | 3.53875 | false | false | false | false |
androidx/androidx | datastore/datastore-core-okio/src/commonMain/kotlin/androidx/datastore/core/okio/OkioStorage.kt | 3 | 6221 | /*
* Copyright 2022 The Android Open Source Project
*
* 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.
*/
package androidx.datastore.core.okio
import androidx.datastore.core.ReadScope
import androidx.datastore.core.Storage
import androidx.datastore.core.StorageConnection
import androidx.datastore.core.WriteScope
import androidx.datastore.core.use
import kotlinx.atomicfu.locks.synchronized
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okio.FileNotFoundException
import okio.FileSystem
import okio.IOException
import okio.Path
import okio.buffer
import okio.use
/**
* OKIO implementation of the Storage interface, providing cross platform IO using the OKIO library.
*/
public class OkioStorage<T>(
private val fileSystem: FileSystem,
private val serializer: OkioSerializer<T>,
private val producePath: () -> Path
) : Storage<T> {
private val canonicalPath by lazy {
val path = producePath()
check(path.isAbsolute) {
"OkioStorage requires absolute paths, but did not get an absolute path from " +
"producePath = $producePath, instead got $path"
}
path
}
override fun createConnection(): StorageConnection<T> {
canonicalPath.toString().let { path ->
synchronized(activeFilesLock) {
check(!activeFiles.contains(path)) {
"There are multiple DataStores active for the same file: $path. You should " +
"either maintain your DataStore as a singleton or confirm that there is " +
"no two DataStore's active on the same file (by confirming that the scope" +
" is cancelled)."
}
activeFiles.add(path)
}
}
return OkioStorageConnection(fileSystem, canonicalPath, serializer) {
synchronized(activeFilesLock) {
activeFiles.remove(canonicalPath.toString())
}
}
}
internal companion object {
internal val activeFiles = mutableSetOf<String>()
class Sync : SynchronizedObject()
internal val activeFilesLock = Sync()
}
}
internal class OkioStorageConnection<T>(
private val fileSystem: FileSystem,
private val path: Path,
private val serializer: OkioSerializer<T>,
private val onClose: () -> Unit
) : StorageConnection<T> {
private val closed = AtomicBoolean(false)
// TODO:(b/233402915) support multiple readers
private val transactionMutex = Mutex()
override suspend fun <R> readScope(
block: suspend ReadScope<T>.(locked: Boolean) -> R
): R {
checkNotClosed()
val lock = transactionMutex.tryLock()
try {
OkioReadScope(fileSystem, path, serializer).use {
return block(it, lock)
}
} finally {
if (lock) {
transactionMutex.unlock()
}
}
}
override suspend fun writeScope(block: suspend WriteScope<T>.() -> Unit) {
checkNotClosed()
val parentDir = path.parent ?: error("must have a parent path")
fileSystem.createDirectories(
dir = parentDir,
mustCreate = false
)
transactionMutex.withLock {
val scratchPath = parentDir / "${path.name}.tmp"
try {
fileSystem.delete(
path = scratchPath,
mustExist = false
)
OkioWriteScope(fileSystem, scratchPath, serializer).use {
block(it)
}
if (fileSystem.exists(scratchPath)) {
fileSystem.atomicMove(scratchPath, path)
}
} catch (ex: IOException) {
if (fileSystem.exists(scratchPath)) {
try {
fileSystem.delete(scratchPath)
} catch (e: IOException) {
// swallow failure to delete
}
}
throw ex
}
}
}
private fun checkNotClosed() {
check(!closed.get()) { "StorageConnection has already been disposed." }
}
override fun close() {
closed.set(true)
onClose()
}
}
internal open class OkioReadScope<T>(
protected val fileSystem: FileSystem,
protected val path: Path,
protected val serializer: OkioSerializer<T>
) : ReadScope<T> {
private var closed by atomic(false)
override suspend fun readData(): T {
checkClose()
return try {
fileSystem.read(
file = path
) {
serializer.readFrom(this)
}
} catch (ex: FileNotFoundException) {
if (fileSystem.exists(path)) {
throw ex
}
serializer.defaultValue
}
}
override fun close() {
closed = true
}
protected fun checkClose() {
check(!closed) { "This scope has already been closed." }
}
}
internal class OkioWriteScope<T>(
fileSystem: FileSystem,
path: Path,
serializer: OkioSerializer<T>
) :
OkioReadScope<T>(fileSystem, path, serializer), WriteScope<T> {
override suspend fun writeData(value: T) {
checkClose()
val fileHandle = fileSystem.openReadWrite(path)
fileHandle.use { handle ->
handle.sink().buffer().use { sink ->
serializer.writeTo(value, sink)
handle.flush()
}
}
}
} | apache-2.0 | 42b175f03cf69ae3792880fadfed2b72 | 29.955224 | 100 | 0.596206 | 4.867762 | false | false | false | false |
actions-on-google/appactions-common-biis-kotlin | app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local/TasksLocalDataSource.kt | 1 | 3598 | /*
* Copyright (C) 2020 Google LLC
*
* 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.
*/
package com.example.android.architecture.blueprints.todoapp.data.source.local
import androidx.lifecycle.LiveData
import androidx.lifecycle.map
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Error
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Concrete implementation of a data source as a db.
*/
class TasksLocalDataSource internal constructor(
private val tasksDao: TasksDao,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksDataSource {
override fun observeTasks(): LiveData<Result<List<Task>>> {
return tasksDao.observeTasks().map {
Success(it)
}
}
override fun observeTask(taskId: String): LiveData<Result<Task>> {
return tasksDao.observeTaskById(taskId).map {
Success(it)
}
}
override suspend fun refreshTask(taskId: String) {
// NO-OP
}
override suspend fun refreshTasks() {
// NO-OP
}
override suspend fun getTasks(): Result<List<Task>> = withContext(ioDispatcher) {
return@withContext try {
Success(tasksDao.getTasks())
} catch (e: Exception) {
Error(e)
}
}
override suspend fun getTask(taskId: String): Result<Task> = withContext(ioDispatcher) {
try {
val task = tasksDao.getTaskById(taskId)
if (task != null) {
return@withContext Success(task)
} else {
return@withContext Error(Exception("Task not found!"))
}
} catch (e: Exception) {
return@withContext Error(e)
}
}
override suspend fun saveTask(task: Task) = withContext(ioDispatcher) {
tasksDao.insertTask(task)
}
override suspend fun completeTask(task: Task) = withContext(ioDispatcher) {
tasksDao.updateCompleted(task.id, true)
}
override suspend fun completeTask(taskId: String) {
tasksDao.updateCompleted(taskId, true)
}
override suspend fun activateTask(task: Task) = withContext(ioDispatcher) {
tasksDao.updateCompleted(task.id, false)
}
override suspend fun activateTask(taskId: String) {
tasksDao.updateCompleted(taskId, false)
}
override suspend fun clearCompletedTasks() = withContext<Unit>(ioDispatcher) {
tasksDao.deleteCompletedTasks()
}
override suspend fun deleteAllTasks() = withContext(ioDispatcher) {
tasksDao.deleteTasks()
}
override suspend fun deleteTask(taskId: String) = withContext<Unit>(ioDispatcher) {
tasksDao.deleteTaskById(taskId)
}
}
| apache-2.0 | 732202e986369a77d658f4fc6a521cba | 32.009174 | 92 | 0.690384 | 4.46402 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-util/src/main/java/org/ccci/gto/android/common/util/ReflectionUtils.kt | 2 | 875 | package org.ccci.gto.android.common.util
import java.lang.reflect.Field
import org.ccci.gto.android.common.util.lang.getDeclaredMethodOrNull
import timber.log.Timber
inline fun <reified T> getDeclaredFieldOrNull(name: String) = try {
T::class.java.getDeclaredField(name).apply { isAccessible = true }
} catch (e: Exception) {
Timber.tag("ReflectionUtils").e(e, "error resolving ${T::class.java.simpleName}.$name")
null
}
inline fun <reified T> getDeclaredMethodOrNull(name: String, vararg parameterTypes: Class<*>) =
T::class.java.getDeclaredMethodOrNull(name, *parameterTypes)
fun Field.getOrNull(obj: Any) = try {
get(obj)
} catch (e: Exception) {
Timber.tag("ReflectionUtils").e(e, "error retrieving field value for field: $this")
null
}
@JvmName("getOrNullReified")
inline fun <reified T> Field.getOrNull(obj: Any) = getOrNull(obj) as? T
| mit | d59308d26729f4a06d749258d74e4658 | 34 | 95 | 0.733714 | 3.600823 | false | false | false | false |
java-opengl-labs/learn-OpenGL | src/main/kotlin/learnOpenGL/common/util.kt | 1 | 5263 | package learnOpenGL.common
import gli_.Format
import gli_.Target
import gli_.Texture
import gli_.gl
import gli_.gli
import glm_.set
import glm_.vec3.Vec3i
import gln.texture.glTexImage2D
import org.lwjgl.opengl.GL11
import org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE
import org.lwjgl.opengl.GL12.GL_TEXTURE_WRAP_R
import org.lwjgl.opengl.GL13.GL_TEXTURE_CUBE_MAP
import org.lwjgl.opengl.GL13.GL_TEXTURE_CUBE_MAP_POSITIVE_X
import org.lwjgl.opengl.GL30
import uno.buffer.toBuf
import uno.glfw.GlfwWindow
import uno.kotlin.uri
import java.awt.image.BufferedImage
import java.awt.image.DataBufferByte
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
/**
* Created by elect on 23/04/2017.
*/
fun readFile(filePath: String): String {
val url = GlfwWindow::javaClass.javaClass.classLoader.getResource(filePath)
val file = File(url.toURI())
return file.readText()
}
fun readImage(filePath: String): BufferedImage {
val url = ClassLoader.getSystemResource(filePath)
val file = File(url.toURI())
return ImageIO.read(file)
}
fun BufferedImage.toBuffer() = (raster.dataBuffer as DataBufferByte).data.toBuf()
fun BufferedImage.flipY(): BufferedImage {
var scanline1: Any? = null
var scanline2: Any? = null
for (i in 0 until height / 2) {
scanline1 = raster.getDataElements(0, i, width, 1, scanline1)
scanline2 = raster.getDataElements(0, height - i - 1, width, 1, scanline2)
raster.setDataElements(0, i, width, 1, scanline2)
raster.setDataElements(0, height - i - 1, width, 1, scanline1)
}
return this
}
fun loadTexture(path: String): Int {
val textureID = GL11.glGenTextures()
val texture = gli.load(path.uri)
gli.gl.profile = gl.Profile.GL33
val format = gli.gl.translate(texture.format, texture.swizzles)
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID)
for (i in 0 until texture.levels()) {
val extend = texture.extent(i)
glTexImage2D(i, format.internal, extend.x, extend.y, format.external, format.type, texture.data(0, 0, i))
}
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D)
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT)
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT)
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR)
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR)
texture.dispose()
return textureID
}
fun loadCubemap(path: String, extension: String): Int {
val textureID = GL11.glGenTextures()
GL11.glBindTexture(GL_TEXTURE_CUBE_MAP, textureID)
listOf("right", "left", "top", "bottom", "back", "front").forEachIndexed { i, it ->
//val texture = gli.load("$path/$it.$extension".uri)
val texture = loadImage(Paths.get("$path/$it.$extension".uri))
gli.gl.profile = gl.Profile.GL33
val format = gli.gl.translate(texture.format, texture.swizzles)
val extend = texture.extent()
GL11.glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format.internal.i,
extend.x, extend.y, 0, format.external.i, format.type.i, texture.data())
GL30.glGenerateMipmap(GL_TEXTURE_CUBE_MAP)
GL11.glTexParameteri(GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
GL11.glTexParameteri(GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
GL11.glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
GL11.glTexParameteri(GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR)
GL11.glTexParameteri(GL_TEXTURE_CUBE_MAP, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR)
texture.dispose()
}
return textureID
}
//TODO remove this shit, remove .flipY() on first line and remove it from gli and all the tests here
fun loadImage(path: Path): Texture {
val image = ImageIO.read(path.toFile())
val data = (image.raster.dataBuffer as DataBufferByte).data
val format = when (image.type) {
BufferedImage.TYPE_3BYTE_BGR -> { // switch blue and red
repeat(image.width * image.height) {
val tmp = data[it * 3] // save blue
data[it * 3] = data[it * 3 + 2] // write red
data[it * 3 + 2] = tmp // write blue
}
Format.RGB8_UNORM_PACK8
}
BufferedImage.TYPE_4BYTE_ABGR -> {
repeat(image.width * image.height) {
// switch alpha and red
var tmp = data[it * 4] // save alpha
data[it * 4] = data[it * 4 + 3] // write red
data[it * 4 + 3] = tmp // write alpha
// switch blue and green
tmp = data[it * 4 + 1] // save blue
data[it * 4 + 1] = data[it * 4 + 2] // write green
data[it * 4 + 2] = tmp // write blue
}
Format.RGBA8_UNORM_PACK8
}
else -> throw Error("not yet supported")
}
return Texture(Target._2D, format, Vec3i(image.width, image.height, 1), 1, 1, 1)
.apply { with(data()) { for (i in 0 until size) set(i, data[i]) } }
} | mit | b4c10bd2c5d5282cb82529f9c467f4eb | 33.860927 | 113 | 0.65134 | 3.318411 | false | false | false | false |
tasomaniac/OpenLinkWith | base/src/main/kotlin/com/tasomaniac/openwith/rx/SchedulingStrategy.kt | 1 | 1703 | package com.tasomaniac.openwith.rx
import io.reactivex.CompletableTransformer
import io.reactivex.FlowableTransformer
import io.reactivex.MaybeTransformer
import io.reactivex.ObservableTransformer
import io.reactivex.Scheduler
import io.reactivex.SingleTransformer
import io.reactivex.disposables.Disposable
class SchedulingStrategy(private val executor: Scheduler, private val notifier: Scheduler) {
fun <T> forObservable() = ObservableTransformer<T, T> { observable ->
observable
.subscribeOn(executor)
.observeOn(notifier)
}
fun <T> forFlowable() = FlowableTransformer<T, T> { flowable ->
flowable
.subscribeOn(executor)
.observeOn(notifier)
}
fun <T> forMaybe() = MaybeTransformer<T, T> { maybe ->
maybe
.subscribeOn(executor)
.observeOn(notifier)
}
fun forCompletable() = CompletableTransformer { completable ->
completable
.subscribeOn(executor)
.observeOn(notifier)
}
fun <T> forSingle() = SingleTransformer<T, T> { single ->
single
.subscribeOn(executor)
.observeOn(notifier)
}
fun runOnNotifier(runnable: Runnable): Disposable {
return runOnWorker(runnable, notifier.createWorker())
}
fun runOnExecutor(runnable: Runnable): Disposable {
return runOnWorker(runnable, executor.createWorker())
}
private fun runOnWorker(runnable: Runnable, worker: Scheduler.Worker): Disposable {
return worker.schedule {
try {
runnable.run()
} finally {
worker.dispose()
}
}
}
}
| apache-2.0 | a0397382b9583a1ac5d4a0e21fb6007e | 27.383333 | 92 | 0.636524 | 4.907781 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/commands/settings/AutoRoleCommand.kt | 1 | 2862 | package xyz.gnarbot.gnar.commands.settings
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Role
import xyz.gnarbot.gnar.commands.BotInfo
import xyz.gnarbot.gnar.commands.Category
import xyz.gnarbot.gnar.commands.Command
import xyz.gnarbot.gnar.commands.Context
import xyz.gnarbot.gnar.commands.template.CommandTemplate
import xyz.gnarbot.gnar.commands.template.annotations.Description
@Command(
aliases = ["autorole"],
usage = "(set|unset) [@role]",
description = "Set auto-roles that are assigned to users on joining."
)
@BotInfo(
id = 52,
category = Category.SETTINGS,
permissions = [Permission.MANAGE_ROLES]
)
class AutoRoleCommand : CommandTemplate() {
@Description("Set the auto-role.")
fun set(context: Context, role: Role) {
if (!context.selfMember.hasPermission(Permission.MANAGE_ROLES)) {
context.send().error("The bot can not manage auto-roles without the ${Permission.MANAGE_ROLES.getName()} permission.").queue()
return
}
if (role == context.guild.publicRole) {
context.send().error("You can't grant the public role!").queue()
return
}
if (!context.selfMember.canInteract(role)) {
context.send().error("That role is higher than my role! Fix by changing the role hierarchy.").queue()
return
}
if (role.id == context.data.roles.autoRole) {
context.send().error("${role.asMention} is already set as the auto-role.").queue()
return
}
context.data.roles.autoRole = role.id
context.data.save()
context.send().info("Users joining the guild will now be granted the role ${role.asMention}.").queue()
}
@Description("Unset the auto-role.")
fun reset(context: Context) {
if (context.data.roles.autoRole == null) {
context.send().error("This guild doesn't have an auto-role.").queue()
return
}
context.data.roles.autoRole = null
context.data.save()
context.send().info("Unset autorole. Users joining the guild will not be granted any role.").queue()
}
override fun onWalkFail(context: Context, args: Array<String>, depth: Int) {
onWalkFail(context, args, depth, null, buildString {
if (!context.selfMember.hasPermission(Permission.MANAGE_ROLES)) {
append("**WARNING:** Bot lacks the ${Permission.MANAGE_ROLES.getName()} permission.")
return
}
val role = context.data.roles.autoRole
append("Current auto-role: ")
if (role == null) {
append("__None__")
} else {
context.guild.getRoleById(role)?.asMention?.let { append(it) }
}
})
}
} | mit | ca0451c5d51186b5b314d442371b54af | 34.345679 | 138 | 0.6174 | 4.278027 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/xqt-platform-intellij-marklogic/main/xqt/platform/intellij/marklogic/MarkLogicXPathTokenProvider.kt | 1 | 10615 | // Copyright (C) 2022 Reece H. Dunn. SPDX-License-Identifier: Apache-2.0
package xqt.platform.intellij.marklogic
import xqt.platform.intellij.lexer.token.*
import xqt.platform.intellij.xpath.XPath
import xqt.platform.intellij.xpath.XPathTokenProvider
import xqt.platform.marklogic.v8.lexer.tokens.MarkLogic80XPathTokenProvider
/**
* The tokens present in the XPath grammar with MarkLogic vendor extensions.
*/
object MarkLogicXPathTokenProvider : MarkLogic80XPathTokenProvider {
// region XPath10TokenProvider
override val AbbrevAttribute: ISymbolTokenType get() = XPathTokenProvider.AbbrevAttribute
override val AbbrevDescendantOrSelf: ISymbolTokenType get() = XPathTokenProvider.AbbrevDescendantOrSelf
override val AbbrevParent: ISymbolTokenType get() = XPathTokenProvider.AbbrevParent
override val AxisSeparator: ISymbolTokenType get() = XPathTokenProvider.AxisSeparator
override val Colon: ISymbolTokenType get() = XPathTokenProvider.Colon
override val Comma: ISymbolTokenType get() = XPathTokenProvider.Comma
override val ContextItem: ISymbolTokenType get() = XPathTokenProvider.ContextItem
override val Equals: ISymbolTokenType get() = XPathTokenProvider.Equals
override val GreaterThan: ISymbolTokenType get() = XPathTokenProvider.GreaterThan
override val GreaterThanOrEquals: ISymbolTokenType get() = XPathTokenProvider.GreaterThanOrEquals
override val LessThan: ISymbolTokenType get() = XPathTokenProvider.LessThan
override val LessThanOrEquals: ISymbolTokenType get() = XPathTokenProvider.LessThanOrEquals
override val Minus: ISymbolTokenType get() = XPathTokenProvider.Minus
override val NotEquals: ISymbolTokenType get() = XPathTokenProvider.NotEquals
override val ParenthesisClose: ISymbolTokenType get() = XPathTokenProvider.ParenthesisClose
override val ParenthesisOpen: ISymbolTokenType get() = XPathTokenProvider.ParenthesisOpen
override val PathOperator: ISymbolTokenType get() = XPathTokenProvider.PathOperator
override val Plus: ISymbolTokenType get() = XPathTokenProvider.Plus
override val SquareBracketClose: ISymbolTokenType get() = XPathTokenProvider.SquareBracketClose
override val SquareBracketOpen: ISymbolTokenType get() = XPathTokenProvider.SquareBracketOpen
override val Star: ISymbolTokenType get() = XPathTokenProvider.Star
override val Union: ISymbolTokenType get() = XPathTokenProvider.Union
override val VariableIndicator: ISymbolTokenType get() = XPathTokenProvider.VariableIndicator
override val Literal: ITerminalSymbolTokenType get() = XPathTokenProvider.Literal
override val Number: ITerminalSymbolTokenType get() = XPathTokenProvider.Number
override val NCName: INCNameTokenType get() = XPathTokenProvider.NCName
override val PrefixedName: ITerminalSymbolTokenType get() = XPathTokenProvider.PrefixedName
override val S: IWrappedTerminalSymbolTokenType get() = XPathTokenProvider.S
override val KAncestor: IKeywordTokenType get() = XPathTokenProvider.KAncestor
override val KAncestorOrSelf: IKeywordTokenType get() = XPathTokenProvider.KAncestorOrSelf
override val KAnd: IKeywordTokenType get() = XPathTokenProvider.KAnd
override val KAttribute: IKeywordTokenType get() = XPathTokenProvider.KAttribute
override val KChild: IKeywordTokenType get() = XPathTokenProvider.KChild
override val KComment: IKeywordTokenType get() = XPathTokenProvider.KComment
override val KDescendant: IKeywordTokenType get() = XPathTokenProvider.KDescendant
override val KDescendantOrSelf: IKeywordTokenType get() = XPathTokenProvider.KDescendantOrSelf
override val KDiv: IKeywordTokenType get() = XPathTokenProvider.KDiv
override val KFollowing: IKeywordTokenType get() = XPathTokenProvider.KFollowing
override val KFollowingSibling: IKeywordTokenType get() = XPathTokenProvider.KFollowingSibling
override val KMod: IKeywordTokenType get() = XPathTokenProvider.KMod
override val KNamespace: IKeywordTokenType get() = XPathTokenProvider.KNamespace
override val KNode: IKeywordTokenType get() = XPathTokenProvider.KNode
override val KOr: IKeywordTokenType get() = XPathTokenProvider.KOr
override val KParent: IKeywordTokenType get() = XPathTokenProvider.KParent
override val KPreceding: IKeywordTokenType get() = XPathTokenProvider.KPreceding
override val KPrecedingSibling: IKeywordTokenType get() = XPathTokenProvider.KPrecedingSibling
override val KProcessingInstruction: IKeywordTokenType get() = XPathTokenProvider.KProcessingInstruction
override val KSelf: IKeywordTokenType get() = XPathTokenProvider.KSelf
override val KText: IKeywordTokenType get() = XPathTokenProvider.KText
// endregion
// region XPath20TokenProvider
override val EscapeApos: ISymbolTokenType get() = XPathTokenProvider.EscapeApos
override val EscapeQuot: ISymbolTokenType get() = XPathTokenProvider.EscapeQuot
override val NodePrecedes: ISymbolTokenType get() = XPathTokenProvider.NodePrecedes
override val NodeFollows: ISymbolTokenType get() = XPathTokenProvider.NodeFollows
override val QuestionMark: ISymbolTokenType get() = XPathTokenProvider.QuestionMark
override val StringLiteralApos: ISymbolTokenType get() = XPathTokenProvider.StringLiteralApos
override val StringLiteralQuot: ISymbolTokenType get() = XPathTokenProvider.StringLiteralQuot
override val IntegerLiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.IntegerLiteral
override val DecimalLiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.DecimalLiteral
override val DoubleLiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.DoubleLiteral
override val StringLiteralAposContents: ITerminalSymbolTokenType get() = XPathTokenProvider.StringLiteralAposContents
override val StringLiteralQuotContents: ITerminalSymbolTokenType get() = XPathTokenProvider.StringLiteralQuotContents
override val CommentOpen: ISymbolTokenType get() = XPathTokenProvider.CommentOpen
override val CommentContents: ITerminalSymbolTokenType get() = XPathTokenProvider.CommentContents
override val CommentClose: ISymbolTokenType get() = XPathTokenProvider.CommentClose
override val KAs: IKeywordTokenType get() = XPathTokenProvider.KAs
override val KCast: IKeywordTokenType get() = XPathTokenProvider.KCast
override val KCastable: IKeywordTokenType get() = XPathTokenProvider.KCastable
override val KDocumentNode: IKeywordTokenType get() = XPathTokenProvider.KDocumentNode
override val KElement: IKeywordTokenType get() = XPathTokenProvider.KElement
override val KElse: IKeywordTokenType get() = XPathTokenProvider.KElse
override val KEmptySequence: IKeywordTokenType get() = XPathTokenProvider.KEmptySequence
override val KEq: IKeywordTokenType get() = XPathTokenProvider.KEq
override val KEvery: IKeywordTokenType get() = XPathTokenProvider.KEvery
override val KExcept: IKeywordTokenType get() = XPathTokenProvider.KExcept
override val KFor: IKeywordTokenType get() = XPathTokenProvider.KFor
override val KGe: IKeywordTokenType get() = XPathTokenProvider.KGe
override val KGt: IKeywordTokenType get() = XPathTokenProvider.KGt
override val KIDiv: IKeywordTokenType get() = XPathTokenProvider.KIDiv
override val KIf: IKeywordTokenType get() = XPathTokenProvider.KIf
override val KIn: IKeywordTokenType get() = XPathTokenProvider.KIn
override val KInstance: IKeywordTokenType get() = XPathTokenProvider.KInstance
override val KIntersect: IKeywordTokenType get() = XPathTokenProvider.KIntersect
override val KIs: IKeywordTokenType get() = XPathTokenProvider.KIs
override val KItem: IKeywordTokenType get() = XPathTokenProvider.KItem
override val KLe: IKeywordTokenType get() = XPathTokenProvider.KLe
override val KLt: IKeywordTokenType get() = XPathTokenProvider.KLt
override val KNe: IKeywordTokenType get() = XPathTokenProvider.KNe
override val KOf: IKeywordTokenType get() = XPathTokenProvider.KOf
override val KReturn: IKeywordTokenType get() = XPathTokenProvider.KReturn
override val KSatisfies: IKeywordTokenType get() = XPathTokenProvider.KSatisfies
override val KSchemaAttribute: IKeywordTokenType get() = XPathTokenProvider.KSchemaAttribute
override val KSchemaElement: IKeywordTokenType get() = XPathTokenProvider.KSchemaElement
override val KSome: IKeywordTokenType get() = XPathTokenProvider.KSome
override val KThen: IKeywordTokenType get() = XPathTokenProvider.KThen
override val KTo: IKeywordTokenType get() = XPathTokenProvider.KTo
override val KTreat: IKeywordTokenType get() = XPathTokenProvider.KTreat
override val KUnion: IKeywordTokenType get() = XPathTokenProvider.KUnion
// endregion
// region MarkLogic60XPathTokenProvider
override val KBinary: IKeywordTokenType = IKeywordTokenType("binary", XPath)
override val KProperty: IKeywordTokenType = IKeywordTokenType("property", XPath)
// endregion
// region MarkLogic70XPathTokenProvider
override val KAttributeDecl: IKeywordTokenType = IKeywordTokenType("attribute-decl", XPath)
override val KComplexType: IKeywordTokenType = IKeywordTokenType("complex-type", XPath)
override val KElementDecl: IKeywordTokenType = IKeywordTokenType("element-decl", XPath)
override val KModelGroup: IKeywordTokenType = IKeywordTokenType("model-group", XPath)
override val KSchemaComponent: IKeywordTokenType = IKeywordTokenType("schema-component", XPath)
override val KSchemaParticle: IKeywordTokenType = IKeywordTokenType("schema-particle", XPath)
override val KSchemaRoot: IKeywordTokenType = IKeywordTokenType("schema-root", XPath)
override val KSchemaType: IKeywordTokenType = IKeywordTokenType("schema-type", XPath)
override val KSchemaWildcard: IKeywordTokenType = IKeywordTokenType("schema-wildcard", XPath)
override val KSimpleType: IKeywordTokenType = IKeywordTokenType("simple-type", XPath)
// endregion
// region MarkLogic80XPathTokenProvider
override val KArrayNode: IKeywordTokenType = IKeywordTokenType("array-node", XPath)
override val KBooleanNode: IKeywordTokenType = IKeywordTokenType("boolean-node", XPath)
override val KNullNode: IKeywordTokenType = IKeywordTokenType("null-node", XPath)
override val KNumberNode: IKeywordTokenType = IKeywordTokenType("number-node", XPath)
override val KObjectNode: IKeywordTokenType = IKeywordTokenType("object-node", XPath)
override val KSchemaFacet: IKeywordTokenType = IKeywordTokenType("schema-facet", XPath)
// endregion
}
| apache-2.0 | f813d267b15351940bb6d06056614f7a | 67.928571 | 121 | 0.804051 | 5.835624 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/ViewerConfig.kt | 1 | 2774 | package eu.kanade.tachiyomi.ui.reader.viewer
import eu.kanade.tachiyomi.core.preference.Preference
import eu.kanade.tachiyomi.data.preference.PreferenceValues.TappingInvertMode
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
/**
* Common configuration for all viewers.
*/
abstract class ViewerConfig(readerPreferences: ReaderPreferences, private val scope: CoroutineScope) {
var imagePropertyChangedListener: (() -> Unit)? = null
var navigationModeChangedListener: (() -> Unit)? = null
var tappingInverted = TappingInvertMode.NONE
var longTapEnabled = true
var usePageTransitions = false
var doubleTapAnimDuration = 500
var volumeKeysEnabled = false
var volumeKeysInverted = false
var trueColor = false
var alwaysShowChapterTransition = true
var navigationMode = 0
protected set
var forceNavigationOverlay = false
var navigationOverlayOnStart = false
var dualPageSplit = false
protected set
var dualPageInvert = false
protected set
abstract var navigator: ViewerNavigation
protected set
init {
readerPreferences.readWithLongTap()
.register({ longTapEnabled = it })
readerPreferences.pageTransitions()
.register({ usePageTransitions = it })
readerPreferences.doubleTapAnimSpeed()
.register({ doubleTapAnimDuration = it })
readerPreferences.readWithVolumeKeys()
.register({ volumeKeysEnabled = it })
readerPreferences.readWithVolumeKeysInverted()
.register({ volumeKeysInverted = it })
readerPreferences.trueColor()
.register({ trueColor = it }, { imagePropertyChangedListener?.invoke() })
readerPreferences.alwaysShowChapterTransition()
.register({ alwaysShowChapterTransition = it })
forceNavigationOverlay = readerPreferences.showNavigationOverlayNewUser().get()
if (forceNavigationOverlay) {
readerPreferences.showNavigationOverlayNewUser().set(false)
}
readerPreferences.showNavigationOverlayOnStart()
.register({ navigationOverlayOnStart = it })
}
protected abstract fun defaultNavigation(): ViewerNavigation
abstract fun updateNavigation(navigationMode: Int)
fun <T> Preference<T>.register(
valueAssignment: (T) -> Unit,
onChanged: (T) -> Unit = {},
) {
changes()
.onEach { valueAssignment(it) }
.distinctUntilChanged()
.onEach { onChanged(it) }
.launchIn(scope)
}
}
| apache-2.0 | 3b5f26043a99d39a553c566ca1f39f65 | 30.168539 | 102 | 0.692862 | 5.355212 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/PreferenceScaffold.kt | 1 | 1661 | package eu.kanade.presentation.more.settings
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import eu.kanade.presentation.components.Scaffold
import eu.kanade.tachiyomi.R
@Composable
fun PreferenceScaffold(
@StringRes titleRes: Int,
actions: @Composable RowScope.() -> Unit = {},
onBackPressed: (() -> Unit)? = null,
itemsProvider: @Composable () -> List<Preference>,
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = stringResource(id = titleRes)) },
navigationIcon = {
if (onBackPressed != null) {
IconButton(onClick = onBackPressed) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = stringResource(R.string.abc_action_bar_up_description),
)
}
}
},
actions = actions,
scrollBehavior = it,
)
},
content = { contentPadding ->
PreferenceScreen(
items = itemsProvider(),
contentPadding = contentPadding,
)
},
)
}
| apache-2.0 | c4d7d91cb8cf327aa5e6964a594adbb2 | 33.604167 | 108 | 0.58519 | 5.323718 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/vote/entry/EntryVoteButtonPresenter.kt | 1 | 1221 | package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.entry
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.base.BaseVoteButtonPresenter
import io.github.feelfreelinux.wykopmobilny.utils.rx.SubscriptionHelperApi
class EntryVoteButtonPresenter(private val subscriptionHandler : SubscriptionHelperApi, private val entriesApi : EntriesApi) : BasePresenter<EntryVoteButtonView>(), BaseVoteButtonPresenter {
var entryId = 0
override fun unvote() {
subscriptionHandler.subscribe(entriesApi.unvoteEntry(entryId),
{
view?.voteCount = it.vote
view?.isButtonSelected = false
}, { view?.showErrorDialog(it) }, this)
}
override fun vote() {
subscriptionHandler.subscribe(entriesApi.voteEntry(entryId),
{
view?.voteCount = it.vote
view?.isButtonSelected = true
}, { view?.showErrorDialog(it) }, this)
}
} | mit | d376cbef93a84e1329872f3dacccbc69 | 46 | 191 | 0.644554 | 5.308696 | false | false | false | false |
rinp/javaQuiz | src/main/kotlin/xxx/jq/entity/Category.kt | 1 | 642 | package xxx.jq.entity
import org.hibernate.annotations.DynamicUpdate
import org.hibernate.validator.constraints.NotBlank
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Version
/**
* @author rinp
* @since 2015/10/08
*/
@Entity
@DynamicUpdate
data class Category(
@javax.persistence.Id
@javax.persistence.GeneratedValue
override var id: Long? = null,
@Version
var version: Long = -1,
@field:NotBlank(message = "カテゴリー内容は必ず入力してください。")
@Column(unique = true)
var name: String = ""
) : BaseEntity | mit | 11a90fff3346564996b9a8d9ac37894f | 21.407407 | 56 | 0.692053 | 3.682927 | false | false | false | false |
square/wire | wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt | 1 | 58821 | /*
* Copyright 2019 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UsePropertyAccessSyntax")
package com.squareup.wire
import com.squareup.wire.MockRouteGuideService.Action.Delay
import com.squareup.wire.MockRouteGuideService.Action.ReceiveCall
import com.squareup.wire.MockRouteGuideService.Action.ReceiveComplete
import com.squareup.wire.MockRouteGuideService.Action.ReceiveError
import com.squareup.wire.MockRouteGuideService.Action.SendCompleted
import com.squareup.wire.MockRouteGuideService.Action.SendMessage
import io.grpc.Status
import io.grpc.StatusException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.Call
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Protocol.HTTP_2
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import okio.ByteString
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.Timeout
import routeguide.Feature
import routeguide.Point
import routeguide.Rectangle
import routeguide.RouteGuideClient
import routeguide.RouteGuideProto
import routeguide.RouteNote
import routeguide.RouteSummary
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import okhttp3.Protocol.H2_PRIOR_KNOWLEDGE
import okhttp3.Protocol.HTTP_1_1
import org.junit.Assert.assertThrows
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
class GrpcClientTest {
@JvmField @Rule val mockService = MockRouteGuideService()
@JvmField @Rule val timeout = Timeout(30, TimeUnit.SECONDS)
private lateinit var okhttpClient: OkHttpClient
private lateinit var grpcClient: GrpcClient
private lateinit var routeGuideService: RouteGuideClient
private lateinit var incompatibleRouteGuideService: IncompatibleRouteGuideClient
private var callReference = AtomicReference<Call>()
/** This is a pass through interceptor that tests can replace without extra plumbing. */
private var interceptor: Interceptor = object : Interceptor {
override fun intercept(chain: Chain) = chain.proceed(chain.request())
}
@Before
fun setUp() {
okhttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
callReference.set(chain.call())
interceptor.intercept(chain)
}
.protocols(listOf(H2_PRIOR_KNOWLEDGE))
.build()
grpcClient = GrpcClient.Builder()
.client(okhttpClient)
.baseUrl(mockService.url)
.build()
routeGuideService = grpcClient.create(RouteGuideClient::class)
incompatibleRouteGuideService = IncompatibleRouteGuideClient(grpcClient)
}
@After
fun tearDown() {
okhttpClient.dispatcher.executorService.shutdown()
}
@Test
fun grpcClientBuilderThrowsIfHttp2ProtocolMissing() {
val okHttpClient = OkHttpClient.Builder()
.protocols(listOf(HTTP_1_1))
.build()
val exception = assertThrows(IllegalArgumentException::class.java) {
GrpcClient.Builder().client(okHttpClient)
}
assertThat(exception.message)
.isEqualTo(
"OkHttpClient is not configured with a HTTP/2 protocol which is required for gRPC connections."
)
}
@Test
fun grpcClientBuilderDoesNotThrowIfHttp2ProtocolIsSet() {
val okHttpClient = OkHttpClient.Builder()
.protocols(listOf(HTTP_1_1, HTTP_2))
.build()
GrpcClient.Builder()
.client(okHttpClient)
.baseUrl("https://square.github.io/wire/")
.build()
}
@Test
fun grpcClientBuilderDoesNotThrowIfH2PriorKnowledgeProtocolIsSet() {
val okHttpClient = OkHttpClient.Builder()
.protocols(listOf(H2_PRIOR_KNOWLEDGE))
.build()
GrpcClient.Builder()
.client(okHttpClient)
.baseUrl("https://square.github.io/wire/")
.build()
}
@Suppress("ReplaceCallWithBinaryOperator") // We are explicitly testing this behavior.
@Test
fun objectMethodsStillWork() {
assertThat(routeGuideService.hashCode()).isNotZero()
assertThat(routeGuideService.equals(this)).isFalse()
assertThat(routeGuideService.toString()).isNotEmpty()
}
@Test
fun invalidBaseUrlThrows() {
val builder = GrpcClient.Builder()
try {
builder.baseUrl("mailto:bob@example.com")
fail()
} catch (_: IllegalArgumentException) {
}
}
@Test
fun requestResponseSuspend() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
runBlocking {
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.execute(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
}
@Test
fun requestResponseBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
@Test
fun requestResponseCallback() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
var feature: Feature? = null
val latch = CountDownLatch(1)
grpcCall.enqueue(
Point(latitude = 5, longitude = 6),
object : GrpcCall.Callback<Point, Feature> {
override fun onFailure(call: GrpcCall<Point, Feature>, exception: IOException) {
throw AssertionError()
}
override fun onSuccess(call: GrpcCall<Point, Feature>, response: Feature) {
feature = response
latch.countDown()
}
}
)
mockService.awaitSuccessBlocking()
latch.await()
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
@Test @Ignore
fun cancelRequestResponseSuspending() {
TODO()
}
@Test @Ignore
fun cancelRequestResponseBlocking() {
TODO()
}
@Test @Ignore
fun cancelRequestResponseCallback() {
TODO()
}
@Test
fun streamingRequestSuspend() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RecordRoute"))
mockService.enqueueReceivePoint(latitude = 3, longitude = 3)
mockService.enqueueReceivePoint(latitude = 9, longitude = 6)
mockService.enqueueSendSummary(pointCount = 2)
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RecordRoute().execute()
runBlocking {
requestChannel.send(Point(3, 3))
requestChannel.send(Point(9, 6))
requestChannel.close()
assertThat(responseChannel.receive()).isEqualTo(RouteSummary(point_count = 2))
}
}
@Test
fun streamingRequestBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RecordRoute"))
mockService.enqueueReceivePoint(latitude = 3, longitude = 3)
mockService.enqueueReceivePoint(latitude = 9, longitude = 6)
mockService.enqueueSendSummary(pointCount = 2)
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val (requestChannel, deferredResponse) = routeGuideService.RecordRoute().executeBlocking()
requestChannel.write(Point(3, 3))
requestChannel.write(Point(9, 6))
requestChannel.close()
assertThat(deferredResponse.read()).isEqualTo(RouteSummary(point_count = 2))
}
@Test
fun cancelStreamingRequestSuspend() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RecordRoute"))
val (_, responseChannel) = routeGuideService.RecordRoute().execute()
runBlocking {
// TODO(benoit) Fix it so we don't have to wait.
// We wait for the request to proceed.
delay(200)
responseChannel.cancel()
mockService.awaitSuccess()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
}
@Test
fun cancelStreamingRequestBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RecordRoute"))
val (_, responseDeferred) = routeGuideService.RecordRoute().executeBlocking()
// We wait for the request to proceed.
Thread.sleep(200)
responseDeferred.close()
mockService.awaitSuccessBlocking()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
@Test
fun streamingResponseSuspend() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/ListFeatures"))
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5))
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree")
mockService.enqueueSendFeature(name = "house")
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.ListFeatures().execute()
runBlocking {
requestChannel.send(Rectangle(lo = Point(0, 0), hi = Point(4, 5)))
requestChannel.close()
assertThat(responseChannel.receive()).isEqualTo(Feature(name = "tree"))
assertThat(responseChannel.receive()).isEqualTo(Feature(name = "house"))
assertThat(responseChannel.receiveCatching().getOrNull()).isNull()
}
}
@Test
fun streamingResponseBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/ListFeatures"))
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5))
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree")
mockService.enqueueSendFeature(name = "house")
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.ListFeatures().executeBlocking()
requestChannel.write(Rectangle(lo = Point(0, 0), hi = Point(4, 5)))
requestChannel.close()
assertThat(responseChannel.read()).isEqualTo(Feature(name = "tree"))
assertThat(responseChannel.read()).isEqualTo(Feature(name = "house"))
assertThat(responseChannel.read()).isNull()
}
@Test
fun cancelStreamingResponseSuspend() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/ListFeatures"))
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5))
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree")
mockService.enqueue(Delay(500, TimeUnit.MILLISECONDS))
mockService.enqueueSendFeature(name = "house")
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.ListFeatures().execute()
runBlocking {
requestChannel.send(Rectangle(lo = Point(0, 0), hi = Point(4, 5)))
requestChannel.close()
assertThat(responseChannel.receive()).isEqualTo(Feature(name = "tree"))
responseChannel.cancel()
mockService.awaitSuccess()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
}
@Test
fun cancelStreamingResponseBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/ListFeatures"))
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5))
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree")
mockService.enqueue(Delay(500, TimeUnit.MILLISECONDS))
mockService.enqueueSendFeature(name = "house")
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.ListFeatures().executeBlocking()
requestChannel.write(Rectangle(lo = Point(0, 0), hi = Point(4, 5)))
requestChannel.close()
assertThat(responseChannel.read()).isEqualTo(Feature(name = "tree"))
responseChannel.close()
mockService.awaitSuccessBlocking()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
@Test
fun duplexSuspend_receiveDataAfterClosingRequest() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
mockService.enqueue(ReceiveComplete)
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
requestChannel.send(RouteNote(message = "marco"))
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "polo"))
requestChannel.send(RouteNote(message = "rené"))
requestChannel.close()
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "lacoste"))
assertThat(responseChannel.receiveCatching().getOrNull()).isNull()
}
}
@Test
fun duplexSuspend_requestChannelThrowsWhenResponseChannelExhausted() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueue(SendCompleted)
runBlocking {
val (requestChannel, _) = routeGuideService.RouteChat().executeIn(this)
val latch = Mutex(locked = true)
requestChannel.invokeOnClose { expected ->
assertThat(expected).isInstanceOf(CancellationException::class.java)
latch.unlock()
}
requestChannel.send(RouteNote(message = "marco"))
latch.withLock {
// Wait for requestChannel to be closed.
}
try {
requestChannel.send(RouteNote(message = "léo"))
fail()
} catch (expected: Throwable) {
assertThat(expected).isInstanceOf(CancellationException::class.java)
}
}
}
@Test
fun duplexSuspend_requestChannelThrowsWhenWhenCanceledByServer() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendError(StatusException(Status.FAILED_PRECONDITION))
runBlocking {
val (requestChannel, _) = routeGuideService.RouteChat().executeIn(this)
val latch = Mutex(locked = true)
requestChannel.invokeOnClose { expected ->
assertThat(expected).isInstanceOf(CancellationException::class.java)
latch.unlock()
}
requestChannel.send(RouteNote(message = "marco"))
latch.withLock {
// Wait for requestChannel to be closed.
}
try {
requestChannel.send(RouteNote(message = "léo"))
fail()
} catch (expected: Throwable) {
assertThat(expected).isInstanceOf(CancellationException::class.java)
}
}
}
@Test
fun duplexSuspend_requestChannelThrowsWhenCallCanceledByClient() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "marco")
mockService.enqueueReceiveNote(message = "léo")
runBlocking {
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeIn(this)
val latch = Mutex(locked = true)
requestChannel.invokeOnClose { expected ->
assertThat(expected).isInstanceOf(CancellationException::class.java)
latch.unlock()
}
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "marco"))
requestChannel.send(RouteNote(message = "léo"))
callReference.get().cancel()
latch.withLock {
// Wait for requestChannel to be closed.
}
try {
requestChannel.send(RouteNote(message = "rené"))
fail()
} catch (expected: Throwable) {
assertThat(expected).isInstanceOf(CancellationException::class.java)
}
}
}
// Note that this test is asserting that we can actually catch the exception within our try/catch.
@Test
fun duplexSuspend_responseChannelThrowsWhenCanceledByServer() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "marco")
mockService.enqueueSendError(StatusException(Status.FAILED_PRECONDITION))
runBlocking {
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeIn(this)
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "marco"))
try {
responseChannel.receive()
fail()
} catch (expected: GrpcException) {
assertThat(expected.grpcStatus).isEqualTo(GrpcStatus.FAILED_PRECONDITION)
}
assertThat(responseChannel.isClosedForReceive).isTrue()
}
}
@Test
fun duplexSuspend_responseChannelThrowsWhenCallCanceledByClient() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "marco")
runBlocking {
val (_, responseChannel) = routeGuideService.RouteChat().executeIn(this)
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "marco"))
callReference.get().cancel()
try {
responseChannel.receive()
fail()
} catch (expected: IOException) {
assertThat(expected.message).startsWith("gRPC transport failure")
}
assertThat(responseChannel.isClosedForReceive).isTrue()
}
}
@Test
fun duplexBlocking_receiveDataAfterClosingRequest() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
mockService.enqueue(ReceiveComplete)
mockService.enqueue(SendCompleted)
val (requestSink, responseSource) = routeGuideService.RouteChat().executeBlocking()
requestSink.write(RouteNote(message = "marco"))
assertThat(responseSource.read()).isEqualTo(RouteNote(message = "polo"))
requestSink.write(RouteNote(message = "rené"))
requestSink.close()
assertThat(responseSource.read()).isEqualTo(RouteNote(message = "lacoste"))
assertThat(responseSource.read()).isNull()
}
@Test
fun duplexSuspend_receiveDataBeforeClosingRequest() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
// We give time to the sender to read the response.
mockService.enqueue(Delay(500, TimeUnit.MILLISECONDS))
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
requestChannel.send(RouteNote(message = "marco"))
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "polo"))
requestChannel.send(RouteNote(message = "rené"))
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "lacoste"))
assertThat(responseChannel.receiveCatching().getOrNull()).isNull()
requestChannel.close()
}
}
@Test
fun duplexBlocking_receiveDataBeforeClosingRequest() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
// We give time to the sender to read the response.
mockService.enqueue(Delay(500, TimeUnit.MILLISECONDS))
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeBlocking()
requestChannel.write(RouteNote(message = "marco"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "polo"))
requestChannel.write(RouteNote(message = "rené"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "lacoste"))
assertThat(responseChannel.read()).isNull()
requestChannel.close()
}
@Test
fun cancelDuplexSuspendBeforeRequestCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
// We wait for mockService to process our actions.
delay(500)
responseChannel.cancel()
assertThat((requestChannel as Channel).isClosedForReceive).isTrue()
assertThat(requestChannel.isClosedForSend).isTrue()
mockService.awaitSuccess()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
}
@Test
fun cancelDuplexSuspendAfterRequestCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
requestChannel.send(RouteNote(message = "marco"))
requestChannel.close()
// We wait for mockService to process our actions.
delay(500)
responseChannel.cancel()
assertThat((requestChannel as Channel).isClosedForReceive).isTrue()
assertThat(requestChannel.isClosedForSend).isTrue()
mockService.awaitSuccess()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
}
@Test
fun cancelDuplexSuspendBeforeResponseCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
requestChannel.send(RouteNote(message = "marco"))
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "polo"))
requestChannel.send(RouteNote(message = "rené"))
requestChannel.close()
// We wait for mockService to process our actions.
delay(500)
responseChannel.cancel()
assertThat((requestChannel as Channel).isClosedForReceive).isTrue()
assertThat(requestChannel.isClosedForSend).isTrue()
mockService.awaitSuccess()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
}
@Test
fun cancelDuplexSuspendAfterResponseCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
mockService.enqueue(ReceiveComplete)
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
requestChannel.send(RouteNote(message = "marco"))
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "polo"))
requestChannel.send(RouteNote(message = "rené"))
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "lacoste"))
requestChannel.close()
assertThat(responseChannel.receiveCatching().getOrNull()).isNull()
// We wait for mockService to process our actions.
delay(500)
responseChannel.cancel()
assertThat((requestChannel as Channel).isClosedForReceive).isTrue()
assertThat(requestChannel.isClosedForSend).isTrue()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
}
@Test fun cancelDuplexBlockingBeforeRequestCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
val (_, responseChannel) = routeGuideService.RouteChat().executeBlocking()
// We wait for mockService to process our actions.
Thread.sleep(500)
responseChannel.close()
mockService.awaitSuccessBlocking()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
@Test fun cancelDuplexBlockingAfterRequestCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeBlocking()
requestChannel.write(RouteNote(message = "marco"))
requestChannel.close()
// We wait for mockService to process our actions.
Thread.sleep(500)
responseChannel.close()
mockService.awaitSuccessBlocking()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
@Test fun cancelDuplexBlockingBeforeResponseCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeBlocking()
requestChannel.write(RouteNote(message = "marco"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "polo"))
requestChannel.write(RouteNote(message = "rené"))
requestChannel.close()
// We wait for mockService to process our actions.
Thread.sleep(500)
responseChannel.close()
mockService.awaitSuccessBlocking()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
@Test fun cancelDuplexBlockingAfterResponseCompletes() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueReceiveNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
mockService.enqueue(ReceiveComplete)
mockService.enqueue(SendCompleted)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeBlocking()
requestChannel.write(RouteNote(message = "marco"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "polo"))
requestChannel.write(RouteNote(message = "rené"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "lacoste"))
requestChannel.close()
assertThat(responseChannel.read()).isNull()
// We wait for mockService to process our actions.
Thread.sleep(500)
responseChannel.close()
assertThat(callReference.get()?.isCanceled()).isTrue()
}
@Test
fun duplexSuspendReceiveOnly() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "welcome")
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "welcome"))
requestChannel.close()
assertThat(responseChannel.receiveCatching().getOrNull()).isNull()
}
}
@Test
fun duplexBlockingReceiveOnly() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "welcome")
mockService.enqueueSendNote(message = "polo")
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().executeBlocking()
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "welcome"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "polo"))
requestChannel.close()
assertThat(responseChannel.read()).isNull()
}
/**
* This test is flaky. The root cause is OkHttp may send the cancel frame after the EOF frame,
* which is incorrect. https://github.com/square/okhttp/issues/5388
*/
@Test
fun cancelOutboundStream() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "welcome")
mockService.enqueue(ReceiveError)
val (requestChannel, responseChannel) = routeGuideService.RouteChat().execute()
runBlocking {
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "welcome"))
requestChannel.close(IOException("boom!"))
mockService.awaitSuccess()
}
}
@Test
fun grpcCallIsCanceledWhenItShouldBe() {
val grpcCall = routeGuideService.GetFeature()
assertThat(grpcCall.isCanceled()).isFalse()
grpcCall.cancel()
assertThat(grpcCall.isCanceled()).isTrue()
}
@Test
fun grpcStreamingCallIsCanceledWhenItShouldBe() {
val grpcStreamingCall = routeGuideService.RouteChat()
assertThat(grpcStreamingCall.isCanceled()).isFalse()
grpcStreamingCall.cancel()
assertThat(grpcStreamingCall.isCanceled()).isTrue()
}
@Test
fun grpcCallIsExecutedAfterExecute() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
runBlocking {
val grpcCall = routeGuideService.GetFeature()
assertThat(grpcCall.isExecuted()).isFalse()
val feature = grpcCall.execute(Point(latitude = 5, longitude = 6))
assertThat(grpcCall.isExecuted()).isTrue()
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
}
@Test
fun grpcCallIsExecutedAfterExecuteBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
assertThat(grpcCall.isExecuted()).isFalse()
val feature = grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(grpcCall.isExecuted()).isTrue()
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
@Test
fun grpcCallIsExecutedAfterEnqueue() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
assertThat(grpcCall.isExecuted()).isFalse()
var feature: Feature? = null
val latch = CountDownLatch(1)
grpcCall.enqueue(
Point(latitude = 5, longitude = 6),
object : GrpcCall.Callback<Point, Feature> {
override fun onFailure(call: GrpcCall<Point, Feature>, exception: IOException) {
throw AssertionError()
}
override fun onSuccess(call: GrpcCall<Point, Feature>, response: Feature) {
feature = response
latch.countDown()
}
}
)
assertThat(grpcCall.isExecuted()).isTrue()
mockService.awaitSuccessBlocking()
latch.await()
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
@Test
fun grpcStreamingCallIsExecutedAfterExecute() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "welcome")
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val grpcStreamingCall = routeGuideService.RouteChat()
assertThat(grpcStreamingCall.isExecuted()).isFalse()
val (requestChannel, responseChannel) = grpcStreamingCall.execute()
assertThat(grpcStreamingCall.isExecuted()).isTrue()
runBlocking {
assertThat(responseChannel.receive()).isEqualTo(RouteNote(message = "welcome"))
requestChannel.close()
assertThat(responseChannel.receiveCatching().getOrNull()).isNull()
}
}
@Test
fun grpcStreamingCallIsExecutedAfterExecuteBlocking() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueSendNote(message = "welcome")
mockService.enqueueSendNote(message = "polo")
mockService.enqueue(SendCompleted)
mockService.enqueue(ReceiveComplete)
val grpcStreamingCall = routeGuideService.RouteChat()
assertThat(grpcStreamingCall.isExecuted()).isFalse()
val (requestChannel, responseChannel) = grpcStreamingCall.executeBlocking()
assertThat(grpcStreamingCall.isExecuted()).isTrue()
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "welcome"))
assertThat(responseChannel.read()).isEqualTo(RouteNote(message = "polo"))
requestChannel.close()
assertThat(responseChannel.read()).isNull()
}
@Test
fun requestResponseSuspendServerOmitsGrpcStatus() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
interceptor = removeGrpcStatusInterceptor()
runBlocking {
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.execute(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)"
)
}
}
}
@Test
fun requestResponseBlockingServerOmitsGrpcStatus() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
interceptor = removeGrpcStatusInterceptor()
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)"
)
}
}
@Test
fun requestResponseCallbackServerOmitsGrpcStatus() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
interceptor = removeGrpcStatusInterceptor()
val grpcCall = routeGuideService.GetFeature()
val latch = CountDownLatch(1)
grpcCall.enqueue(
Point(latitude = 5, longitude = 6),
object : GrpcCall.Callback<Point, Feature> {
override fun onFailure(call: GrpcCall<Point, Feature>, exception: IOException) {
assertThat(exception).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)"
)
latch.countDown()
}
override fun onSuccess(call: GrpcCall<Point, Feature>, response: Feature) {
throw AssertionError()
}
}
)
mockService.awaitSuccessBlocking()
latch.await()
}
@Test
fun responseStatusIsNot200() {
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return Response.Builder()
.request(chain.request())
.protocol(HTTP_2)
.code(500)
.message("internal server error")
.body(ByteString.EMPTY.toResponseBody("application/grpc".toMediaType()))
.build()
}
}
runBlocking {
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.execute(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"expected gRPC but was HTTP status=500, content-type=application/grpc"
)
}
}
}
@Test
fun responseContentTypeIsNotGrpc() {
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return Response.Builder()
.request(chain.request())
.protocol(HTTP_2)
.code(200)
.message("ok")
.body(ByteString.EMPTY.toResponseBody("text/plain".toMediaType()))
.build()
}
}
runBlocking {
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.execute(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"expected gRPC but was HTTP status=200, content-type=text/plain"
)
}
}
}
/** Confirm the response content-type "application/grpc" is accepted. */
@Test
fun contentTypeApplicationGrpc() {
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
return response.newBuilder()
.body(object : ResponseBody() {
override fun contentLength() = response.body!!.contentLength()
override fun source() = response.body!!.source()
override fun contentType() = "application/grpc".toMediaType()
})
.build()
}
}
requestResponseBlocking()
}
/** Confirm the response content-type "application/grpc+proto" is accepted. */
@Test
fun contentTypeApplicationGrpcPlusProto() {
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
return response.newBuilder()
.body(object : ResponseBody() {
override fun contentLength() = response.body!!.contentLength()
override fun source() = response.body!!.source()
override fun contentType() = "application/grpc+proto".toMediaType()
})
.build()
}
}
requestResponseBlocking()
}
@Test
fun requestEarlyFailure() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendError(Exception("boom"))
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=2, grpc-message=null)"
)
assertThat(expected.cause).hasMessage("expected 1 message but got none")
}
}
@Test
fun requestEarlyFailureWithDescription() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendError(Status.INTERNAL.withDescription("boom").asRuntimeException())
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=13, grpc-message=boom)"
)
assertThat(expected.cause).hasMessage("expected 1 message but got none")
}
}
/** Return a value, then send an error. This relies on trailers being read. */
@Test
fun requestLateFailureWithDescription() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueueSendError(Status.INTERNAL.withDescription("boom").asRuntimeException())
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: GrpcException) {
assertThat(expected.grpcStatus).isEqualTo(GrpcStatus.INTERNAL)
assertThat(expected).hasMessage(
"grpc-status=13, grpc-status-name=INTERNAL, grpc-message=boom"
)
}
}
/** Violate the server's API contract, causing the stream to be canceled. */
@Test
fun serverCrashDueToTooManyResponses() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueueSendFeature(name = "tree at 7,8") // Invalid! Will cause a failure response.
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
try {
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)"
)
assertThat(expected.cause).hasMessage("stream was reset: CANCEL")
}
}
/** The server is streaming multiple responses, but the client expects 1 response. */
@Test
fun serverSendsTooManyResponseMessages() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueueSendNote(message = "polo")
mockService.enqueueSendNote(message = "rené")
mockService.enqueueSendNote(message = "lacoste")
mockService.enqueue(ReceiveComplete)
mockService.enqueue(SendCompleted)
val grpcCall = incompatibleRouteGuideService.RouteChat()
try {
grpcCall.executeBlocking(RouteNote(message = "marco"))
fail()
} catch (expected: IOException) {
// It's racy whether we receive trailers first or close the response stream first.
assertThat(expected.message).isIn(
"gRPC transport failure (HTTP status=200, grpc-status=0, grpc-message=null)",
"gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)"
)
assertThat(expected.cause).hasMessage("expected 1 message but got multiple")
}
}
/** The server is streaming zero responses, but the client expects 1 response. */
@Test
fun serverSendsTooFewResponseMessages() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/RouteChat"))
mockService.enqueueReceiveNote(message = "marco")
mockService.enqueue(ReceiveComplete)
mockService.enqueue(SendCompleted)
val grpcCall = incompatibleRouteGuideService.RouteChat()
try {
grpcCall.executeBlocking(RouteNote(message = "marco"))
fail()
} catch (expected: IOException) {
assertThat(expected).hasMessage(
"gRPC transport failure (HTTP status=200, grpc-status=0, grpc-message=null)"
)
assertThat(expected.cause).hasMessage("expected 1 message but got none")
}
}
@Test
fun grpcMethodTagIsPresent() {
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val grpcMethod = chain.request().tag(GrpcMethod::class.java)
assertThat(grpcMethod?.path).isEqualTo("/routeguide.RouteGuide/GetFeature")
return chain.proceed(chain.request())
}
}
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
}
@Test
fun messageLargerThanMinimumSizeIsCompressed() {
val requestBodyBuffer = Buffer()
interceptor = object : Interceptor {
override fun intercept(chain: Chain): Response {
assertThat(chain.request().header("grpc-encoding")).isEqualTo("gzip")
chain.request().body!!.writeTo(requestBodyBuffer)
return chain.proceed(chain.request())
}
}
grpcClient = grpcClient.newBuilder()
.minMessageToCompress(1L) // Smaller than Point(5, 6).
.build()
routeGuideService = grpcClient.create(RouteGuideClient::class)
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
assertThat(requestBodyBuffer.size).isEqualTo(29L) // 5-byte frame + 24-byte gzip data.
}
@Test
fun messageSmallerThanMinimumSizeIsNotCompressed() {
val requestBodyBuffer = Buffer()
interceptor = object : Interceptor {
override fun intercept(chain: Chain): Response {
// The grpc-encoding header is sent if gzip is enabled, independent of message size.
assertThat(chain.request().header("grpc-encoding")).isEqualTo("gzip")
chain.request().body!!.writeTo(requestBodyBuffer)
return chain.proceed(chain.request())
}
}
grpcClient = grpcClient.newBuilder()
.minMessageToCompress(10L) // Larger than Point(5, 6).
.build()
routeGuideService = grpcClient.create(RouteGuideClient::class)
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
assertThat(requestBodyBuffer.size).isEqualTo(9L) // 5-byte frame + 4-byte data.
}
@Test
fun maxMessageSizeToCompressDisablesCompression() {
val requestBodyBuffer = Buffer()
interceptor = object : Interceptor {
override fun intercept(chain: Chain): Response {
assertThat(chain.request().header("grpc-encoding")).isNull()
chain.request().body!!.writeTo(requestBodyBuffer)
return chain.proceed(chain.request())
}
}
grpcClient = grpcClient.newBuilder()
.minMessageToCompress(Long.MAX_VALUE)
.build()
routeGuideService = grpcClient.create(RouteGuideClient::class)
mockService.enqueue(ReceiveCall("/routeguide.RouteGuide/GetFeature"))
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueueSendFeature(name = "tree at 5,6")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
val feature = grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(feature).isEqualTo(Feature(name = "tree at 5,6"))
assertThat(requestBodyBuffer.size).isEqualTo(9L) // 5-byte frame + 4-byte body.
}
@Test
fun requestResponseMetadataOnSuccessfulCall() {
mockService.enqueue(
ReceiveCall(
path = "/routeguide.RouteGuide/GetFeature",
requestHeaders = mapOf("request-lucky-number" to "twenty-two"),
)
)
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueue(
SendMessage(
message = RouteGuideProto.Feature.newBuilder()
.setName("tree at 5,6")
.build(),
responseHeaders = mapOf("response-lucky-animal" to "horse")
)
)
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
grpcCall.requestMetadata = mapOf("request-lucky-number" to "twenty-two")
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(grpcCall.responseMetadata!!["response-lucky-animal"]).isEqualTo("horse")
mockService.awaitSuccessBlocking()
}
@Test
fun requestResponseMetadataOnSuccessfulClonedCall() {
// First call.
mockService.enqueue(
ReceiveCall(
path = "/routeguide.RouteGuide/GetFeature",
requestHeaders = mapOf("request-lucky-number" to "twenty-two"),
)
)
mockService.enqueueReceivePoint(latitude = 5, longitude = 6)
mockService.enqueue(ReceiveComplete)
mockService.enqueue(
SendMessage(
message = RouteGuideProto.Feature.newBuilder()
.setName("tree at 5,6")
.build(),
responseHeaders = mapOf("response-lucky-animal" to "horse")
)
)
mockService.enqueue(SendCompleted)
// Cloned call.
mockService.enqueue(
ReceiveCall(
path = "/routeguide.RouteGuide/GetFeature",
requestHeaders = mapOf("request-lucky-number" to "twenty-two", "all-in" to "true"),
)
)
mockService.enqueueReceivePoint(latitude = 15, longitude = 16)
mockService.enqueue(ReceiveComplete)
mockService.enqueue(
SendMessage(
message = RouteGuideProto.Feature.newBuilder()
.setName("tree at 15,16")
.build(),
responseHeaders = mapOf("response-lucky-animal" to "emu")
)
)
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.GetFeature()
val callMetadata = mutableMapOf("request-lucky-number" to "twenty-two")
grpcCall.requestMetadata = callMetadata
// First call.
grpcCall.executeBlocking(Point(latitude = 5, longitude = 6))
assertThat(grpcCall.responseMetadata!!["response-lucky-animal"]).isEqualTo("horse")
// Cloned call.
val clonedCall = grpcCall.clone()
// Modifying the original call's metadata should not affect the already cloned `clonedCall`.
callMetadata["request-lucky-number"] = "one"
clonedCall.requestMetadata += mapOf("all-in" to "true")
clonedCall.executeBlocking(Point(latitude = 15, longitude = 16))
assertThat(clonedCall.responseMetadata!!["response-lucky-animal"]).isEqualTo("emu")
mockService.awaitSuccessBlocking()
}
@Test
fun requestResponseMetadataOnSuccessfulStreamingCall() {
mockService.enqueue(
ReceiveCall(
path = "/routeguide.RouteGuide/ListFeatures",
requestHeaders = mapOf("request-lucky-number" to "twenty-two"),
)
)
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5))
mockService.enqueue(ReceiveComplete)
mockService.enqueue(
SendMessage(
message = RouteGuideProto.Feature.newBuilder()
.setName("tree")
.build(),
responseHeaders = mapOf("response-lucky-animal" to "horse")
)
)
mockService.enqueueSendFeature(name = "house")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.ListFeatures()
grpcCall.requestMetadata = mapOf("request-lucky-number" to "twenty-two")
val (requestChannel, responseChannel) = grpcCall.executeBlocking()
requestChannel.write(Rectangle(lo = Point(0, 0), hi = Point(4, 5)))
requestChannel.close()
assertThat(responseChannel.read()).isEqualTo(Feature(name = "tree"))
assertThat(responseChannel.read()).isEqualTo(Feature(name = "house"))
assertThat(responseChannel.read()).isNull()
assertThat(grpcCall.responseMetadata!!["response-lucky-animal"]).isEqualTo("horse")
}
@Test
fun requestResponseMetadataOnSuccessfulClonedStreamingCall() {
// First call.
mockService.enqueue(
ReceiveCall(
path = "/routeguide.RouteGuide/ListFeatures",
requestHeaders = mapOf("request-lucky-number" to "twenty-two"),
)
)
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5))
mockService.enqueue(ReceiveComplete)
mockService.enqueue(
SendMessage(
message = RouteGuideProto.Feature.newBuilder()
.setName("tree")
.build(),
responseHeaders = mapOf("response-lucky-animal" to "horse")
)
)
mockService.enqueueSendFeature(name = "house")
mockService.enqueue(SendCompleted)
// Clone call.
mockService.enqueue(
ReceiveCall(
path = "/routeguide.RouteGuide/ListFeatures",
requestHeaders = mapOf("request-lucky-number" to "twenty-two", "all-in" to "true"),
)
)
mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(14, 15))
mockService.enqueue(ReceiveComplete)
mockService.enqueue(
SendMessage(
message = RouteGuideProto.Feature.newBuilder()
.setName("forest")
.build(),
responseHeaders = mapOf("response-lucky-animal" to "emu")
)
)
mockService.enqueueSendFeature(name = "cabane")
mockService.enqueue(SendCompleted)
val grpcCall = routeGuideService.ListFeatures()
val callMetadata = mutableMapOf("request-lucky-number" to "twenty-two")
grpcCall.requestMetadata = callMetadata
// First call.
val (requestChannel, responseChannel) = grpcCall.executeBlocking()
requestChannel.write(Rectangle(lo = Point(0, 0), hi = Point(4, 5)))
requestChannel.close()
assertThat(responseChannel.read()).isEqualTo(Feature(name = "tree"))
assertThat(responseChannel.read()).isEqualTo(Feature(name = "house"))
assertThat(responseChannel.read()).isNull()
assertThat(grpcCall.responseMetadata!!["response-lucky-animal"]).isEqualTo("horse")
// Cloned call.
val clonedCall = grpcCall.clone()
// Modifying the original call's metadata should not affect the already cloned `clonedCall`.
callMetadata["request-lucky-number"] = "one"
clonedCall.requestMetadata += mapOf("all-in" to "true")
val (cloneRequestChannel, cloneResponseChannel) = clonedCall.executeBlocking()
cloneRequestChannel.write(Rectangle(lo = Point(0, 0), hi = Point(14, 15)))
cloneRequestChannel.close()
assertThat(cloneResponseChannel.read()).isEqualTo(Feature(name = "forest"))
assertThat(cloneResponseChannel.read()).isEqualTo(Feature(name = "cabane"))
assertThat(cloneResponseChannel.read()).isNull()
assertThat(clonedCall.responseMetadata!!["response-lucky-animal"]).isEqualTo("emu")
}
@Test
fun requestResponseCanceledInHttpCall() {
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
chain.call().cancel()
throw IOException("boom")
}
}
val grpcCall = routeGuideService.GetFeature()
runBlocking {
try {
grpcCall.execute(Point(latitude = 5, longitude = 6))
fail()
} catch (expected: Throwable) {
assertThat(expected).isInstanceOf(IOException::class.java)
assertThat(grpcCall.isCanceled()).isTrue()
}
}
}
@Test
fun requestResponseStreamingCanceledInHttpCall() {
interceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
chain.call().cancel()
throw IOException("boom")
}
}
val grpcCall = routeGuideService.RouteChat()
runBlocking {
val (_, receive) = grpcCall.executeIn(this@runBlocking)
try {
receive.receive()
fail()
} catch (expected: Throwable) {
assertThat(expected).isInstanceOf(IOException::class.java)
assertThat(grpcCall.isCanceled()).isTrue()
}
}
}
private fun removeGrpcStatusInterceptor(): Interceptor {
val noTrailersResponse = noTrailersResponse()
assertThat(noTrailersResponse.trailers().size).isEqualTo(0)
return object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
return noTrailersResponse.newBuilder()
.request(response.request)
.code(response.code)
.protocol(response.protocol)
.message(response.message)
.headers(response.headers)
.removeHeader("grpc-status")
.body(response.body)
.build()
}
}
}
/**
* OkHttp really tries to make it hard for us to strip out the trailers on a response. We
* accomplish it by taking a completely unrelated response and building upon it. This is ugly.
*
* https://github.com/square/okhttp/issues/5527
*/
private fun noTrailersResponse(): Response {
val request = Request.Builder()
.url(mockService.url)
.build()
val response = okhttpClient.newCall(request).execute()
response.use {
response.body!!.bytes()
}
return response
}
@ExperimentalCoroutinesApi
private fun MockRouteGuideService.awaitSuccessBlocking() {
runBlocking {
awaitSuccess()
}
}
class IncompatibleRouteGuideClient(
private val client: GrpcClient
) {
fun RouteChat(): GrpcCall<RouteNote, RouteNote> =
client.newCall(
GrpcMethod(
path = "/routeguide.RouteGuide/RouteChat",
requestAdapter = RouteNote.ADAPTER,
responseAdapter = RouteNote.ADAPTER
)
)
}
}
| apache-2.0 | d6ef0350f78955247643876ba9ad72e8 | 35.161747 | 103 | 0.710318 | 4.352258 | false | false | false | false |
sirixdb/sirix | bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/SirixDBUser.kt | 1 | 669 | package org.sirix.rest.crud
import io.vertx.ext.auth.User
import io.vertx.ext.auth.oauth2.KeycloakHelper
import io.vertx.ext.web.RoutingContext
import java.util.*
class SirixDBUser {
companion object {
fun create(ctx: RoutingContext): org.sirix.access.User {
val user = ctx.get("user") as User
val accessToken = KeycloakHelper.accessToken(user.principal())
val userId = accessToken.getString("sub")
val userName = accessToken.getString("preferred_username")
val userUuid = UUID.fromString(userId)
return org.sirix.access.User(userName, userUuid)
}
}
}
| bsd-3-clause | 00dc648797ad58b9d24c7a7420f9357e | 33.210526 | 74 | 0.650224 | 3.95858 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/account/AccountCreator.kt | 1 | 2899 | package com.fsck.k9.account
import android.content.res.Resources
import com.fsck.k9.Account.DeletePolicy
import com.fsck.k9.Preferences
import com.fsck.k9.mail.ConnectionSecurity
import com.fsck.k9.preferences.Protocols
import com.fsck.k9.ui.R
import com.fsck.k9.ui.helper.MaterialColors
/**
* Deals with logic surrounding account creation.
*
* TODO Move much of the code from com.fsck.k9.activity.setup.* into here
*/
class AccountCreator(private val preferences: Preferences, private val resources: Resources) {
fun getDefaultDeletePolicy(type: String): DeletePolicy {
return when (type) {
Protocols.IMAP -> DeletePolicy.ON_DELETE
Protocols.POP3 -> DeletePolicy.NEVER
Protocols.WEBDAV -> DeletePolicy.ON_DELETE
"demo" -> DeletePolicy.ON_DELETE
else -> throw AssertionError("Unhandled case: $type")
}
}
fun getDefaultPort(securityType: ConnectionSecurity, serverType: String): Int {
return when (serverType) {
Protocols.IMAP -> getImapDefaultPort(securityType)
Protocols.WEBDAV -> getWebDavDefaultPort(securityType)
Protocols.POP3 -> getPop3DefaultPort(securityType)
Protocols.SMTP -> getSmtpDefaultPort(securityType)
else -> throw AssertionError("Unhandled case: $serverType")
}
}
private fun getImapDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 993 else 143
}
private fun getPop3DefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 995 else 110
}
private fun getWebDavDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 443 else 80
}
private fun getSmtpDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 465 else 587
}
fun pickColor(): Int {
val accounts = preferences.accounts
val usedAccountColors = accounts.map { it.chipColor }
val accountColors = resources.getIntArray(R.array.account_colors).toList()
val availableColors = accountColors - usedAccountColors
if (availableColors.isEmpty()) {
return accountColors.random()
}
return availableColors.shuffled().minByOrNull { color ->
val index = DEFAULT_COLORS.indexOf(color)
if (index != -1) index else DEFAULT_COLORS.size
} ?: error("availableColors must not be empty")
}
companion object {
private val DEFAULT_COLORS = intArrayOf(
MaterialColors.BLUE_700,
MaterialColors.PINK_500,
MaterialColors.AMBER_600
)
}
}
| apache-2.0 | 6bb33e51e7b9fcee94e5450e0dfc60b6 | 36.649351 | 94 | 0.686789 | 4.55102 | false | false | false | false |
Maccimo/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/IdeaPluginDescriptorImpl.kt | 1 | 21485 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.ide.plugins
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import com.intellij.core.CoreBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.time.ZoneOffset
import java.util.*
private val LOG: Logger
get() = PluginManagerCore.getLogger()
fun Iterable<IdeaPluginDescriptor>.toPluginSet(): Set<PluginId> = mapTo(LinkedHashSet()) { it.pluginId }
fun Iterable<PluginId>.toPluginDescriptors(): List<IdeaPluginDescriptorImpl> = mapNotNull { PluginManagerCore.findPlugin(it) }
@ApiStatus.Internal
class IdeaPluginDescriptorImpl(raw: RawPluginDescriptor,
@JvmField val path: Path,
private val isBundled: Boolean,
id: PluginId?,
@JvmField val moduleName: String?,
@JvmField val useCoreClassLoader: Boolean = false) : IdeaPluginDescriptor {
private val id: PluginId = id ?: PluginId.getId(raw.id ?: raw.name ?: throw RuntimeException("Neither id nor name are specified"))
private val name = raw.name ?: id?.idString ?: raw.id
@Suppress("EnumEntryName")
enum class OS {
mac, linux, windows, unix, freebsd
}
// only for sub descriptors
@JvmField internal var descriptorPath: String? = null
@Volatile private var description: String? = null
private val productCode = raw.productCode
private var releaseDate: Date? = raw.releaseDate?.let { Date.from(it.atStartOfDay(ZoneOffset.UTC).toInstant()) }
private val releaseVersion = raw.releaseVersion
private val isLicenseOptional = raw.isLicenseOptional
@NonNls private var resourceBundleBaseName: String? = null
private val changeNotes = raw.changeNotes
private var version: String? = raw.version
private var vendor = raw.vendor
private val vendorEmail = raw.vendorEmail
private val vendorUrl = raw.vendorUrl
private var category: String? = raw.category
@JvmField internal val url = raw.url
@JvmField val pluginDependencies: List<PluginDependency>
@JvmField val incompatibilities: List<PluginId> = raw.incompatibilities ?: Collections.emptyList()
init {
// https://youtrack.jetbrains.com/issue/IDEA-206274
val list = raw.depends
if (list != null) {
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
if (!item.isOptional) {
for (a in list) {
if (a.isOptional && a.pluginId == item.pluginId) {
a.isOptional = false
iterator.remove()
break
}
}
}
}
}
pluginDependencies = list ?: Collections.emptyList()
}
companion object {
@ApiStatus.Internal
@JvmField var disableNonBundledPlugins = false
}
@Transient @JvmField var jarFiles: List<Path>? = null
private var _pluginClassLoader: ClassLoader? = null
@JvmField val actions: List<RawPluginDescriptor.ActionDescriptor> = raw.actions ?: Collections.emptyList()
// extension point name -> list of extension descriptors
val epNameToExtensions: Map<String, MutableList<ExtensionDescriptor>>? = raw.epNameToExtensions
@JvmField val appContainerDescriptor = raw.appContainerDescriptor
@JvmField val projectContainerDescriptor = raw.projectContainerDescriptor
@JvmField val moduleContainerDescriptor = raw.moduleContainerDescriptor
@JvmField val content: PluginContentDescriptor = raw.contentModules?.let { PluginContentDescriptor(it) } ?: PluginContentDescriptor.EMPTY
@JvmField val dependencies = raw.dependencies
@JvmField val modules: List<PluginId> = raw.modules ?: Collections.emptyList()
private val descriptionChildText = raw.description
@JvmField val isUseIdeaClassLoader = raw.isUseIdeaClassLoader
@JvmField val isBundledUpdateAllowed = raw.isBundledUpdateAllowed
@JvmField internal val implementationDetail = raw.implementationDetail
@JvmField internal val isRestartRequired = raw.isRestartRequired
@JvmField val packagePrefix = raw.`package`
private val sinceBuild = raw.sinceBuild
private val untilBuild = raw.untilBuild
private var isEnabled = true
var isDeleted = false
@JvmField internal var isIncomplete = false
override fun getDescriptorPath() = descriptorPath
override fun getDependencies(): List<IdeaPluginDependency> {
return if (pluginDependencies.isEmpty()) Collections.emptyList() else Collections.unmodifiableList(pluginDependencies)
}
override fun getPluginPath() = path
private fun createSub(raw: RawPluginDescriptor,
descriptorPath: String,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
dataLoader: DataLoader,
moduleName: String?): IdeaPluginDescriptorImpl {
raw.name = name
val result = IdeaPluginDescriptorImpl(raw, path = path, isBundled = isBundled, id = id, moduleName = moduleName,
useCoreClassLoader = useCoreClassLoader)
result.descriptorPath = descriptorPath
result.vendor = vendor
result.version = version
result.resourceBundleBaseName = resourceBundleBaseName
result.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = true, dataLoader = dataLoader)
return result
}
fun readExternal(raw: RawPluginDescriptor,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
isSub: Boolean,
dataLoader: DataLoader) {
// include module file descriptor if not specified as `depends` (old way - xi:include)
// must be first because merged into raw descriptor
if (!isSub) {
for (module in content.modules) {
val subDescriptorFile = module.configFile ?: "${module.name}.xml"
val subDescriptor = createSub(raw = pathResolver.resolveModuleFile(readContext = context,
dataLoader = dataLoader,
path = subDescriptorFile,
readInto = null),
descriptorPath = subDescriptorFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader,
moduleName = module.name)
module.descriptor = subDescriptor
}
}
if (raw.resourceBundleBaseName != null) {
if (id == PluginManagerCore.CORE_ID && !isSub) {
LOG.warn("<resource-bundle>${raw.resourceBundleBaseName}</resource-bundle> tag is found in an xml descriptor" +
" included into the platform part of the IDE but the platform part uses predefined bundles " +
"(e.g. ActionsBundle for actions) anyway; this tag must be replaced by a corresponding attribute in some inner tags " +
"(e.g. by 'resource-bundle' attribute in 'actions' tag)")
}
if (resourceBundleBaseName != null && resourceBundleBaseName != raw.resourceBundleBaseName) {
LOG.warn("Resource bundle redefinition for plugin $id. " +
"Old value: $resourceBundleBaseName, new value: ${raw.resourceBundleBaseName}")
}
resourceBundleBaseName = raw.resourceBundleBaseName
}
if (version == null) {
version = context.defaultVersion
}
if (!isSub) {
if (context.isPluginDisabled(id)) {
markAsIncomplete(context, disabledDependency = null, shortMessage = null)
}
else {
checkCompatibility(context)
if (isIncomplete) {
return
}
for (pluginDependency in dependencies.plugins) {
if (context.isPluginDisabled(pluginDependency.id)) {
markAsIncomplete(context, pluginDependency.id, shortMessage = "plugin.loading.error.short.depends.on.disabled.plugin")
}
else if (context.result.isBroken(pluginDependency.id)) {
markAsIncomplete(context = context,
disabledDependency = null,
shortMessage = "plugin.loading.error.short.depends.on.broken.plugin",
pluginId = pluginDependency.id)
}
}
}
}
if (!isIncomplete && moduleName == null) {
processOldDependencies(descriptor = this,
context = context,
pathResolver = pathResolver,
dependencies = pluginDependencies,
dataLoader = dataLoader)
}
}
private fun processOldDependencies(descriptor: IdeaPluginDescriptorImpl,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
dependencies: List<PluginDependency>,
dataLoader: DataLoader) {
var visitedFiles: MutableList<String>? = null
for (dependency in dependencies) {
// context.isPluginIncomplete must be not checked here as another version of plugin maybe supplied later from another source
if (context.isPluginDisabled(dependency.pluginId)) {
if (!dependency.isOptional && !isIncomplete) {
markAsIncomplete(context, dependency.pluginId, "plugin.loading.error.short.depends.on.disabled.plugin")
}
}
else if (context.result.isBroken(dependency.pluginId)) {
if (!dependency.isOptional && !isIncomplete) {
markAsIncomplete(context = context,
disabledDependency = null,
shortMessage = "plugin.loading.error.short.depends.on.broken.plugin",
pluginId = dependency.pluginId)
}
}
// because of https://youtrack.jetbrains.com/issue/IDEA-206274, configFile maybe not only for optional dependencies
val configFile = dependency.configFile ?: continue
if (pathResolver.isFlat && context.checkOptionalConfigShortName(configFile, descriptor)) {
continue
}
var resolveError: Exception? = null
val raw: RawPluginDescriptor? = try {
pathResolver.resolvePath(readContext = context, dataLoader = dataLoader, relativePath = configFile, readInto = null)
}
catch (e: IOException) {
resolveError = e
null
}
if (raw == null) {
val message = "Plugin $descriptor misses optional descriptor $configFile"
if (context.isMissingSubDescriptorIgnored) {
LOG.info(message)
if (resolveError != null) {
LOG.debug(resolveError)
}
}
else {
throw RuntimeException(message, resolveError)
}
continue
}
if (visitedFiles == null) {
visitedFiles = context.visitedFiles
}
checkCycle(descriptor, configFile, visitedFiles)
visitedFiles.add(configFile)
val subDescriptor = descriptor.createSub(raw = raw,
descriptorPath = configFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader,
moduleName = null)
dependency.subDescriptor = subDescriptor
visitedFiles.clear()
}
}
private fun checkCompatibility(context: DescriptorListLoadingContext) {
if (isBundled) {
return
}
fun markAsIncompatible(error: PluginLoadingError) {
if (isIncomplete) {
return
}
isIncomplete = true
isEnabled = false
context.result.addIncompletePlugin(plugin = this, error = error)
}
if (disableNonBundledPlugins) {
markAsIncompatible(PluginLoadingError(
plugin = this,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.custom.plugin.loading.disabled", getName()) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.custom.plugin.loading.disabled") },
isNotifyUser = false
))
return
}
PluginManagerCore.checkBuildNumberCompatibility(this, context.result.productBuildNumber.get())?.let {
markAsIncompatible(it)
return
}
// "Show broken plugins in Settings | Plugins so that users can uninstall them and resolve "Plugin Error" (IDEA-232675)"
if (context.result.isBroken(this)) {
markAsIncompatible(PluginLoadingError(
plugin = this,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.marked.as.broken", name, version) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.marked.as.broken") }
))
}
}
private fun markAsIncomplete(context: DescriptorListLoadingContext,
disabledDependency: PluginId?,
@PropertyKey(resourceBundle = CoreBundle.BUNDLE) shortMessage: String?,
pluginId: PluginId? = disabledDependency) {
if (isIncomplete) {
return
}
isIncomplete = true
isEnabled = false
val pluginError = if (shortMessage == null) {
null
}
else {
PluginLoadingError(plugin = this,
detailedMessageSupplier = null,
shortMessageSupplier = { CoreBundle.message(shortMessage, pluginId!!) },
isNotifyUser = false,
disabledDependency = disabledDependency)
}
context.result.addIncompletePlugin(this, pluginError)
}
@ApiStatus.Internal
fun registerExtensions(nameToPoint: Map<String, ExtensionPointImpl<*>>,
containerDescriptor: ContainerDescriptor,
listenerCallbacks: MutableList<in Runnable>?) {
containerDescriptor.extensions?.let {
if (!it.isEmpty()) {
@Suppress("JavaMapForEach")
it.forEach { name, list ->
nameToPoint.get(name)?.registerExtensions(list, this, listenerCallbacks)
}
}
return
}
val unsortedMap = epNameToExtensions ?: return
// app container: in most cases will be only app-level extensions - to reduce map copying, assume that all extensions are app-level and then filter out
// project container: rest of extensions wil be mostly project level
// module container: just use rest, area will not register unrelated extension anyway as no registered point
if (containerDescriptor == appContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
projectContainerDescriptor.extensions = Collections.emptyMap()
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else if (containerDescriptor == projectContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
containerDescriptor.extensions = unsortedMap
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
else if (registeredCount == (unsortedMap.size - appContainerDescriptor.distinctExtensionPointCount)) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
if (registeredCount == 0) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
}
private fun doRegisterExtensions(unsortedMap: Map<String, MutableList<ExtensionDescriptor>>,
nameToPoint: Map<String, ExtensionPointImpl<*>>,
listenerCallbacks: MutableList<in Runnable>?): Int {
var registeredCount = 0
for (entry in unsortedMap) {
val point = nameToPoint.get(entry.key) ?: continue
point.registerExtensions(entry.value, this, listenerCallbacks)
registeredCount++
}
return registeredCount
}
@Suppress("HardCodedStringLiteral")
override fun getDescription(): String? {
var result = description
if (result != null) {
return result
}
result = (resourceBundleBaseName?.let { baseName ->
try {
AbstractBundle.messageOrDefault(
DynamicBundle.getResourceBundle(classLoader, baseName),
"plugin.$id.description",
descriptionChildText ?: "",
)
}
catch (_: MissingResourceException) {
LOG.info("Cannot find plugin $id resource-bundle: $baseName")
null
}
}) ?: descriptionChildText
description = result
return result
}
override fun getChangeNotes() = changeNotes
override fun getName(): String = name!!
override fun getProductCode() = productCode
override fun getReleaseDate() = releaseDate
override fun getReleaseVersion() = releaseVersion
override fun isLicenseOptional() = isLicenseOptional
override fun getOptionalDependentPluginIds(): Array<PluginId> {
val pluginDependencies = pluginDependencies
return if (pluginDependencies.isEmpty())
PluginId.EMPTY_ARRAY
else
pluginDependencies.asSequence()
.filter { it.isOptional }
.map { it.pluginId }
.toList()
.toTypedArray()
}
override fun getVendor() = vendor
override fun getVersion() = version
override fun getResourceBundleBaseName() = resourceBundleBaseName
override fun getCategory() = category
/*
This setter was explicitly defined to be able to set a category for a
descriptor outside its loading from the xml file.
Problem was that most commonly plugin authors do not publish the plugin's
category in its .xml file so to be consistent in plugins representation
(e.g. in the Plugins form) we have to set this value outside.
*/
fun setCategory(category: String?) {
this.category = category
}
val unsortedEpNameToExtensionElements: Map<String, List<ExtensionDescriptor>>
get() {
return Collections.unmodifiableMap(epNameToExtensions ?: return Collections.emptyMap())
}
override fun getVendorEmail() = vendorEmail
override fun getVendorUrl() = vendorUrl
override fun getUrl() = url
override fun getPluginId() = id
override fun getPluginClassLoader(): ClassLoader? = _pluginClassLoader
@ApiStatus.Internal
fun setPluginClassLoader(classLoader: ClassLoader?) {
_pluginClassLoader = classLoader
}
override fun isEnabled() = isEnabled
override fun setEnabled(enabled: Boolean) {
isEnabled = enabled
}
override fun getSinceBuild() = sinceBuild
override fun getUntilBuild() = untilBuild
override fun isBundled() = isBundled
override fun allowBundledUpdate() = isBundledUpdateAllowed
override fun isImplementationDetail() = implementationDetail
override fun isRequireRestart() = isRestartRequired
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is IdeaPluginDescriptorImpl) {
return false
}
return id == other.id && descriptorPath == other.descriptorPath
}
override fun hashCode(): Int {
return 31 * id.hashCode() + (descriptorPath?.hashCode() ?: 0)
}
override fun toString(): String {
return "PluginDescriptor(" +
"name=$name, " +
"id=$id, " +
(if (moduleName == null) "" else "moduleName=$moduleName, ") +
"descriptorPath=${descriptorPath ?: "plugin.xml"}, " +
"path=${pluginPathToUserString(path)}, " +
"version=$version, " +
"package=$packagePrefix, " +
"isBundled=$isBundled" +
")"
}
}
// don't expose user home in error messages
internal fun pluginPathToUserString(file: Path): String {
return file.toString().replace("${System.getProperty("user.home")}${File.separatorChar}", "~${File.separatorChar}")
}
private fun checkCycle(descriptor: IdeaPluginDescriptorImpl, configFile: String, visitedFiles: List<String>) {
var i = 0
val n = visitedFiles.size
while (i < n) {
if (configFile == visitedFiles[i]) {
val cycle = visitedFiles.subList(i, visitedFiles.size)
throw RuntimeException("Plugin $descriptor optional descriptors form a cycle: ${java.lang.String.join(", ", cycle)}")
}
i++
}
} | apache-2.0 | d3122f848411949897b06d4d2a5a84b8 | 36.961131 | 155 | 0.64943 | 5.295785 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/refIndex/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerReferenceIndexService.kt | 1 | 21344 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.search.refIndex
import com.intellij.compiler.CompilerReferenceService
import com.intellij.compiler.backwardRefs.*
import com.intellij.compiler.backwardRefs.CompilerReferenceServiceBase.CompilerRefProvider
import com.intellij.compiler.server.BuildManager
import com.intellij.compiler.server.BuildManagerListener
import com.intellij.compiler.server.CustomBuilderMessageHandler
import com.intellij.compiler.server.PortableCachesLoadListener
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.ProjectScope
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.Processor
import com.intellij.util.containers.generateRecursiveSequence
import com.intellij.util.indexing.StorageException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.syntheticAccessors
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.config.SettingConstants
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerWorkspaceSettings
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.search.not
import org.jetbrains.kotlin.idea.search.restrictToKotlinSources
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.parameterIndex
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.io.IOException
import java.util.*
import java.util.concurrent.atomic.LongAdder
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
/**
* Based on [com.intellij.compiler.backwardRefs.CompilerReferenceServiceBase] and [com.intellij.compiler.backwardRefs.CompilerReferenceServiceImpl]
*/
class KotlinCompilerReferenceIndexService(private val project: Project) : Disposable, ModificationTracker {
private var initialized: Boolean = false
private var storage: KotlinCompilerReferenceIndexStorage? = null
private var activeBuildCount = 0
private val compilationCounter = LongAdder()
private val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex
private val supportedFileTypes: Set<FileType> = setOf(KotlinFileType.INSTANCE, JavaFileType.INSTANCE)
private val dirtyScopeHolder = DirtyScopeHolder(
project,
supportedFileTypes,
projectFileIndex,
this,
this,
) { connect, mutableSet ->
connect.subscribe(
CustomBuilderMessageHandler.TOPIC,
CustomBuilderMessageHandler { builderId, _, messageText ->
if (builderId == SettingConstants.KOTLIN_COMPILER_REFERENCE_INDEX_BUILDER_ID) {
mutableSet += messageText
}
},
)
}
private val lock = ReentrantReadWriteLock()
private fun <T> withWriteLock(action: () -> T): T = lock.write(action)
private fun <T> withReadLock(action: () -> T): T = lock.read(action)
private fun <T> tryWithReadLock(action: () -> T): T? {
return lock.readLock().run {
if (tryLock())
try {
action()
} finally {
unlock()
}
else
null
}
}
private fun withDirtyScopeUnderWriteLock(updater: DirtyScopeHolder.() -> Unit): Unit = withWriteLock { dirtyScopeHolder.updater() }
private fun <T> withDirtyScopeUnderReadLock(readAction: DirtyScopeHolder.() -> T): T = withReadLock { dirtyScopeHolder.readAction() }
init {
subscribeToEvents()
}
private fun subscribeToEvents() {
dirtyScopeHolder.installVFSListener(this)
val connection = project.messageBus.connect(this)
connection.subscribe(BuildManagerListener.TOPIC, object : BuildManagerListener {
override fun buildStarted(project: Project, sessionId: UUID, isAutomake: Boolean) {
if (project === this@KotlinCompilerReferenceIndexService.project) {
compilationStarted()
}
}
override fun buildFinished(project: Project, sessionId: UUID, isAutomake: Boolean) {
if (project === this@KotlinCompilerReferenceIndexService.project) {
executeOnBuildThread {
if (!runReadAction { this@KotlinCompilerReferenceIndexService.project.isDisposed }) {
compilationFinished()
}
}
}
}
})
if (isUnitTestMode()) return
connection.subscribe(PortableCachesLoadListener.TOPIC, object : PortableCachesLoadListener {
override fun loadingStarted() {
withWriteLock { closeStorage() }
}
})
}
class KCRIIsUpToDateConsumer : IsUpToDateCheckConsumer {
override fun isApplicable(project: Project): Boolean = isEnabled(project) && KotlinCompilerReferenceIndexStorage.hasIndex(project)
override fun isUpToDate(project: Project, isUpToDate: Boolean) {
if (!isUpToDate) return
val service = getInstanceIfEnabled(project) ?: return
executeOnBuildThread(service::markAsUpToDate)
}
}
private val projectIfNotDisposed: Project? get() = project.takeUnless(Project::isDisposed)
private fun compilationFinished() {
val compiledModules = runReadAction {
projectIfNotDisposed?.let {
val manager = ModuleManager.getInstance(it)
dirtyScopeHolder.compilationAffectedModules.mapNotNull(manager::findModuleByName)
}
}
val allModules = if (!initialized) allModules() else null
compilationCounter.increment()
withDirtyScopeUnderWriteLock {
--activeBuildCount
if (!initialized) {
initialize(allModules, compiledModules)
} else {
compilerActivityFinished(compiledModules)
}
if (activeBuildCount == 0) openStorage()
}
}
private fun DirtyScopeHolder.initialize(allModules: Array<Module>?, compiledModules: Collection<Module>?) {
initialized = true
LOG.info("initialized")
upToDateCheckFinished(allModules?.asList(), compiledModules)
}
private fun allModules(): Array<Module>? = runReadAction { projectIfNotDisposed?.let { ModuleManager.getInstance(it).modules } }
private fun markAsUpToDate() {
val modules = allModules() ?: return
withDirtyScopeUnderWriteLock {
val modificationCount = modificationCount
LOG.info("MC: $modificationCount, ABC: $activeBuildCount")
if (activeBuildCount == 0 && modificationCount == 1L) {
compilerActivityFinished(modules.asList())
LOG.info("marked as up to date")
}
}
}
private fun compilationStarted(): Unit = withDirtyScopeUnderWriteLock {
++activeBuildCount
compilerActivityStarted()
closeStorage()
}
private fun openStorage() {
if (storage != null) {
LOG.warn("already opened – will be overridden")
closeStorage()
}
storage = KotlinCompilerReferenceIndexStorage.open(project)
}
private fun closeStorage() {
KotlinCompilerReferenceIndexStorage.close(storage)
storage = null
}
private fun <T> runActionSafe(actionName: String, action: () -> T): T? = try {
action()
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
try {
LOG.error("an exception during $actionName calculation", e)
} finally {
if (e is IOException || e is StorageException) {
withWriteLock { closeStorage() }
}
}
null
}
fun scopeWithCodeReferences(element: PsiElement): GlobalSearchScope? {
if (!isServiceEnabledFor(element)) return null
return runActionSafe("scope with code references") {
CachedValuesManager.getCachedValue(element) {
CachedValueProvider.Result.create(
buildScopeWithReferences(referentFiles(element), element),
PsiModificationTracker.MODIFICATION_COUNT,
this,
)
}
}
}
fun directKotlinSubtypesOf(searchId: SearchId): Collection<FqNameWrapper>? {
val fqNameWrapper = FqNameWrapper.createFromSearchId(searchId) ?: return null
return tryWithReadLock { getDirectKotlinSubtypesOf(fqNameWrapper.fqName).toList() }
}
@TestOnly
fun getSubtypesOfInTests(fqName: FqName, deep: Boolean): Sequence<FqName>? = storage?.getSubtypesOf(fqName, deep)
@TestOnly
fun getSubtypesOfInTests(hierarchyElement: PsiElement, isFromLibrary: Boolean = false): Sequence<FqName> = getSubtypesOf(
hierarchyElement,
isFromLibrary,
)
@TestOnly
fun findReferenceFilesInTests(element: PsiElement): Set<VirtualFile>? = referentFiles(element)
private fun referentFiles(element: PsiElement): Set<VirtualFile>? = tryWithReadLock(fun(): Set<VirtualFile>? {
val storage = storage ?: return null
val originalElement = element.unwrapped ?: return null
val originalFqNames = extractFqNames(originalElement) ?: return null
val virtualFile = PsiUtilCore.getVirtualFile(element) ?: return null
if (projectFileIndex.isInSource(virtualFile) && virtualFile in dirtyScopeHolder) return null
val isFromLibrary = projectFileIndex.isInLibrary(virtualFile)
originalFqNames.takeIf { isFromLibrary }?.singleOrNull()?.asString()?.let { fqName ->
// "Any" is not in the subtypes storage
if (fqName.startsWith(CommonClassNames.JAVA_LANG_OBJECT) || fqName.startsWith("kotlin.Any")) {
return null
}
}
val additionalFqNames = findSubclassesFqNamesIfApplicable(originalElement, isFromLibrary)?.let { subclassesFqNames ->
subclassesFqNames.flatMap { subclass -> originalFqNames.map { subclass.child(it.shortName()) } }
}.orEmpty()
return originalFqNames.toSet().plus(additionalFqNames).flatMapTo(mutableSetOf(), storage::getUsages)
})
private fun findSubclassesFqNamesIfApplicable(element: PsiElement, isFromLibrary: Boolean): Sequence<FqName>? {
val hierarchyElement = when (element) {
is KtClassOrObject -> null
is PsiMember -> element.containingClass
is KtCallableDeclaration -> element.containingClassOrObject?.takeUnless { it is KtObjectDeclaration }
else -> null
} ?: return null
return getSubtypesOf(hierarchyElement, isFromLibrary)
}
private fun getSubtypesOf(hierarchyElement: PsiElement, isFromLibrary: Boolean): Sequence<FqName> =
generateRecursiveSequence(computeInitialElementsSequence(hierarchyElement, isFromLibrary)) { fqNameWrapper ->
val javaValues = getDirectJavaSubtypesOf(fqNameWrapper::asJavaCompilerClassRef)
val kotlinValues = getDirectKotlinSubtypesOf(fqNameWrapper.fqName)
kotlinValues + javaValues
}.map(FqNameWrapper::fqName)
private fun computeInitialElementsSequence(hierarchyElement: PsiElement, isFromLibrary: Boolean): Sequence<FqNameWrapper> {
val initialElements = if (isFromLibrary) {
computeInLibraryScope { findHierarchyInLibrary(hierarchyElement) }
} else {
setOf(hierarchyElement)
}
val kotlinInitialValues = initialElements.asSequence().mapNotNull(PsiElement::getKotlinFqName).flatMap { fqName ->
fqName.computeDirectSubtypes(
withSelf = isFromLibrary,
selfAction = FqNameWrapper.Companion::createFromFqName,
subtypesAction = this::getDirectKotlinSubtypesOf
)
}
val javaInitialValues = initialElements.asSequence().flatMap { currentHierarchyElement ->
currentHierarchyElement.computeDirectSubtypes(
withSelf = isFromLibrary,
selfAction = FqNameWrapper.Companion::createFromPsiElement,
subtypesAction = ::getDirectJavaSubtypesOf
)
}
return kotlinInitialValues + javaInitialValues
}
private fun <T> T.computeDirectSubtypes(
withSelf: Boolean,
selfAction: (T) -> FqNameWrapper?,
subtypesAction: (T) -> Sequence<FqNameWrapper>,
): Sequence<FqNameWrapper> {
val directSubtypes = subtypesAction(this)
return selfAction.takeIf { withSelf }?.invoke(this)?.let { sequenceOf(it) + directSubtypes } ?: directSubtypes
}
private fun getDirectKotlinSubtypesOf(fqName: FqName): Sequence<FqNameWrapper> = storage?.getSubtypesOf(fqName, deep = false)
?.map(FqNameWrapper.Companion::createFromFqName)
.orEmpty()
private fun getDirectJavaSubtypesOf(compilerRefProvider: CompilerRefProvider): Sequence<FqNameWrapper> {
return compilerReferenceServiceBase?.getDirectInheritorsNames(compilerRefProvider)
?.asSequence()
?.mapNotNull(FqNameWrapper.Companion::createFromSearchId)
.orEmpty()
}
private fun getDirectJavaSubtypesOf(hierarchyElement: PsiElement): Sequence<FqNameWrapper> =
LanguageCompilerRefAdapter.findAdapter(hierarchyElement, true)?.let { adapter ->
getDirectJavaSubtypesOf { adapter.asCompilerRef(hierarchyElement, it) }
}.orEmpty()
private val compilerReferenceServiceBase: CompilerReferenceServiceBase<*>?
get() = CompilerReferenceService.getInstanceIfEnabled(project)?.safeAs<CompilerReferenceServiceBase<*>>()
private val isInsideLibraryScopeThreadLocal = ThreadLocal.withInitial { false }
private fun isInsideLibraryScope(): Boolean =
compilerReferenceServiceBase?.isInsideLibraryScope
?: isInsideLibraryScopeThreadLocal.get()
private fun <T> computeInLibraryScope(action: () -> T): T =
compilerReferenceServiceBase?.computeInLibraryScope<T, Throwable>(action)
?: run {
isInsideLibraryScopeThreadLocal.set(true)
try {
action()
} finally {
isInsideLibraryScopeThreadLocal.set(false)
}
}
private fun findHierarchyInLibrary(hierarchyElement: PsiElement): Set<PsiElement> {
val overridden: MutableSet<PsiElement> = linkedSetOf(hierarchyElement)
val processor = Processor { clazz: PsiClass ->
clazz.takeUnless { it.hasModifierProperty(PsiModifier.PRIVATE) }?.let { overridden += clazz }
true
}
HierarchySearchRequest(
originalElement = hierarchyElement,
searchScope = ProjectScope.getLibrariesScope(project),
searchDeeply = true,
).searchInheritors().forEach(processor)
return overridden
}
private fun isServiceEnabledFor(element: PsiElement): Boolean {
return !isInsideLibraryScope() &&
storage != null &&
isEnabled(project) &&
runReadAction { element.containingFile }
?.let(InjectedLanguageManager.getInstance(project)::isInjectedFragment)
?.not() == true
}
private fun buildScopeWithReferences(virtualFiles: Set<VirtualFile>?, element: PsiElement): GlobalSearchScope? {
if (virtualFiles == null) return null
// knows everything
val referencesScope = GlobalSearchScope.filesWithoutLibrariesScope(project, virtualFiles)
/***
* can contain all languages, but depends on [supportedFileTypes]
* [com.intellij.compiler.backwardRefs.DirtyScopeHolder.getModuleForSourceContentFile]
*/
val knownDirtyScope = withDirtyScopeUnderReadLock { dirtyScope }
// [supportedFileTypes] without references + can contain references from other languages
val wholeClearScope = knownDirtyScope.not()
// [supportedFileTypes] without references
//val knownCleanScope = GlobalSearchScope.getScopeRestrictedByFileTypes(wholeClearScope, *supportedFileTypes.toTypedArray())
val knownCleanScope = wholeClearScope.restrictToKotlinSources()
// [supportedFileTypes] from dirty scope + other languages from the whole project
val wholeDirtyScope = knownCleanScope.not()
/*
* Example:
* module1 (dirty): 1.java, 2.kt, 3.groovy
* module2: 4.groovy
* module3: 5.java, 6.kt, 7.groovy
* -----
* [knownDirtyScope] contains m1[1, 2, 3]
* [wholeClearScope] contains m2[4], m3[5, 6, 7]
* [knownCleanScope] contains m3[6]
* [wholeDirtyScope] contains m1[1, 2, 3], m2[4], m3[5, 7]
*/
val mayContainReferencesScope = referencesScope.uniteWith(wholeDirtyScope)
return CompilerReferenceServiceBase.scopeWithLibraryIfNeeded(project, projectFileIndex, mayContainReferencesScope, element)
}
override fun dispose(): Unit = withWriteLock { closeStorage() }
override fun getModificationCount(): Long = compilationCounter.sum()
companion object {
operator fun get(project: Project): KotlinCompilerReferenceIndexService = project.service()
fun getInstanceIfEnabled(project: Project): KotlinCompilerReferenceIndexService? = if (isEnabled(project)) get(project) else null
fun isEnabled(project: Project): Boolean {
return AdvancedSettings.getBoolean("kotlin.compiler.ref.index") && KotlinCompilerWorkspaceSettings.getInstance(project).preciseIncrementalEnabled
}
private val LOG = logger<KotlinCompilerReferenceIndexService>()
}
}
private fun executeOnBuildThread(compilationFinished: () -> Unit): Unit =
if (isUnitTestMode()) {
compilationFinished()
} else {
BuildManager.getInstance().runCommand(compilationFinished)
}
private fun extractFqNames(element: PsiElement): List<FqName>? {
extractFqName(element)?.let { return listOf(it) }
return when (element) {
is PsiMethod -> extractFqNamesFromPsiMethod(element)
is KtParameter -> extractFqNamesFromParameter(element)
else -> null
}
}
private fun extractFqName(element: PsiElement): FqName? = when (element) {
is KtClassOrObject, is PsiClass -> element.getKotlinFqName()
is KtConstructor<*> -> element.getContainingClassOrObject().fqName
is KtNamedFunction -> element.fqName
is KtProperty -> element.fqName
is PsiField -> element.getKotlinFqName()
else -> null
}
private fun extractFqNamesFromParameter(parameter: KtParameter): List<FqName>? {
val parameterFqName = parameter.takeIf(KtParameter::hasValOrVar)?.fqName ?: return null
val componentFunctionName = parameter.asComponentFunctionName?.let { FqName(parameterFqName.parent().asString() + ".$it") }
return listOfNotNull(parameterFqName, componentFunctionName)
}
internal val KtParameter.asComponentFunctionName: String?
get() {
if (containingClassOrObject?.safeAs<KtClass>()?.isData() != true) return null
val parameterIndex = parameterIndex().takeUnless { it == -1 }?.plus(1) ?: return null
return "component$parameterIndex"
}
private fun extractFqNamesFromPsiMethod(psiMethod: PsiMethod): List<FqName>? {
if (psiMethod.isConstructor) return psiMethod.containingClass?.getKotlinFqName()?.let(::listOf)
val fqName = psiMethod.getKotlinFqName() ?: return null
val listOfFqName = listOf(fqName)
val propertyAssessors = psiMethod.syntheticAccessors.ifEmpty { return listOfFqName }
val parentFqName = fqName.parent()
return listOfFqName + propertyAssessors.map { parentFqName.child(it) }
}
| apache-2.0 | 8cbbbe691c098c174cfff43d86648298 | 41.769539 | 157 | 0.690657 | 5.1229 | false | false | false | false |
suntabu/MoonRover | src/main/kotlin/suntabu/moonrover/utils/vector3.kt | 1 | 522 | package suntabu.moonrover.utils
/**
* Created by gouzhun on 2017/2/13.
*/
class Vector3(val ix: Float = 0f, val iy: Float = 0f,val iz:Float = 0f) {
var x: Float = ix
var y: Float = iy
var z: Float = iz
constructor(ve:Vector2) : this() {
x = ve.x
y = 0f
z = ve.y
}
fun cross(other:Vector3):Vector3{
return Vector3(y*other.z-other.y * z,z * other.x -other.z * x,x * other.y -other.x * y)
}
fun toVector2():Vector2{
return Vector2(x,z)
}
} | apache-2.0 | 02ff71fdfea46bdfc8aa7a0130060191 | 17.678571 | 95 | 0.545977 | 2.690722 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/JumpsCommand.kt | 1 | 2149 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.helper.EngineStringHelper
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import kotlin.math.absoluteValue
/**
* see "h :jumps"
*/
data class JumpsCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_FORBIDDEN, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
val jumps = injector.markGroup.getJumps()
val spot = injector.markGroup.getJumpSpot()
val text = StringBuilder(" jump line col file/text\n")
jumps.forEachIndexed { idx, jump ->
val jumpSizeMinusSpot = jumps.size - idx - spot - 1
text.append(if (jumpSizeMinusSpot == 0) ">" else " ")
text.append(jumpSizeMinusSpot.absoluteValue.toString().padStart(3))
text.append(" ")
text.append((jump.line + 1).toString().padStart(5))
text.append(" ")
text.append(jump.col.toString().padStart(3))
text.append(" ")
val vf = editor.getVirtualFile()
if (vf != null && vf.path == jump.filepath) {
val line = editor.getLineText(jump.line).trim().take(200)
val keys = injector.parser.stringToKeys(line)
text.append(EngineStringHelper.toPrintableCharacters(keys).take(200))
} else {
text.append(jump.filepath)
}
text.append("\n")
}
if (spot == -1) {
text.append(">\n")
}
injector.exOutputPanel.getPanel(editor).output(text.toString())
return ExecutionResult.Success
}
}
| mit | c9a1f9b8dd42c64035640b9ed0aacc37 | 34.229508 | 132 | 0.707771 | 3.851254 | false | false | false | false |