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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt | 3 | 10101 | // Copyright 2000-2022 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.intentions
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.inspections.RedundantSamConstructorInspection
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.sam.JavaSingleAbstractMethodUtils
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
@Suppress("DEPRECATION")
class ObjectLiteralToLambdaInspection : IntentionBasedInspection<KtObjectLiteralExpression>(ObjectLiteralToLambdaIntention::class) {
override fun problemHighlightType(element: KtObjectLiteralExpression): ProblemHighlightType {
val (_, baseType, singleFunction) = extractData(element) ?: return super.problemHighlightType(element)
val bodyBlock = singleFunction.bodyBlockExpression
val lastStatement = bodyBlock?.statements?.lastOrNull()
if (bodyBlock?.anyDescendantOfType<KtReturnExpression> { it != lastStatement } == true) return ProblemHighlightType.INFORMATION
val valueArgument = element.parent as? KtValueArgument
val call = valueArgument?.getStrictParentOfType<KtCallExpression>()
if (call != null) {
val argumentMatch = call.resolveToCall()?.getArgumentMapping(valueArgument) as? ArgumentMatch
if (baseType.constructor != argumentMatch?.valueParameter?.type?.constructor) return ProblemHighlightType.INFORMATION
}
return super.problemHighlightType(element)
}
}
class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention<KtObjectLiteralExpression>(
KtObjectLiteralExpression::class.java,
KotlinBundle.lazyMessage("convert.to.lambda"),
KotlinBundle.lazyMessage("convert.object.literal.to.lambda")
) {
override fun applicabilityRange(element: KtObjectLiteralExpression): TextRange? {
val (baseTypeRef, baseType, singleFunction) = extractData(element) ?: return null
if (!JavaSingleAbstractMethodUtils.isSamType(baseType)) return null
val functionDescriptor = singleFunction.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return null
val overridden = functionDescriptor.overriddenDescriptors.singleOrNull() ?: return null
if (overridden.modality != Modality.ABSTRACT) return null
if (!singleFunction.hasBody()) return null
if (singleFunction.valueParameters.any { it.name == null }) return null
val bodyExpression = singleFunction.bodyExpression!!
val context = bodyExpression.analyze()
val containingDeclaration = functionDescriptor.containingDeclaration
// this-reference
if (bodyExpression.anyDescendantOfType<KtThisExpression> { thisReference ->
context[BindingContext.REFERENCE_TARGET, thisReference.instanceReference] == containingDeclaration
}
) return null
// Recursive call, skip labels
if (ReferencesSearch.search(singleFunction, LocalSearchScope(bodyExpression)).any { it.element !is KtLabelReferenceExpression }) {
return null
}
fun ReceiverValue?.isImplicitClassFor(descriptor: DeclarationDescriptor) =
this is ImplicitClassReceiver && classDescriptor == descriptor
if (bodyExpression.anyDescendantOfType<KtExpression> { expression ->
val resolvedCall = expression.getResolvedCall(context)
resolvedCall?.let {
it.dispatchReceiver.isImplicitClassFor(containingDeclaration) || it.extensionReceiver
.isImplicitClassFor(containingDeclaration)
} == true
}
) return null
return TextRange(element.objectDeclaration.getObjectKeyword()!!.startOffset, baseTypeRef.endOffset)
}
override fun applyTo(element: KtObjectLiteralExpression, editor: Editor?) {
val (_, baseType, singleFunction) = extractData(element)!!
val commentSaver = CommentSaver(element)
val returnSaver = ReturnSaver(singleFunction)
val body = singleFunction.bodyExpression!!
val factory = KtPsiFactory(element)
val newExpression = factory.buildExpression {
appendFixedText(IdeDescriptorRenderers.SOURCE_CODE.renderType(baseType))
appendFixedText("{")
val parameters = singleFunction.valueParameters
val needParameters =
parameters.count() > 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() }
if (needParameters) {
parameters.forEachIndexed { index, parameter ->
if (index > 0) {
appendFixedText(",")
}
appendName(parameter.nameAsSafeName)
}
appendFixedText("->")
}
val lastCommentOwner = if (singleFunction.hasBlockBody()) {
val contentRange = (body as KtBlockExpression).contentRange()
appendChildRange(contentRange)
contentRange.last
} else {
appendExpression(body)
body
}
if (lastCommentOwner?.anyDescendantOfType<PsiComment> { it.tokenType == KtTokens.EOL_COMMENT } == true) {
appendFixedText("\n")
}
appendFixedText("}")
}
val replaced = runWriteActionIfPhysical(element) { element.replaced(newExpression) }
val pointerToReplaced = replaced.createSmartPointer()
val callee = replaced.callee
val callExpression = callee.parent as KtCallExpression
val functionLiteral = callExpression.lambdaArguments.single().getLambdaExpression()!!
val returnLabel = callee.getReferencedNameAsName()
runWriteActionIfPhysical(element) {
returnSaver.restore(functionLiteral, returnLabel)
}
val parentCall = ((replaced.parent as? KtValueArgument)
?.parent as? KtValueArgumentList)
?.parent as? KtCallExpression
if (parentCall != null && RedundantSamConstructorInspection.samConstructorCallsToBeConverted(parentCall)
.singleOrNull() == callExpression
) {
runWriteActionIfPhysical(element) {
commentSaver.restore(replaced, forceAdjustIndent = true/* by some reason lambda body is sometimes not properly indented */)
}
RedundantSamConstructorInspection.replaceSamConstructorCall(callExpression)
if (parentCall.canMoveLambdaOutsideParentheses()) runWriteActionIfPhysical(element) {
parentCall.moveFunctionLiteralOutsideParentheses()
}
} else {
runWriteActionIfPhysical(element) {
commentSaver.restore(replaced, forceAdjustIndent = true/* by some reason lambda body is sometimes not properly indented */)
}
pointerToReplaced.element?.let { replacedByPointer ->
val endOffset = (replacedByPointer.callee.parent as? KtCallExpression)?.typeArgumentList?.endOffset
?: replacedByPointer.callee.endOffset
ShortenReferences.DEFAULT.process(replacedByPointer.containingKtFile, replacedByPointer.startOffset, endOffset)
}
}
}
private val KtExpression.callee
get() = getCalleeExpressionIfAny() as KtNameReferenceExpression
}
private data class Data(
val baseTypeRef: KtTypeReference,
val baseType: KotlinType,
val singleFunction: KtNamedFunction
)
private fun extractData(element: KtObjectLiteralExpression): Data? {
val objectDeclaration = element.objectDeclaration
val singleFunction = objectDeclaration.declarations.singleOrNull() as? KtNamedFunction ?: return null
if (!singleFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null
val delegationSpecifier = objectDeclaration.superTypeListEntries.singleOrNull() ?: return null
val typeRef = delegationSpecifier.typeReference ?: return null
val bindingContext = typeRef.analyze(BodyResolveMode.PARTIAL)
val baseType = bindingContext[BindingContext.TYPE, typeRef] ?: return null
return Data(typeRef, baseType, singleFunction)
} | apache-2.0 | 664202f2c3dbdded925bb140b9b9e790 | 47.567308 | 158 | 0.72478 | 5.633575 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MoveLambdaOutsideParenthesesInspection.kt | 2 | 2553 | // 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.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.core.canMoveLambdaOutsideParentheses
import org.jetbrains.kotlin.idea.core.getLastLambdaExpression
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.unpackFunctionLiteral
class MoveLambdaOutsideParenthesesInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(KtCallExpression::class.java) {
private fun KtCallExpression.withInformationLevel(): Boolean {
return when {
valueArguments.lastOrNull()?.isNamed() == true -> true
valueArguments.count { it.getArgumentExpression()?.unpackFunctionLiteral() != null } > 1 -> true
else -> false
}
}
private val KtCallExpression.verb: String
get() = if (withInformationLevel()) KotlinBundle.message("text.can") else KotlinBundle.message("text.should")
override fun inspectionHighlightType(element: KtCallExpression): ProblemHighlightType =
if (element.withInformationLevel()) ProblemHighlightType.INFORMATION else ProblemHighlightType.GENERIC_ERROR_OR_WARNING
override fun isApplicable(element: KtCallExpression) = element.canMoveLambdaOutsideParentheses()
override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
if (element.canMoveLambdaOutsideParentheses()) {
element.moveFunctionLiteralOutsideParentheses()
}
}
override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("lambda.argument.0.be.moved.out", element.verb)
override fun inspectionHighlightRangeInElement(element: KtCallExpression) = element.getLastLambdaExpression()
?.getStrictParentOfType<KtValueArgument>()?.asElement()
?.textRangeIn(element)
override val defaultFixText get() = KotlinBundle.message("move.lambda.argument.out.of.parentheses")
} | apache-2.0 | a213ab5b77e7ecc6cdec8a4a8d99a209 | 51.122449 | 133 | 0.788092 | 5.263918 | false | false | false | false |
satoshun/RxLifecycleOwner | rxlifecycleowner/src/main/java/com/github/satoshun/io/reactivex/lifecycleowner/core.kt | 1 | 1136 | package com.github.satoshun.io.reactivex.lifecycleowner
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
import io.reactivex.disposables.Disposable
@Suppress("NOTHING_TO_INLINE")
internal inline fun lifecycleBoundObserver(
lifecycle: Lifecycle,
targetEvent: Lifecycle.Event,
init: (LifecycleBoundObserver) -> Disposable
): Disposable {
val observer = LifecycleBoundObserver(targetEvent)
val disposable = init(observer)
observer.disposable = disposable
lifecycle.addObserver(observer)
return disposable
}
internal class LifecycleBoundObserver(
private val targetEvent: Lifecycle.Event
) : LifecycleObserver {
lateinit var disposable: Disposable
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onStateChange(owner: LifecycleOwner, event: Lifecycle.Event) {
if (targetEvent == event) {
disposable.dispose()
owner.lifecycle.removeObserver(this)
return
}
if (event == Lifecycle.Event.ON_DESTROY) {
owner.lifecycle.removeObserver(this)
}
}
}
| apache-2.0 | fdf79f5bed3d9c641eafbd11df042176 | 28.128205 | 68 | 0.775528 | 4.420233 | false | false | false | false |
ktorio/ktor | ktor-io/jvm/src/io/ktor/utils/io/ByteChannel.kt | 1 | 1133 | package io.ktor.utils.io
import java.nio.*
/**
* Creates channel for reading from the specified byte buffer.
*/
public fun ByteReadChannel(content: ByteBuffer): ByteReadChannel = ByteBufferChannel(content)
/**
* Creates buffered channel for asynchronous reading and writing of sequences of bytes.
*/
public actual fun ByteChannel(autoFlush: Boolean): ByteChannel = ByteBufferChannel(autoFlush = autoFlush)
/**
* Creates channel for reading from the specified byte array.
*/
public actual fun ByteReadChannel(content: ByteArray, offset: Int, length: Int): ByteReadChannel =
ByteBufferChannel(ByteBuffer.wrap(content, offset, length))
/**
* Creates buffered channel for asynchronous reading and writing of sequences of bytes using [close] function to close
* channel.
*/
public fun ByteChannel(autoFlush: Boolean = false, exceptionMapper: (Throwable?) -> Throwable?): ByteChannel =
object : ByteBufferChannel(autoFlush = autoFlush) {
override fun close(cause: Throwable?): Boolean {
val mappedException = exceptionMapper(cause)
return super.close(mappedException)
}
}
| apache-2.0 | a6553e93b256e07cbb12337a58887046 | 34.40625 | 118 | 0.738747 | 4.760504 | false | false | false | false |
marius-m/wt4 | app/src/test/java/lt/markmerkk/widgets/settings/OAuthAuthorizatorSetupAuth1Test.kt | 1 | 2929 | package lt.markmerkk.widgets.settings
import com.nhaarman.mockitokotlin2.*
import lt.markmerkk.JiraClientProvider
import lt.markmerkk.JiraOAuthCreds
import lt.markmerkk.JiraUser
import lt.markmerkk.UserSettings
import lt.markmerkk.interactors.JiraBasicApi
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import rx.Single
import rx.schedulers.Schedulers
import java.lang.RuntimeException
class OAuthAuthorizatorSetupAuth1Test {
@Mock lateinit var view: OAuthAuthorizator.View
@Mock lateinit var oauthInteractor: OAuthInteractor
@Mock lateinit var jiraClientProvider: JiraClientProvider
@Mock lateinit var jiraBasicApi: JiraBasicApi
@Mock lateinit var userSettings: UserSettings
lateinit var authorizator: OAuthAuthorizator
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
authorizator = OAuthAuthorizator(
view,
oauthInteractor,
jiraClientProvider,
jiraBasicApi,
userSettings,
Schedulers.immediate(),
Schedulers.immediate()
)
}
@Test
fun validAuthUrl() {
// Assemble
doReturn(Single.just("auth_url")).whenever(oauthInteractor).generateAuthUrl()
// Act
authorizator.setupAuthStep1()
// Assert
val viewModelCapture = argumentCaptor<AuthViewModel>()
verify(view).renderView(viewModelCapture.capture())
val viewModel = viewModelCapture.firstValue
assertThat(viewModel.showContainerWebview).isTrue()
assertThat(viewModel.showContainerStatus).isFalse()
assertThat(viewModel.showStatusEmoticon).isEqualTo(AuthViewModel.StatusEmoticon.NEUTRAL)
assertThat(viewModel.textStatus).isEqualTo("")
assertThat(viewModel.showButtonSetupNew).isFalse()
verify(userSettings).resetUserData()
verify(view).loadAuthWeb("auth_url")
}
@Test
fun errorExportingToken() {
// Assemble
doReturn(Single.error<Any>(RuntimeException())).whenever(oauthInteractor).generateAuthUrl()
// Act
authorizator.setupAuthStep1()
// Assert
val viewModelCapture = argumentCaptor<AuthViewModel>()
verify(view).renderView(viewModelCapture.capture())
val viewModel = viewModelCapture.firstValue
assertThat(viewModel.showContainerWebview).isFalse()
assertThat(viewModel.showContainerStatus).isTrue()
assertThat(viewModel.showStatusEmoticon).isEqualTo(AuthViewModel.StatusEmoticon.SAD)
assertThat(viewModel.textStatus).isEqualTo("Error generating JIRA token. Press 'Show logs' for more info!")
assertThat(viewModel.showButtonSetupNew).isTrue()
verify(view, never()).loadAuthWeb("auth_url")
}
} | apache-2.0 | a80f58de89b4343d94080eafcb4921d6 | 33.880952 | 115 | 0.71014 | 5.006838 | false | false | false | false |
seirion/code | leetcode/merge-k-sorted-lists/main.kt | 1 | 767 | // https://leetcode.com/problems/merge-k-sorted-lists
import java.util.*
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
val q = PriorityQueue<ListNode> { a, b -> a.`val` - b.`val` }
q.addAll(lists.filterNotNull())
val root = ListNode(0)
var current: ListNode? = root
while (q.isNotEmpty()) {
val top = q.poll()
current?.next = ListNode(top.`val`)
current = current?.next
top.next?.let {
q.add(it)
}
}
return root.next
}
}
| apache-2.0 | 55f2fecd3d598d8fbea73617f0deb7c3 | 22.96875 | 69 | 0.529335 | 3.584112 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/volumes/StackedVolumesExample.kt | 2 | 7008 | package graphics.scenery.tests.examples.volumes
import com.jogamp.opengl.math.FloatUtil.sin
import graphics.scenery.*
import graphics.scenery.attribute.material.Material
import graphics.scenery.backends.Renderer
import graphics.scenery.numerics.Random
import graphics.scenery.utils.RingBuffer
import graphics.scenery.utils.extensions.plus
import graphics.scenery.volumes.Colormap
import graphics.scenery.volumes.SlicingPlane
import graphics.scenery.volumes.TransferFunction
import graphics.scenery.volumes.Volume
import net.imglib2.type.numeric.integer.UnsignedByteType
import net.imglib2.type.numeric.integer.UnsignedShortType
import org.joml.Vector3f
import org.lwjgl.system.MemoryUtil.memAlloc
import org.scijava.ui.behaviour.ClickBehaviour
import java.io.Console
import java.nio.ByteBuffer
import kotlin.concurrent.thread
/**
* Stacking and slicing Volumes based on [ProceduralVolumeExample]
*/
class StackedVolumesExample : SceneryBase("Stacking Procedural Volume Rendering Example", 1280, 720) {
val bitsPerVoxel = 8
val volumeSize = 128L
override fun init() {
renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight))
val cam: Camera = DetachedHeadCamera()
with(cam) {
position = Vector3f(0.0f, 0.5f, 5.0f)
perspectiveCamera(50.0f, windowWidth, windowHeight)
scene.addChild(this)
}
val shell = Box(Vector3f(10.0f, 10.0f, 10.0f), insideNormals = true)
shell.material {
cullingMode = Material.CullingMode.None
diffuse = Vector3f(0.5f, 0.5f, 0.5f)
specular = Vector3f(0.0f)
ambient = Vector3f(0.0f)
}
shell.spatial {
position = Vector3f(0.0f, 0.0f, 0.0f)
}
scene.addChild(shell)
val volume = if (bitsPerVoxel == 8) {
Volume.fromBuffer(
emptyList(),
volumeSize.toInt(),
volumeSize.toInt(),
volumeSize.toInt(),
UnsignedByteType(),
hub
)
} else {
Volume.fromBuffer(
emptyList(),
volumeSize.toInt(),
volumeSize.toInt(),
volumeSize.toInt(),
UnsignedShortType(),
hub
)
}
val volumeSliced = if (bitsPerVoxel == 8) {
Volume.fromBuffer(
emptyList(),
volumeSize.toInt(),
volumeSize.toInt(),
volumeSize.toInt(),
UnsignedByteType(),
hub
)
} else {
Volume.fromBuffer(
emptyList(),
volumeSize.toInt(),
volumeSize.toInt(),
volumeSize.toInt(),
UnsignedShortType(),
hub
)
}
volume.name = "volume"
volume.spatial().position = Vector3f(0.0f, 0.0f, 0.0f)
volume.colormap = Colormap.get("hot")
volume.pixelToWorldRatio = 0.03f
volume.transferFunction = TransferFunction.ramp(0.6f, 0.9f)
volumeSliced.name = "volumeSliced"
volumeSliced.spatial().position = Vector3f(0.0f, 0.0f, 0.0f)
volumeSliced.colormap = Colormap.get("viridis")
volumeSliced.pixelToWorldRatio = 0.03f
with(volumeSliced.transferFunction) {
addControlPoint(0.0f, 0.0f)
addControlPoint(0.2f, 0.0f)
addControlPoint(0.4f, 0.5f)
addControlPoint(0.8f, 0.5f)
addControlPoint(1.0f, 0.0f)
}
volume.metadata["animating"] = true
volumeSliced.metadata["animating"] = true
scene.addChild(volume)
scene.addChild(volumeSliced)
val slicingPlane = SlicingPlane()
scene.addChild(slicingPlane)
slicingPlane.addTargetVolume(volumeSliced)
volumeSliced.slicingMode = Volume.SlicingMode.Slicing
val lights = (0 until 3).map {
PointLight(radius = 15.0f)
}
lights.mapIndexed { i, light ->
light.spatial().position = Vector3f(2.0f * i - 4.0f, i - 1.0f, 0.0f)
light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
light.intensity = 0.2f
scene.addChild(light)
}
thread {
val volumeBuffer =
RingBuffer<ByteBuffer>(2) { memAlloc((volumeSize * volumeSize * volumeSize * bitsPerVoxel / 8).toInt()) }
val seed = Random.randomFromRange(0.0f, 133333337.0f).toLong()
var shift = Vector3f(0.0f)
val shiftDelta = Random.random3DVectorFromRange(-1.5f, 1.5f)
var count = 0
while (running && !shouldClose) {
if (volume.metadata["animating"] == true) {
val currentBuffer = volumeBuffer.get()
Volume.generateProceduralVolume(
volumeSize, 0.35f, seed = seed,
intoBuffer = currentBuffer, shift = shift, use16bit = bitsPerVoxel > 8
)
volume.addTimepoint("t-${count}", currentBuffer)
volume.goToLastTimepoint()
volume.purgeFirst(10, 10)
volumeSliced.addTimepoint("t-${count}", currentBuffer)
volumeSliced.goToLastTimepoint()
volumeSliced.purgeFirst(10, 10)
shift += shiftDelta
count++
}
Thread.sleep(5L)
}
}
thread{
while (running && !shouldClose) {
val y = sin(((System.currentTimeMillis() % 20000) / 20000f) * Math.PI.toFloat() * 2) *2
//println(y)
slicingPlane.spatial {
position = Vector3f(0f, y, 0f)
updateWorld(true)
}
Thread.sleep(1L)
}
}
}
override fun inputSetup() {
setupCameraModeSwitching()
val toggleRenderingMode = object : ClickBehaviour {
var modes = Volume.RenderingMethod.values()
var currentMode = (scene.find("volume") as? Volume)?.renderingMethod?.ordinal ?: 0
override fun click(x: Int, y: Int) {
currentMode = (currentMode + 1) % modes.size
(scene.find("volume") as? Volume)?.renderingMethod = Volume.RenderingMethod.values().get(currentMode)
logger.info("Switched volume rendering mode to ${modes[currentMode]} (${(scene.find("volume") as? Volume)?.renderingMethod})")
}
}
inputHandler?.addBehaviour("toggle_rendering_mode", toggleRenderingMode)
inputHandler?.addKeyBinding("toggle_rendering_mode", "M")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
StackedVolumesExample().main()
}
}
}
| lgpl-3.0 | 7d6094538dacffa0b22d6999135671cd | 32.855072 | 142 | 0.565782 | 4.267966 | false | false | false | false |
google/android-fhir | datacapture/src/main/java/com/google/android/fhir/datacapture/QuestionnaireItemEditAdapter.kt | 1 | 11704 | /*
* Copyright 2022 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.google.android.fhir.datacapture
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.google.android.fhir.datacapture.contrib.views.QuestionnaireItemPhoneNumberViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemAutoCompleteViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemBooleanTypePickerViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemCheckBoxGroupViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemDatePickerViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemDateTimePickerViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemDialogSelectViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemDisplayViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemDropDownViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemEditTextDecimalViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemEditTextIntegerViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemEditTextMultiLineViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemEditTextQuantityViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemEditTextSingleLineViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemGroupViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemRadioGroupViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemSliderViewHolderFactory
import com.google.android.fhir.datacapture.views.QuestionnaireItemViewHolder
import com.google.android.fhir.datacapture.views.QuestionnaireItemViewItem
import org.hl7.fhir.r4.model.Questionnaire.QuestionnaireItemType
internal class QuestionnaireItemEditAdapter(
private val questionnaireItemViewHolderMatchers:
List<QuestionnaireFragment.QuestionnaireItemViewHolderFactoryMatcher> =
emptyList()
) : ListAdapter<QuestionnaireItemViewItem, QuestionnaireItemViewHolder>(DiffCallback) {
/**
* @param viewType the integer value of the [QuestionnaireItemViewHolderType] used to render the
* [QuestionnaireItemViewItem].
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuestionnaireItemViewHolder {
val numOfCanonicalWidgets = QuestionnaireItemViewHolderType.values().size
check(viewType < numOfCanonicalWidgets + questionnaireItemViewHolderMatchers.size) {
"Invalid widget type specified. Widget Int type cannot exceed the total number of supported custom and canonical widgets"
}
// Map custom widget viewTypes to their corresponding widget factories
if (viewType >= numOfCanonicalWidgets)
return questionnaireItemViewHolderMatchers[viewType - numOfCanonicalWidgets]
.factory.create(parent)
val viewHolderFactory =
when (QuestionnaireItemViewHolderType.fromInt(viewType)) {
QuestionnaireItemViewHolderType.GROUP -> QuestionnaireItemGroupViewHolderFactory
QuestionnaireItemViewHolderType.BOOLEAN_TYPE_PICKER ->
QuestionnaireItemBooleanTypePickerViewHolderFactory
QuestionnaireItemViewHolderType.DATE_PICKER -> QuestionnaireItemDatePickerViewHolderFactory
QuestionnaireItemViewHolderType.DATE_TIME_PICKER ->
QuestionnaireItemDateTimePickerViewHolderFactory
QuestionnaireItemViewHolderType.EDIT_TEXT_SINGLE_LINE ->
QuestionnaireItemEditTextSingleLineViewHolderFactory
QuestionnaireItemViewHolderType.EDIT_TEXT_MULTI_LINE ->
QuestionnaireItemEditTextMultiLineViewHolderFactory
QuestionnaireItemViewHolderType.EDIT_TEXT_INTEGER ->
QuestionnaireItemEditTextIntegerViewHolderFactory
QuestionnaireItemViewHolderType.EDIT_TEXT_DECIMAL ->
QuestionnaireItemEditTextDecimalViewHolderFactory
QuestionnaireItemViewHolderType.RADIO_GROUP -> QuestionnaireItemRadioGroupViewHolderFactory
QuestionnaireItemViewHolderType.DROP_DOWN -> QuestionnaireItemDropDownViewHolderFactory
QuestionnaireItemViewHolderType.DISPLAY -> QuestionnaireItemDisplayViewHolderFactory
QuestionnaireItemViewHolderType.QUANTITY ->
QuestionnaireItemEditTextQuantityViewHolderFactory
QuestionnaireItemViewHolderType.CHECK_BOX_GROUP ->
QuestionnaireItemCheckBoxGroupViewHolderFactory
QuestionnaireItemViewHolderType.AUTO_COMPLETE ->
QuestionnaireItemAutoCompleteViewHolderFactory
QuestionnaireItemViewHolderType.DIALOG_SELECT ->
QuestionnaireItemDialogSelectViewHolderFactory
QuestionnaireItemViewHolderType.SLIDER -> QuestionnaireItemSliderViewHolderFactory
QuestionnaireItemViewHolderType.PHONE_NUMBER ->
QuestionnaireItemPhoneNumberViewHolderFactory
}
return viewHolderFactory.create(parent)
}
override fun onBindViewHolder(holder: QuestionnaireItemViewHolder, position: Int) {
holder.bind(getItem(position))
}
/**
* Returns the integer value of the [QuestionnaireItemViewHolderType] that will be used to render
* the [QuestionnaireItemViewItem]. This is determined by a combination of the data type of the
* question and any additional Questionnaire Item UI Control Codes
* (http://hl7.org/fhir/R4/valueset-questionnaire-item-control.html) used in the itemControl
* extension (http://hl7.org/fhir/R4/extension-questionnaire-itemcontrol.html).
*/
override fun getItemViewType(position: Int): Int {
return getItemViewTypeMapping(getItem(position))
}
internal fun getItemViewTypeMapping(questionnaireItemViewItem: QuestionnaireItemViewItem): Int {
val questionnaireItem = questionnaireItemViewItem.questionnaireItem
// For custom widgets, generate an int value that's greater than any int assigned to the
// canonical FHIR widgets
questionnaireItemViewHolderMatchers.forEachIndexed { index, matcher ->
if (matcher.matches(questionnaireItem)) {
return index + QuestionnaireItemViewHolderType.values().size
}
}
if (questionnaireItemViewItem.answerOption.isNotEmpty()) {
return getChoiceViewHolderType(questionnaireItemViewItem).value
}
return when (val type = questionnaireItem.type) {
QuestionnaireItemType.GROUP -> QuestionnaireItemViewHolderType.GROUP
QuestionnaireItemType.BOOLEAN -> QuestionnaireItemViewHolderType.BOOLEAN_TYPE_PICKER
QuestionnaireItemType.DATE -> QuestionnaireItemViewHolderType.DATE_PICKER
QuestionnaireItemType.DATETIME -> QuestionnaireItemViewHolderType.DATE_TIME_PICKER
QuestionnaireItemType.STRING -> getStringViewHolderType(questionnaireItemViewItem)
QuestionnaireItemType.TEXT -> QuestionnaireItemViewHolderType.EDIT_TEXT_MULTI_LINE
QuestionnaireItemType.INTEGER -> getIntegerViewHolderType(questionnaireItemViewItem)
QuestionnaireItemType.DECIMAL -> QuestionnaireItemViewHolderType.EDIT_TEXT_DECIMAL
QuestionnaireItemType.CHOICE -> getChoiceViewHolderType(questionnaireItemViewItem)
QuestionnaireItemType.DISPLAY -> QuestionnaireItemViewHolderType.DISPLAY
QuestionnaireItemType.QUANTITY -> QuestionnaireItemViewHolderType.QUANTITY
QuestionnaireItemType.REFERENCE -> getChoiceViewHolderType(questionnaireItemViewItem)
else -> throw NotImplementedError("Question type $type not supported.")
}.value
}
private fun getChoiceViewHolderType(
questionnaireItemViewItem: QuestionnaireItemViewItem
): QuestionnaireItemViewHolderType {
val questionnaireItem = questionnaireItemViewItem.questionnaireItem
// Use the view type that the client wants if they specified an itemControl
return questionnaireItem.itemControl?.viewHolderType
// Otherwise, choose a sensible UI element automatically
?: run {
val numOptions = questionnaireItemViewItem.answerOption.size
when {
// Always use a dialog for questions with a large number of options
numOptions >= MINIMUM_NUMBER_OF_ANSWER_OPTIONS_FOR_DIALOG ->
QuestionnaireItemViewHolderType.DIALOG_SELECT
// Use a check box group if repeated answers are permitted
questionnaireItem.repeats -> QuestionnaireItemViewHolderType.CHECK_BOX_GROUP
// Use a dropdown if there are a medium number of options
numOptions >= MINIMUM_NUMBER_OF_ANSWER_OPTIONS_FOR_DROP_DOWN ->
QuestionnaireItemViewHolderType.DROP_DOWN
// Use a radio group only if there are a small number of options
else -> QuestionnaireItemViewHolderType.RADIO_GROUP
}
}
}
private fun getIntegerViewHolderType(
questionnaireItemViewItem: QuestionnaireItemViewItem
): QuestionnaireItemViewHolderType {
val questionnaireItem = questionnaireItemViewItem.questionnaireItem
// Use the view type that the client wants if they specified an itemControl
return questionnaireItem.itemControl?.viewHolderType
?: QuestionnaireItemViewHolderType.EDIT_TEXT_INTEGER
}
private fun getStringViewHolderType(
questionnaireItemViewItem: QuestionnaireItemViewItem
): QuestionnaireItemViewHolderType {
val questionnaireItem = questionnaireItemViewItem.questionnaireItem
// Use the view type that the client wants if they specified an itemControl
return questionnaireItem.itemControl?.viewHolderType
?: QuestionnaireItemViewHolderType.EDIT_TEXT_SINGLE_LINE
}
internal companion object {
// Choice questions are rendered as dialogs if they have at least this many options
const val MINIMUM_NUMBER_OF_ANSWER_OPTIONS_FOR_DIALOG = 10
// Choice questions are rendered as radio group if number of options less than this constant
const val MINIMUM_NUMBER_OF_ANSWER_OPTIONS_FOR_DROP_DOWN = 4
}
}
internal object DiffCallback : DiffUtil.ItemCallback<QuestionnaireItemViewItem>() {
/**
* [QuestionnaireItemViewItem] is a transient object for the UI only. Whenever the user makes any
* change via the UI, a new list of [QuestionnaireItemViewItem]s will be created, each holding
* references to the underlying [QuestionnaireItem] and [QuestionnaireResponseItem], both of which
* should be read-only, and the current answers. To help recycler view handle update and/or
* animations, we consider two [QuestionnaireItemViewItem]s to be the same if they have the same
* underlying [QuestionnaireItem] and [QuestionnaireResponseItem].
*/
override fun areItemsTheSame(
oldItem: QuestionnaireItemViewItem,
newItem: QuestionnaireItemViewItem
) = oldItem.hasTheSameItem(newItem)
override fun areContentsTheSame(
oldItem: QuestionnaireItemViewItem,
newItem: QuestionnaireItemViewItem
): Boolean {
return oldItem.hasTheSameItem(newItem) &&
oldItem.hasTheSameAnswer(newItem) &&
oldItem.hasTheSameValidationResult(newItem)
}
}
| apache-2.0 | 59bef9011dbc236531e5457257e21ad7 | 52.2 | 127 | 0.798189 | 5.670543 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/mostread/MostReadCardView.kt | 1 | 2211 | package org.wikipedia.feed.mostread
import android.content.Context
import org.wikipedia.feed.view.CardFooterView
import org.wikipedia.feed.view.ListCardItemView
import org.wikipedia.feed.view.ListCardRecyclerAdapter
import org.wikipedia.feed.view.ListCardView
import org.wikipedia.history.HistoryEntry
import org.wikipedia.views.DefaultViewHolder
class MostReadCardView(context: Context) : ListCardView<MostReadListCard>(context) {
override var card: MostReadListCard? = null
set(value) {
field = value
value?.let {
header(it)
footer(it)
set(RecyclerAdapter(it.items().subList(0, it.items().size.coerceAtMost(EVENTS_SHOWN))))
setLayoutDirectionByWikiSite(it.wikiSite(), layoutDirectionView)
}
}
private fun footer(card: MostReadListCard) {
footerView.visibility = VISIBLE
footerView.callback = getFooterCallback(card)
footerView.setFooterActionText(card.footerActionText(), card.wikiSite().languageCode())
}
private fun header(card: MostReadListCard) {
headerView.setTitle(card.title())
.setLangCode(card.wikiSite().languageCode())
.setCard(card)
.setCallback(callback)
}
fun getFooterCallback(card: MostReadListCard): CardFooterView.Callback {
return CardFooterView.Callback {
callback?.onFooterClick(card)
}
}
private inner class RecyclerAdapter constructor(items: List<MostReadItemCard>) :
ListCardRecyclerAdapter<MostReadItemCard>(items) {
override fun callback(): ListCardItemView.Callback? {
return callback
}
override fun onBindViewHolder(holder: DefaultViewHolder<ListCardItemView>, position: Int) {
val item = item(position)
holder.view.setCard(card).setHistoryEntry(HistoryEntry(item.pageTitle(), HistoryEntry.SOURCE_FEED_MOST_READ))
holder.view.setNumber(position + 1)
holder.view.setPageViews(item.pageViews)
holder.view.setGraphView(item.viewHistory)
}
}
companion object {
private const val EVENTS_SHOWN = 5
}
}
| apache-2.0 | 28b16a322aa4977c59b9e87b6e1ac8fa | 35.245902 | 121 | 0.674355 | 4.596674 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/metric/SeriesSetsSummarizer.kt | 1 | 2202 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.spotify.heroic.metric
import com.google.common.collect.HashMultimap
import com.google.common.collect.Multimap
import com.spotify.heroic.common.Histogram
import com.spotify.heroic.common.Series
data class SeriesSetsSummarizer @JvmOverloads constructor(
val uniqueKeys: HashSet<String> = hashSetOf(),
val tags: Multimap<String, String> = HashMultimap.create(),
val resource: Multimap<String, String> = HashMultimap.create(),
val seriesSize: Histogram.Builder = Histogram.Builder()
) {
fun add(series: Set<Series>) {
seriesSize.add(series.size.toLong())
series.forEach {s ->
uniqueKeys.add(s.key)
s.tags.forEach { tags.put(it.key, it.value) }
s.resource.forEach { resource.put(it.key, it.value) }
}
}
fun end(): Summary {
val tagsSize = Histogram.Builder()
val resourceSize = Histogram.Builder()
tags.asMap().forEach { tagsSize.add(it.value.size.toLong()) }
resource.asMap().forEach { resourceSize.add(it.value.size.toLong()) }
return Summary(uniqueKeys.size.toLong(), tagsSize.build(), resourceSize.build(),
seriesSize.build())
}
data class Summary(
val uniqueKeys: Long,
val tagsSize: Histogram,
val resourceSize: Histogram,
val seriesSize: Histogram
)
}
| apache-2.0 | c628846f9f67664e498fcf540007c5f5 | 35.098361 | 88 | 0.69346 | 4.077778 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/projectView/projectViewProviders.kt | 3 | 3948 | // 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.projectView
import com.intellij.ide.projectView.SelectableTreeStructureProvider
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.idea.KotlinIconProvider
import org.jetbrains.kotlin.psi.KtClassBody
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
class KotlinExpandNodeProjectViewProvider : TreeStructureProvider, DumbAware {
// should be called after ClassesTreeStructureProvider
override fun modify(
parent: AbstractTreeNode<*>,
children: Collection<AbstractTreeNode<*>>,
settings: ViewSettings
): Collection<AbstractTreeNode<out Any>> {
val result = ArrayList<AbstractTreeNode<out Any>>()
for (child in children) {
val childValue = child.value?.asKtFile()
if (childValue != null) {
val mainClass = KotlinIconProvider.getSingleClass(childValue)
if (mainClass != null) {
result.add(KtClassOrObjectTreeNode(childValue.project, mainClass, settings))
} else {
result.add(KtFileTreeNode(childValue.project, childValue, settings))
}
} else {
result.add(child)
}
}
return result
}
private fun Any.asKtFile(): KtFile? = when (this) {
is KtFile -> this
is KtLightClassForFacade -> files.singleOrNull()
is KtLightClass -> kotlinOrigin?.containingFile as? KtFile
else -> null
}
}
class KotlinSelectInProjectViewProvider(private val project: Project) : SelectableTreeStructureProvider, DumbAware {
override fun modify(
parent: AbstractTreeNode<*>,
children: Collection<AbstractTreeNode<*>>,
settings: ViewSettings
): Collection<AbstractTreeNode<out Any>> {
return ArrayList(children)
}
// should be called before ClassesTreeStructureProvider
override fun getTopLevelElement(element: PsiElement): PsiElement? {
if (!element.isValid) return null
val file = element.containingFile as? KtFile ?: return null
val virtualFile = file.virtualFile
if (!fileInRoots(virtualFile)) return file
var current = element.parentsWithSelf.firstOrNull() { it.isSelectable() }
if (current is KtFile) {
val declaration = current.declarations.singleOrNull()
val nameWithoutExtension = virtualFile?.nameWithoutExtension ?: file.name
if (declaration is KtClassOrObject && nameWithoutExtension == declaration.name) {
current = declaration
}
}
return current ?: file
}
private fun PsiElement.isSelectable(): Boolean = when (this) {
is KtFile -> true
is KtDeclaration -> parent is KtFile || ((parent as? KtClassBody)?.parent as? KtClassOrObject)?.isSelectable() ?: false
else -> false
}
private fun fileInRoots(file: VirtualFile?): Boolean {
val index = ProjectRootManager.getInstance(project).fileIndex
return file != null && (index.isInSourceContent(file) || index.isInLibraryClasses(file) || index.isInLibrarySource(file))
}
}
| apache-2.0 | 564c93a307bb98814b8bfcefc19a24da | 37.330097 | 158 | 0.696049 | 5.127273 | false | false | false | false |
psanders/sipio | src/main/kotlin/io/routr/core/GRPCServer.kt | 1 | 2756 | package io.routr.core
import io.grpc.Server
import io.grpc.ServerBuilder
import io.grpc.stub.StreamObserver
import io.routr.core.ControllerGrpc.ControllerImplBase
import java.io.IOException
import java.util.*
import kotlin.system.exitProcess
import org.apache.logging.log4j.LogManager
import org.graalvm.polyglot.Context
/**
* @author Pedro Sanders
* @since v1
*/
class GRPCServer(private val context: Context) {
private var server: Server? = null
fun start() {
// TODO: Get this from config file :(
val port = 50099
try {
server = ServerBuilder.forPort(port).addService(ControllerImpl(context)).build().start()
LOG.debug("Starting gRPC service, listening on $port")
Runtime.getRuntime()
.addShutdownHook(
object : Thread() {
override fun run() {
LOG.debug("Shutting down gRPC service")
[email protected]()
}
}
)
} catch (ex: IOException) {
LOG.fatal("Unable to start grpcService: " + ex.message)
exitProcess(status = 1)
}
}
fun stop() {
if (server != null) {
server!!.shutdown()
}
}
@Throws(InterruptedException::class)
fun blockUntilShutdown() {
if (server != null) {
server!!.awaitTermination()
}
}
internal class ControllerImpl(private val context: Context) : ControllerImplBase() {
override fun runCommand(req: CommandRequest, responseObserver: StreamObserver<CommandReply>) {
val reply = CommandReply.newBuilder().setMessage(req.name).build()
val context = context
when (req.name) {
"stop-server" -> {
val timer = Timer()
timer.schedule(
object : TimerTask() {
override fun run() {
context.eval("js", "server.stopIfReady()")
}
},
1000,
10 * 1000.toLong()
)
}
"restart-server" -> {
val timer = Timer()
timer.schedule(
object : TimerTask() {
override fun run() {
context.eval("js", "server.stopIfReady(123)")
}
},
1000,
10 * 1000.toLong()
)
}
"stop-server-now" -> {
context.eval("js", "server.stop()")
}
"restart-server-now" -> {
context.eval("js", "server.stop(123)")
}
"evict-all" -> {
context.eval("js", "server.locator.evictAll()")
}
}
responseObserver.onNext(reply)
responseObserver.onCompleted()
}
}
companion object {
private val LOG = LogManager.getLogger(GRPCServer::class.java)
}
}
| mit | 124b9b6d6d30015bf2b551d9ad0fb725 | 26.56 | 98 | 0.553338 | 4.326531 | false | false | false | false |
eidolon/eidolon-components | eidolon-config/src/main/kotlin/space/eidolon/component/config/parsing/Lexer.kt | 2 | 2072 | /**
* This file is part of the "eidolon-components" project.
*
* 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.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package space.eidolon.component.config.parsing
import org.apache.commons.lang3.StringEscapeUtils
import space.eidolon.component.config.parsing.exception.MatchNotFoundException
import space.eidolon.component.config.parsing.exception.ParseException
import space.eidolon.component.config.parsing.matcher.Matcher
import space.eidolon.component.config.parsing.matcher.MatcherResult
import java.util.*
import kotlin.text.MatchGroupCollection
/**
* Lexer
*
* @author Elliot Wright <[email protected]>
*/
public class Lexer(private var input: String) {
private val matchers = ArrayList<Matcher>()
/**
* Add a matcher to the internal matcher array
*/
public fun addMatcher(matcher: Matcher) {
matchers.add(matcher)
}
/**
* Check if this Lexer has any remaining input to process
*
* @return True if there is input remaining
*/
public fun hasInput(): Boolean {
return input.trim().isNotEmpty()
}
/**
* Attempt to read the next token in the current input stream
*
* @return The next token.
* @throws ParseException if no matches are found.
*/
public fun readNextToken(): Token {
var result: MatcherResult? = null
for (matcher in matchers) {
try {
result = matcher.match(input)
break
} catch (e: MatchNotFoundException) {
// Maybe log this?
}
}
if (result == null) {
throw ParseException("No match found.")
}
input = input.replaceFirstLiteral(result.rawMatch, "")
return result.token
}
}
| mit | 6aaf1ff97f6675e458288a365c98dd6a | 27.777778 | 78 | 0.663127 | 4.494577 | false | true | false | false |
airbnb/epoxy | epoxy-kspsample/src/main/java/com/airbnb/epoxy/ksp/sample/epoxyviews/HeaderView.kt | 1 | 1763 | package com.airbnb.epoxy.ksp.sample.epoxyviews
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.airbnb.epoxy.ModelProp
import com.airbnb.epoxy.ModelView
import com.airbnb.epoxy.TextProp
import com.airbnb.epoxy.ksp.sample.R
import com.airbnb.paris.annotations.Style
import com.airbnb.paris.annotations.Styleable
import com.airbnb.paris.extensions.headerViewStyle
import com.airbnb.paris.extensions.layoutHeight
import com.airbnb.paris.extensions.layoutWidth
@Styleable // Dynamic styling via the Paris library
@ModelView
class HeaderView(context: Context?) : LinearLayout(context) {
private var title: TextView? = null
private var caption: TextView? = null
private var image: ImageView? = null
init {
orientation = VERTICAL
inflate(getContext(), R.layout.header_view, this)
title = findViewById(R.id.title_text)
caption = findViewById(R.id.caption_text)
image = findViewById(R.id.image)
}
@TextProp(defaultRes = R.string.app_name)
fun setTitle(title: CharSequence?) {
this.title?.text = title
}
@TextProp
fun setCaption(caption: CharSequence?) {
this.caption?.text = caption
}
@JvmOverloads
@ModelProp
fun setShowImage(isVisible: Boolean = false) {
image?.visibility = if (isVisible) View.VISIBLE else View.GONE
}
companion object {
@Style(isDefault = true)
val headerStyle: com.airbnb.paris.styles.Style = headerViewStyle {
layoutWidth(ViewGroup.LayoutParams.MATCH_PARENT)
layoutHeight(ViewGroup.LayoutParams.MATCH_PARENT)
}
}
}
| apache-2.0 | da37bf7a6beeac82e0718f638863d7a3 | 29.396552 | 74 | 0.720363 | 4.090487 | false | false | false | false |
TongmingWu/BLPlayer | app/src/main/java/com/tm/blplayer/ui/fragment/RecommendFragment.kt | 1 | 4808 | package com.tm.blplayer.ui.fragment
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.orhanobut.logger.Logger
import com.tm.blplayer.R
import com.tm.blplayer.base.BaseFragment
import com.tm.blplayer.bean.BannerItem
import com.tm.blplayer.bean.HomeData
import com.tm.blplayer.bean.VideoItem
import com.tm.blplayer.listener.OnItemClickListener
import com.tm.blplayer.mvp.presenter.RecommendPresenter
import com.tm.blplayer.mvp.view.BaseView
import com.tm.blplayer.ui.activity.VideoDetailActivity
import com.tm.blplayer.ui.activity.WebViewActivity
import com.tm.blplayer.ui.adapter.VideoCardAdapter
import com.tm.blplayer.utils.CommonUtil
import com.tm.blplayer.utils.StringUtils
import com.tm.blplayer.utils.ToastUtils
import com.tm.blplayer.utils.constants.Constants
import com.tm.blplayer.widget.GridSpacingItemDecoration
import kotlinx.android.synthetic.main.fragment_recommend.*
import java.util.*
/**
* @author wutongming
* *
* @description 推荐
* *
* @since 2017/4/18
*/
class RecommendFragment : BaseFragment(), BaseView {
private val mData = ArrayList<VideoItem>()
private var mAdapter: VideoCardAdapter? = null
override val layoutId: Int
get() = R.layout.fragment_recommend
override fun initView() {
initRefreshLayout()
initBannerLayout()
initRecyclerView()
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
createPresenter()
getData()
}
/**
* 初始化刷新控件
*/
private fun initRefreshLayout() {
refresh_layout.setOnRefreshListener({ this.getData() })
}
/**
* 根据手机分辨率设置bannerLayout大小 --> 图片比例2:1
*/
private fun initBannerLayout() {
val width = CommonUtil.getScreenWidth(activity)
val params = banner.layoutParams
params?.height = width / 2
banner.layoutParams = params
}
/**
* 初始化RecyclerView
*/
private fun initRecyclerView() {
val manager = GridLayoutManager(activity, 2)
mAdapter = VideoCardAdapter(activity, mData, true)
mAdapter?.setOnItemClickListener(object : OnItemClickListener<VideoItem> {
override fun onItemClick(view: View, data: VideoItem, position: Int) {
val intent = Intent(activity, VideoDetailActivity::class.java)
intent.putExtra(Constants.VIDEO_AID, data.aid)
startActivity(intent)
}
})
rv_recommend.layoutManager = manager
rv_recommend.adapter = mAdapter
rv_recommend.isNestedScrollingEnabled = false
rv_recommend.addItemDecoration(GridSpacingItemDecoration(2, Constants.CARD_MARGIN, true))
}
/**
* 刷新控件开关
*/
private fun toggleRefresh(refresh: Boolean) {
Handler().post { refresh_layout.isRefreshing = refresh }
}
/**
* 创建presenter
*/
private fun createPresenter() {
presenter = presenter ?: RecommendPresenter()
presenter?.onAttach(this)
}
/**
* 获取数据
*/
private fun getData() {
toggleRefresh(true)
presenter?.requestData()
}
override fun onNetworkSuccess(result: Any) {
toggleRefresh(false)
if (result is HomeData) {
if (result.video_list.size > 0) {
banner.setViewUrls(filterBannerUrls(result.banner))
banner.setOnBannerItemClickListener { position ->
val url = result.banner[position].url
val intent = Intent(activity, WebViewActivity::class.java)
intent.putExtra("url", url)
startActivity(intent)
}
initBannerLayout()
mData.clear()
mData.addAll(result.video_list)
mAdapter?.notifyDataSetChanged()
} else {
//空处理,展示空布局
Logger.e("获取不到数据")
}
}
}
override fun onClick(v: View?) {
when (v?.id) {
}
}
/**
* 清洗banner中的url
*/
private fun filterBannerUrls(bannerItemList: List<BannerItem>): List<String> {
val result = bannerItemList.map { StringUtils.filterUrl(it.pic) }
return result
}
override fun onNetworkFailed(code: Int, errorMsg: String) {
toggleRefresh(false)
ToastUtils.showShortToast(activity, errorMsg)
}
override fun onNetworkError(error: String) {
toggleRefresh(false)
ToastUtils.showShortToast(activity, error)
}
}
| mit | ec7ae341650dd623fef12b8c43173f13 | 28.15528 | 97 | 0.644014 | 4.461977 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/index/xml/XMLTransformer.kt | 1 | 1548 | package io.georocket.index.xml
import com.fasterxml.aalto.AsyncXMLStreamReader
import com.fasterxml.aalto.`in`.ByteBasedScanner
import com.fasterxml.aalto.stax.InputFactoryImpl
import io.georocket.index.Transformer
import io.georocket.util.XMLStreamEvent
import io.vertx.core.buffer.Buffer
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
/**
* Parses XML chunks and transforms them to stream events
* @author Michel Kraemer
*/
class XMLTransformer : Transformer<XMLStreamEvent> {
private val parser = InputFactoryImpl().createAsyncForByteArray()
private suspend fun processEvents() = flow {
while (true) {
val nextEvent = parser.next()
if (nextEvent == AsyncXMLStreamReader.EVENT_INCOMPLETE) {
break
}
// `parser.location.characterOffset` only returns an int
// val pos = parser.location.characterOffset
val pos = (parser.inputFeeder as ByteBasedScanner).startingByteOffset
val streamEvent = XMLStreamEvent(nextEvent, pos, parser)
emit(streamEvent)
if (nextEvent == AsyncXMLStreamReader.END_DOCUMENT) {
parser.close()
break
}
}
}
override suspend fun transformChunk(chunk: Buffer) = flow {
val bytes = chunk.bytes
var i = 0
while (i < bytes.size) {
val len = bytes.size - i
parser.inputFeeder.feedInput(bytes, i, len)
i += len
emitAll(processEvents())
}
}
override suspend fun finish() = flow {
parser.inputFeeder.endOfInput()
emitAll(processEvents())
}
}
| apache-2.0 | ce73a30c1c41dabf28ef85b137e3b4f5 | 27.145455 | 75 | 0.702842 | 4.062992 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/core/aggregator/ObjectAggregator.kt | 2 | 5500 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.core.aggregator
import org.apache.causeway.client.kroviz.core.event.LogEntry
import org.apache.causeway.client.kroviz.core.event.ResourceProxy
import org.apache.causeway.client.kroviz.core.model.CollectionDM
import org.apache.causeway.client.kroviz.core.model.ObjectDM
import org.apache.causeway.client.kroviz.layout.Layout
import org.apache.causeway.client.kroviz.to.*
import org.apache.causeway.client.kroviz.to.bs3.Grid
import org.apache.causeway.client.kroviz.ui.core.ViewManager
import org.apache.causeway.client.kroviz.ui.dialog.ErrorDialog
/** sequence of operations:
* (0) Menu Action User clicks BasicTypes.String -> handled by ActionDispatcher
* (1) OBJECT TObjectHandler -> invoke() -> passed on to ObjectAggregator
* (2) OBJECT_LAYOUT layoutHandler -> invoke(layout.getProperties()[].getLink()) link can be null?
* (3) ???_OBJECT_PROPERTY PropertyHandler -> invoke()
* (4) ???_PROPERTY_DESCRIPTION <PropertyDescriptionHandler>
*/
class ObjectAggregator(val actionTitle: String) : AggregatorWithLayout() {
var collectionMap = mutableMapOf<String, CollectionAggregator>()
init {
dpm = ObjectDM(actionTitle)
}
override fun update(logEntry: LogEntry, subType: String) {
super.update(logEntry, subType)
if (!logEntry.isUpdatedFromParentedCollection()) {
val referrer = logEntry.url
when (val obj = logEntry.getTransferObject()) {
is TObject -> handleObject(obj, referrer)
is ResultObject -> handleResultObject(obj)
is ResultValue -> handleResultValue(obj)
is Property -> handleProperty(obj)
is Layout -> handleLayout(obj, dpm as ObjectDM, referrer)
is Grid -> handleGrid(obj)
is HttpError -> ErrorDialog(logEntry).open()
else -> log(logEntry)
}
}
if (dpm.canBeDisplayed() && collectionsCanBeDisplayed()) {
collectionMap.forEach {
(dpm as ObjectDM).addCollection(it.key, it.value.dpm as CollectionDM)
}
ViewManager.openObjectView(this)
}
}
private fun collectionsCanBeDisplayed(): Boolean {
if (collectionMap.isEmpty()) return true
return collectionMap.all {
val cdm = it.value.dpm as CollectionDM
cdm.canBeDisplayed()
}
}
fun handleObject(obj: TObject, referrer : String) {
// After ~/action/invoke is called, the actual object instance (containing properties) needs to be invoked as well.
// Note that rel.self/href is identical and both are of type TObject. logEntry.url is different, though.
if (obj.getProperties().size == 0) {
invokeInstance(obj, referrer)
} else {
dpm.addData(obj)
}
if (collectionMap.isEmpty()) {
handleCollections(obj, referrer)
}
invokeLayoutLink(obj, this, referrer = referrer)
}
private fun invokeInstance(obj: TObject, referrer: String) {
val selfLink = obj.links.find { l ->
l.relation() == Relation.SELF
}
invoke(selfLink!!, this, referrer = referrer)
}
fun handleResultObject(resultObject: ResultObject) {
(dpm as ObjectDM).addResult(resultObject)
}
fun handleResultValue(resultValue: ResultValue) {
// TODO (dpm as ObjectDM).addResult(resultObject)
console.log("[OA.handleResultValue]")
console.log(resultValue)
}
override fun getObject(): TObject? {
return dpm.getObject()
}
private fun handleCollections(obj: TObject, referrer: String) {
obj.getCollections().forEach {
val key = it.id
val aggregator = CollectionAggregator(key, this)
collectionMap.put(key, aggregator)
val link = it.links.first()
ResourceProxy().fetch(link, aggregator, referrer = referrer)
}
}
private fun handleProperty(property: Property) {
console.log("[OA.handleProperty]")
console.log(property)
// throw Throwable("[ObjectAggregator.handleProperty] not implemented yet")
}
private fun handleGrid(grid: Grid) {
(dpm as ObjectDM).grid = grid
}
override fun reset(): ObjectAggregator {
dpm.isRendered = false
return this
}
/**
* This is done in order to have the parent check, if it and it's children can be displayed
*/
private fun LogEntry.isUpdatedFromParentedCollection(): Boolean {
return this.url == ""
}
}
| apache-2.0 | 518d2e5006a832fbabd48ca36ddf5789 | 37.194444 | 123 | 0.653636 | 4.330709 | false | false | false | false |
google/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelFactory.kt | 1 | 6307 | // 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.collaboration.ui.codereview.list.search
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.codereview.list.search.ChooserPopupUtil.showAndAwaitListSubmission
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.*
import com.intellij.ui.components.GradientViewport
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBThinOverlappingScrollBar
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.util.ui.JBUI
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.annotations.Nls
import java.awt.Adjustable
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants
abstract class ReviewListSearchPanelFactory<S : ReviewListSearchValue, Q : ReviewListQuickFilter<S>, VM : ReviewListSearchPanelViewModel<S, Q>>(
protected val vm: VM
) {
fun create(viewScope: CoroutineScope): JComponent {
val searchField = ReviewListSearchTextFieldFactory(vm.queryState).create(viewScope, chooseFromHistory = { point ->
val value = JBPopupFactory.getInstance()
.createPopupChooserBuilder(vm.getSearchHistory().reversed())
.setRenderer(SimpleListCellRenderer.create { label, value, _ ->
label.text = getShortText(value)
})
.createPopup()
.showAndAwaitListSubmission<S>(point)
if (value != null) {
vm.searchState.update { value }
}
})
val filters = createFilters(viewScope)
val filtersPanel = JPanel(HorizontalLayout(4)).apply {
isOpaque = false
filters.forEach { add(it, HorizontalLayout.LEFT) }
}.let {
ScrollPaneFactory.createScrollPane(it, true).apply {
viewport = GradientViewport(it, JBUI.insets(0, 10), false)
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
horizontalScrollBar = JBThinOverlappingScrollBar(Adjustable.HORIZONTAL)
ClientProperty.put(this, JBScrollPane.FORCE_HORIZONTAL_SCROLL, true)
}
}
val quickFilterButton = QuickFilterButtonFactory().create(viewScope, vm.quickFilters)
val filterPanel = JPanel(BorderLayout()).apply {
border = JBUI.Borders.emptyTop(10)
isOpaque = false
add(quickFilterButton, BorderLayout.WEST)
add(filtersPanel, BorderLayout.CENTER)
}
val searchPanel = JPanel(BorderLayout()).apply {
border = JBUI.Borders.compound(IdeBorderFactory.createBorder(SideBorder.BOTTOM), JBUI.Borders.empty(8, 10, 0, 10))
add(searchField, BorderLayout.CENTER)
add(filterPanel, BorderLayout.SOUTH)
}
return searchPanel
}
protected abstract fun getShortText(searchValue: S): @Nls String
protected abstract fun createFilters(viewScope: CoroutineScope): List<JComponent>
protected abstract fun Q.getQuickFilterTitle(): @Nls String
private inner class QuickFilterButtonFactory {
fun create(viewScope: CoroutineScope, quickFilters: List<Q>): JComponent {
val toolbar = ActionManager.getInstance().createActionToolbar(
"Review.FilterToolbar",
DefaultActionGroup(FilterPopupMenuAction(quickFilters)),
true
).apply {
layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY
component.isOpaque = false
component.border = null
targetComponent = null
}
viewScope.launch {
vm.searchState.collect {
toolbar.updateActionsImmediately()
}
}
return toolbar.component
}
private fun showQuickFiltersPopup(parentComponent: JComponent, quickFilters: List<Q>) {
val quickFiltersActions =
quickFilters.map { QuickFilterAction(it.getQuickFilterTitle(), it.filter) } +
Separator() +
ClearFiltersAction()
JBPopupFactory.getInstance()
.createActionGroupPopup(CollaborationToolsBundle.message("review.list.filter.quick.title"), DefaultActionGroup(quickFiltersActions),
DataManager.getInstance().getDataContext(parentComponent),
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
false)
.showUnderneathOf(parentComponent)
}
private inner class FilterPopupMenuAction(private val quickFilters: List<Q>) : AnActionButton(), DumbAware {
override fun updateButton(e: AnActionEvent) {
e.presentation.icon = FILTER_ICON.getLiveIndicatorIcon(vm.searchState.value.filterCount != 0)
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun actionPerformed(e: AnActionEvent) {
showQuickFiltersPopup(e.inputEvent.component as JComponent, quickFilters)
}
}
private inner class QuickFilterAction(name: @Nls String, private val search: S)
: DumbAwareAction(name), Toggleable {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) = Toggleable.setSelected(e.presentation, vm.searchState.value == search)
override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { search }
}
private inner class ClearFiltersAction
: DumbAwareAction(CollaborationToolsBundle.message("review.list.filter.quick.clear", vm.searchState.value.filterCount)) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = vm.searchState.value.filterCount > 0
}
override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { vm.emptySearch }
}
}
companion object {
private val FILTER_ICON: BadgeIconSupplier = BadgeIconSupplier(AllIcons.General.Filter)
}
} | apache-2.0 | 3519f7cc66ab8e475431a14fed7703bf | 38.672956 | 144 | 0.734105 | 5.03754 | false | false | false | false |
youdonghai/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt | 4 | 13639 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.jetbrains.builtInWebServer
import com.google.common.cache.CacheBuilder
import com.google.common.net.InetAddresses
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.io.setOwnerPermissions
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.*
import com.intellij.util.net.NetUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.cookie.DefaultCookie
import io.netty.handler.codec.http.cookie.ServerCookieDecoder
import io.netty.handler.codec.http.cookie.ServerCookieEncoder
import org.jetbrains.ide.BuiltInServerManagerImpl
import org.jetbrains.ide.HttpRequestHandler
import org.jetbrains.io.*
import java.awt.datatransfer.StringSelection
import java.io.IOException
import java.math.BigInteger
import java.net.InetAddress
import java.nio.file.Path
import java.nio.file.Paths
import java.security.SecureRandom
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
internal val LOG = Logger.getInstance(BuiltInWebServer::class.java)
// name is duplicated in the ConfigImportHelper
private const val IDE_TOKEN_FILE = "user.web.token"
private val notificationManager by lazy {
SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP.value, NotificationType.INFORMATION,
null)
}
class BuiltInWebServer : HttpRequestHandler() {
override fun isAccessible(request: HttpRequest) = request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true)
override fun isSupported(request: FullHttpRequest) = super.isSupported(request) || request.method() == HttpMethod.POST
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
var host = request.host
if (host.isNullOrEmpty()) {
return false
}
val portIndex = host!!.indexOf(':')
if (portIndex > 0) {
host = host.substring(0, portIndex)
}
val projectName: String?
val isIpv6 = host[0] == '[' && host.length > 2 && host[host.length - 1] == ']'
if (isIpv6) {
host = host.substring(1, host.length - 1)
}
if (isIpv6 || InetAddresses.isInetAddress(host) || isOwnHostName(host) || host.endsWith(".ngrok.io")) {
if (urlDecoder.path().length < 2) {
return false
}
projectName = null
}
else {
projectName = host
}
return doProcess(urlDecoder, request, context, projectName)
}
}
internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false)
internal const val TOKEN_PARAM_NAME = "_ijt"
const val TOKEN_HEADER_NAME = "x-ijt"
private val STANDARD_COOKIE by lazy {
val productName = ApplicationNamesInfo.getInstance().lowercaseProductName
val configPath = PathManager.getConfigPath()
val file = Paths.get(configPath, IDE_TOKEN_FILE)
var token: String? = null
if (file.exists()) {
try {
token = UUID.fromString(file.readText()).toString()
}
catch (e: Exception) {
LOG.warn(e)
}
}
if (token == null) {
token = UUID.randomUUID().toString()
file.write(token!!)
file.setOwnerPermissions()
}
// explicit setting domain cookie on localhost doesn't work for chrome
// http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https
val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!)
cookie.isHttpOnly = true
cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10))
cookie.setPath("/")
cookie
}
// expire after access because we reuse tokens
private val tokens = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>()
fun acquireToken(): String {
var token = tokens.asMap().keys.firstOrNull()
if (token == null) {
token = TokenGenerator.generate()
tokens.put(token, java.lang.Boolean.TRUE)
}
return token
}
// http://stackoverflow.com/a/41156 - shorter than UUID, but secure
private object TokenGenerator {
private val random = SecureRandom()
fun generate(): String = BigInteger(130, random).toString(32)
}
private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean {
val decodedPath = URLUtil.unescapePercentSequences(urlDecoder.path())
var offset: Int
var isEmptyPath: Boolean
val isCustomHost = projectNameAsHost != null
var projectName: String
if (isCustomHost) {
projectName = projectNameAsHost!!
// host mapped to us
offset = 0
isEmptyPath = decodedPath.isEmpty()
}
else {
offset = decodedPath.indexOf('/', 1)
projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset)
isEmptyPath = offset == -1
}
var candidateByDirectoryName: Project? = null
val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean {
if (project.isDisposed) {
return false
}
val name = project.name
if (isCustomHost) {
// domain name is case-insensitive
if (projectName.equals(name, ignoreCase = true)) {
if (!SystemInfoRt.isFileSystemCaseSensitive) {
// may be passed path is not correct
projectName = name
}
return true
}
}
else {
// WEB-17839 Internal web server reports 404 when serving files from project with slashes in name
if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfoRt.isFileSystemCaseSensitive)) {
val isEmptyPathCandidate = decodedPath.length == (name.length + 1)
if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') {
projectName = name
offset = name.length + 1
isEmptyPath = isEmptyPathCandidate
return true
}
}
}
if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) {
candidateByDirectoryName = project
}
return false
}) ?: candidateByDirectoryName ?: return false
if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) {
notificationManager.notify("Built-in web server is deactivated, to activate, please use Open in Browser", null)
return false
}
if (isEmptyPath) {
// we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work
redirectToDirectory(request, context.channel(), projectName, null)
return true
}
val path = toIdeaPath(decodedPath, offset)
if (path == null) {
HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request)
return true
}
for (pathHandler in WebServerPathHandler.EP_NAME.extensions) {
LOG.catchAndLog {
if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) {
return true
}
}
}
return false
}
internal fun HttpRequest.isSignedRequest(): Boolean {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return true
}
// we must check referrer - if html cached, browser will send request without query
val token = headers().get(TOKEN_HEADER_NAME)
?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull()
?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() }
// we don't invalidate token — allow to make subsequent requests using it (it is required for our javadoc DocumentationComponent)
return token != null && tokens.getIfPresent(token) != null
}
@JvmOverloads
internal fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean = request.isSignedRequest()): HttpHeaders? {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return EmptyHttpHeaders.INSTANCE
}
request.headers().get(HttpHeaderNames.COOKIE)?.let {
for (cookie in ServerCookieDecoder.STRICT.decode(it)) {
if (cookie.name() == STANDARD_COOKIE.name()) {
if (cookie.value() == STANDARD_COOKIE.value()) {
return EmptyHttpHeaders.INSTANCE
}
break
}
}
}
if (isSignedRequest) {
return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict")
}
val urlDecoder = QueryStringDecoder(request.uri())
if (!urlDecoder.path().endsWith("/favicon.ico")) {
val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}"
SwingUtilities.invokeAndWait {
ProjectUtil.focusProjectWindow(null, true)
if (MessageDialogBuilder
.yesNo("", "Page '" + StringUtil.trimMiddle(url, 50) + "' requested without authorization, " +
"\nyou can copy URL and open it in browser to trust it.")
.icon(Messages.getWarningIcon())
.yesText("Copy authorization URL to clipboard")
.show() == Messages.YES) {
CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken()))
}
}
}
HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return null
}
private fun toIdeaPath(decodedPath: String, offset: Int): String? {
// must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize
val path = decodedPath.substring(offset)
if (!path.startsWith('/')) {
return null
}
return FileUtil.toCanonicalPath(path, '/').substring(1)
}
fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean {
val basePath = project.basePath
return basePath != null && endsWithName(basePath, projectName)
}
fun findIndexFile(basedir: VirtualFile): VirtualFile? {
val children = basedir.children
if (children == null || children.isEmpty()) {
return null
}
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: VirtualFile? = null
val preferredName = indexNamePrefix + "html"
for (child in children) {
if (!child.isDirectory) {
val name = child.name
//noinspection IfStatementWithIdenticalBranches
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
fun findIndexFile(basedir: Path): Path? {
val children = basedir.directoryStreamIfExists({
val name = it.fileName.toString()
name.startsWith("index.") || name.startsWith("default.")
}) { it.toList() } ?: return null
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: Path? = null
val preferredName = "${indexNamePrefix}html"
for (child in children) {
if (!child.isDirectory()) {
val name = child.fileName.toString()
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
// is host loopback/any or network interface address (i.e. not custom domain)
// must be not used to check is host on local machine
internal fun isOwnHostName(host: String): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
try {
val address = InetAddress.getByName(host)
if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) {
return true
}
val localHostName = InetAddress.getLocalHost().hostName
// WEB-8889
// develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name)
return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true))
}
catch (ignored: IOException) {
return false
}
} | apache-2.0 | 95742fc1f967750f3ffcefbac86739ce | 34.331606 | 165 | 0.706754 | 4.493245 | false | false | false | false |
littleGnAl/Accounting | app/src/main/java/com/littlegnal/accounting/ui/addedit/AddOrEditFragment.kt | 1 | 7415 | package com.littlegnal.accounting.ui.addedit
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.navigation.fragment.findNavController
import com.airbnb.mvrx.BaseMvRxFragment
import com.airbnb.mvrx.Fail
import com.airbnb.mvrx.activityViewModel
import com.airbnb.mvrx.args
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.withState
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxbinding3.widget.textChanges
import com.littlegnal.accounting.R
import com.littlegnal.accounting.base.util.plusAssign
import com.littlegnal.accounting.base.util.success
import com.littlegnal.accounting.base.util.toast
import com.littlegnal.accounting.ui.main.MainActivity
import com.littlegnal.accounting.ui.main.MainViewModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Function3
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.fragment_add_or_edit.btn_add_or_edit_confirm
import kotlinx.android.synthetic.main.fragment_add_or_edit.et_add_or_edit_pay_value
import kotlinx.android.synthetic.main.fragment_add_or_edit.et_add_or_edit_remarks
import kotlinx.android.synthetic.main.fragment_add_or_edit.fbl_tag_container
import kotlinx.android.synthetic.main.fragment_add_or_edit.sv_add_or_edit
import kotlinx.android.synthetic.main.fragment_add_or_edit.tv_add_or_edit_date_value
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit
class AddOrEditFragment : BaseMvRxFragment() {
private lateinit var showDate: String
private val selectedDateAndTimePublisher: PublishSubject<String> = PublishSubject.create()
private lateinit var saveOrUpdateConfirmObservable: Observable<Boolean>
private lateinit var inputPayObservable: Observable<String>
private val accountingArgs: AddOrEditMvRxStateArgs by args()
private val disposables = CompositeDisposable()
private val mainMvRxViewModel by activityViewModel(MainViewModel::class)
private val addOrEditMvRxViewModel by fragmentViewModel(AddOrEditViewModel::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val title = if (accountingArgs.id != -1) {
getString(R.string.add_or_edit_edit_title)
} else {
getString(R.string.add_or_edit_add_title)
}
(activity as MainActivity).updateTitle(title)
addOrEditMvRxViewModel.loadAccounting(accountingArgs.id)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_add_or_edit, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tv_add_or_edit_date_value.setOnClickListener {
hideSoftKeyboard()
datePicker()
}
sv_add_or_edit.setOnTouchListener { _, _ ->
hideSoftKeyboard()
return@setOnTouchListener false
}
saveOrUpdateConfirmObservable = btn_add_or_edit_confirm.clicks()
.throttleFirst(300, TimeUnit.MILLISECONDS)
.map { true }
inputPayObservable = et_add_or_edit_pay_value.textChanges()
.map { it.toString() }
.share()
// 只有输入金额,选择tag,选择时间后才允许点击确认按钮
disposables += Observable.combineLatest(
inputPayObservable,
fbl_tag_container.checkedTagNameObservable(),
selectedDateAndTimePublisher,
Function3<String, String, String, Boolean> { pay, tagName, dateTime ->
pay.isNotEmpty() && tagName.isNotEmpty() && dateTime.isNotEmpty()
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
btn_add_or_edit_confirm.isEnabled = it
}
disposables += btn_add_or_edit_confirm.clicks()
.throttleFirst(300, TimeUnit.MILLISECONDS)
.subscribe {
withState(mainMvRxViewModel) { preState ->
preState.success(preState.accountingDetailList) { preList ->
mainMvRxViewModel.addOrEditAccounting(
preList,
accountingArgs.id,
et_add_or_edit_pay_value.text.toString().toFloat(),
fbl_tag_container.getCheckedTagName(),
showDate,
et_add_or_edit_remarks.text.toString()
)
}
}
findNavController().navigateUp()
}
}
private var inputMethodManager: InputMethodManager? = null
private fun hideSoftKeyboard() {
if (inputMethodManager == null) {
inputMethodManager = context?.getSystemService(
Context.INPUT_METHOD_SERVICE
) as InputMethodManager
}
if (activity?.window?.attributes?.softInputMode !=
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
if (activity?.currentFocus != null) {
inputMethodManager?.hideSoftInputFromWindow(
activity?.currentFocus?.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
}
}
}
private fun timePicker() {
val c = Calendar.getInstance()
TimePickerDialog(
context,
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
showDate += " $hourOfDay:$minute"
tv_add_or_edit_date_value.text = showDate
selectedDateAndTimePublisher.onNext(showDate)
},
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
).run { show() }
}
private fun datePicker() {
val c = Calendar.getInstance()
context?.apply {
DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
showDate = "$year/${month + 1}/$dayOfMonth"
timePicker()
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)
).apply {
datePicker.maxDate = c.timeInMillis
show()
}
}
}
override fun invalidate() {
withState(addOrEditMvRxViewModel) { state ->
if ((state.accounting as? Fail)?.error != null) {
activity?.toast(state.accounting.error.message.toString())
return@withState
}
state.accounting()?.apply {
if (id == 0) return@withState
if (amount != 0.0f) {
val amountString = amount.toString()
et_add_or_edit_pay_value.setText(amountString)
et_add_or_edit_pay_value.setSelection(amountString.length)
}
if (tagName.isNotEmpty()) {
fbl_tag_container.selectTag(tagName)
}
val dateTime = SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.getDefault()).format(createTime)
tv_add_or_edit_date_value.text = dateTime
selectedDateAndTimePublisher.onNext(dateTime)
showDate = dateTime
remarks?.apply { et_add_or_edit_remarks.setText(this) }
}
}
}
override fun onDestroyView() {
super.onDestroyView()
disposables.dispose()
}
}
| apache-2.0 | 7af839d5148f3df0d63de6ea47085a21 | 32.334842 | 99 | 0.694448 | 4.330982 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_info/model/CourseInfoItem.kt | 1 | 1696 | package org.stepik.android.view.course_info.model
import org.stepik.android.model.user.User
import org.stepik.android.view.video_player.model.VideoPlayerMediaData
import ru.nobird.app.core.model.Identifiable
sealed class CourseInfoItem(
open val type: CourseInfoType
) : Comparable<CourseInfoItem>, Identifiable<Int> {
override val id: Int
get() = type.ordinal
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CourseInfoItem
if (type != other.type) return false
return true
}
override fun hashCode(): Int =
type.hashCode()
override fun compareTo(other: CourseInfoItem): Int =
type.ordinal.compareTo(other.type.ordinal)
data class AuthorsBlock(
val authors: List<User?>
) : CourseInfoItem(CourseInfoType.AUTHORS)
data class Skills(
val acquiredSkills: List<String>
) : CourseInfoItem(CourseInfoType.ACQUIRED_SKILLS)
data class SummaryBlock(
val text: String
) : CourseInfoItem(CourseInfoType.SUMMARY)
data class AboutBlock(
val text: String
) : CourseInfoItem(CourseInfoType.ABOUT)
data class VideoBlock(
val videoMediaData: VideoPlayerMediaData
) : CourseInfoItem(CourseInfoType.VIDEO)
sealed class WithTitle(type: CourseInfoType) : CourseInfoItem(type) {
data class TextBlock(
override val type: CourseInfoType,
val text: String
) : WithTitle(type)
data class InstructorsBlock(
val instructors: List<User?>
) : WithTitle(CourseInfoType.INSTRUCTORS)
}
} | apache-2.0 | 1d66f027839dbc4dac4e6ac2d42d5efc | 27.283333 | 73 | 0.675118 | 4.571429 | false | false | false | false |
fancylou/FancyFilePicker | fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/PicturePicker.kt | 1 | 5293 | package net.muliba.fancyfilepickerlibrary
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.ColorInt
import com.wugang.activityresult.library.ActivityResult
import net.muliba.fancyfilepickerlibrary.ui.PictureLoaderActivity
import net.muliba.fancyfilepickerlibrary.util.Utils
/**
* Created by fancy on 2017/5/22.
*/
class PicturePicker {
companion object {
@JvmStatic val FANCY_REQUEST_CODE @JvmName("FANCY_REQUEST_CODE") get() = 1024
@JvmStatic val FANCY_PICTURE_PICKER_ARRAY_LIST_RESULT_KEY @JvmName("FANCY_PICTURE_PICKER_ARRAY_LIST_RESULT_KEY") get() = "fancy_picture_picker_array_result"
@JvmStatic val FANCY_PICTURE_PICKER_SINGLE_RESULT_KEY @JvmName("FANCY_PICTURE_PICKER_SINGLE_RESULT_KEY") get() = "fancy_picture_picker_single_result"
//选择类型
@JvmStatic val CHOOSE_TYPE_MULTIPLE @JvmName("CHOOSE_TYPE_MULTIPLE") get() = 0
@JvmStatic val CHOOSE_TYPE_SINGLE @JvmName("CHOOSE_TYPE_SINGLE") get() = 1
}
private var requestCode: Int = FANCY_REQUEST_CODE
private var activity: Activity? = null
private var actionBarColor: Int = Color.parseColor("#F44336")
private var actionBarTitle: String = ""
private var chooseType = CHOOSE_TYPE_MULTIPLE //默认多选
private var existingResults = ArrayList<String>()
fun withActivity(activity: Activity): PicturePicker {
this.activity = activity
return this
}
fun chooseType(type: Int = CHOOSE_TYPE_SINGLE): PicturePicker {
if (type != CHOOSE_TYPE_SINGLE && type != CHOOSE_TYPE_MULTIPLE) {
throw IllegalArgumentException("chooseType value is illegal , must be one of #PicturePicker.CHOOSE_TYPE_MULTIPLE or #PicturePicker.CHOOSE_TYPE_SINGLE ")
}
chooseType = type
return this
}
/**
* 定义requestCode
* @param requestCode
*/
@Deprecated(message = "4.0.0开始不再使用,用forResult直接返回结果,不需要onActivityResult接收结果")
fun requestCode(requestCode: Int): PicturePicker {
this.requestCode = requestCode
return this
}
fun existingResults(results:ArrayList<String>): PicturePicker {
this.existingResults.clear()
if (!results.isEmpty()) {
this.existingResults.addAll(results)
}
return this
}
/**
* 设置actionBar的背景色
* @param color actionBar的背景色
*/
fun actionBarColor(@ColorInt color: Int): PicturePicker {
actionBarColor = color
return this
}
/**
* 设置标题
* @param title
*/
fun title(title: String): PicturePicker {
this.actionBarTitle = title
return this
}
/**
* 启动选择器
*/
@Deprecated(message = "4.0.0开始不再使用,用forResult直接返回结果,不需要onActivityResult接收结果")
fun start() {
if (activity == null) {
throw RuntimeException("not found Activity, Please execute the function 'withActivity' ")
}
val intent = Intent(activity, PictureLoaderActivity::class.java)
intent.putExtra(Utils.ACTION_BAR_BACKGROUND_COLOR_KEY, actionBarColor)
intent.putExtra(Utils.ACTION_BAR_TITLE_KEY, actionBarTitle)
intent.putExtra(Utils.CHOOSE_TYPE_KEY, chooseType)
intent.putExtra(Utils.MULIT_CHOOSE_BACK_RESULTS_KEY, existingResults)
activity?.startActivityForResult(intent, requestCode)
}
/**
* 4.0.0 新增
* 返回选择的结果 如果是单选 result[0]获取
* 不再需要到onActivityResult中去接收结果
*/
fun forResult(listener: (filePaths: List<String>) -> Unit) {
if (activity == null) {
throw RuntimeException("not found Activity, Please execute the function 'withActivity' ")
}
val bundle = Bundle()
bundle.putInt(Utils.ACTION_BAR_BACKGROUND_COLOR_KEY, actionBarColor)
bundle.putString(Utils.ACTION_BAR_TITLE_KEY, actionBarTitle)
bundle.putInt(Utils.CHOOSE_TYPE_KEY, chooseType)
bundle.putStringArrayList(Utils.MULIT_CHOOSE_BACK_RESULTS_KEY, existingResults)
ActivityResult.of(activity!!)
.className(PictureLoaderActivity::class.java)
.params(bundle)
.greenChannel()
.forResult { resultCode, data ->
val result = ArrayList<String>()
if (resultCode == Activity.RESULT_OK) {
if (chooseType == CHOOSE_TYPE_SINGLE) {
val single = data?.getStringExtra(FANCY_PICTURE_PICKER_SINGLE_RESULT_KEY)
if (single!=null && single.isNotEmpty()) {
result.add(single)
}
}else {
val array = data?.getStringArrayListExtra(FANCY_PICTURE_PICKER_ARRAY_LIST_RESULT_KEY)
if (array!=null && array.isNotEmpty()) {
result.addAll(array)
}
}
}
listener(result)
}
}
} | apache-2.0 | b5ff5fde609e5831485bb666492adf8f | 36.455882 | 164 | 0.621245 | 4.417173 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/impl/SelectFileAction.kt | 3 | 3050 | // 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.ide.projectView.impl
import com.intellij.ide.SelectInContext
import com.intellij.ide.SelectInManager
import com.intellij.ide.SelectInTarget
import com.intellij.ide.actions.SelectInContextImpl
import com.intellij.ide.impl.ProjectViewSelectInGroupTarget
import com.intellij.ide.projectView.ProjectView
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys.TOOL_WINDOW
import com.intellij.openapi.keymap.KeymapUtil.getFirstKeyboardShortcutText
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.wm.ToolWindowId.PROJECT_VIEW
private const val SELECT_CONTEXT_FILE = "SelectInProjectView"
private const val SELECT_OPENED_FILE = "SelectOpenedFileInProjectView"
internal class SelectFileAction : DumbAwareAction() {
override fun actionPerformed(event: AnActionEvent) {
when (getActionId(event)) {
SELECT_CONTEXT_FILE -> getSelector(event)?.run { target.selectIn(context, true) }
SELECT_OPENED_FILE -> getView(event)?.selectOpenedFile?.run()
}
}
override fun update(event: AnActionEvent) {
val id = getActionId(event)
event.presentation.text = ActionsBundle.actionText(id)
event.presentation.description = ActionsBundle.actionDescription(id)
when (id) {
SELECT_CONTEXT_FILE -> {
event.presentation.isEnabledAndVisible = getSelector(event)?.run { target.canSelect(context) } == true
}
SELECT_OPENED_FILE -> {
val view = getView(event)
event.presentation.isEnabled = view?.selectOpenedFile != null
event.presentation.isVisible = view?.isSelectOpenedFileEnabled == true
event.project?.let { project ->
if (event.presentation.isVisible && getFirstKeyboardShortcutText(id).isEmpty()) {
val shortcut = getFirstKeyboardShortcutText("SelectIn")
if (shortcut.isNotEmpty()) {
val index = 1 + SelectInManager.getInstance(project).targetList.indexOfFirst { it is ProjectViewSelectInGroupTarget }
if (index >= 1) event.presentation.text = "${event.presentation.text} ($shortcut, $index)"
}
}
}
}
}
}
private data class Selector(val target: SelectInTarget, val context: SelectInContext)
private fun getSelector(event: AnActionEvent): Selector? {
val target = SelectInManager.findSelectInTarget(PROJECT_VIEW, event.project) ?: return null
val context = SelectInContextImpl.createContext(event) ?: return null
return Selector(target, context)
}
private fun getView(event: AnActionEvent) =
event.project?.let { ProjectView.getInstance(it) as? ProjectViewImpl }
private fun getActionId(event: AnActionEvent) =
when (TOOL_WINDOW.getData(event.dataContext)?.id) {
PROJECT_VIEW -> SELECT_OPENED_FILE
else -> SELECT_CONTEXT_FILE
}
}
| apache-2.0 | e7d6d21508f057e05ecf6c8f903f424e | 42.571429 | 140 | 0.736066 | 4.43314 | false | false | false | false |
allotria/intellij-community | platform/execution-impl/src/com/intellij/execution/impl/RunConfigurationInArbitraryFileScanner.kt | 8 | 1934 | // 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.impl
import com.intellij.openapi.project.Project
import com.intellij.util.indexing.roots.IndexableFileScanner
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import com.intellij.util.indexing.roots.kind.ModuleRootOrigin
import com.intellij.util.indexing.roots.kind.ProjectFileOrDirOrigin
/**
* This class doesn't push any file properties, it is used for scanning the project for `*.run.xml` files - files with run configurations.
* This is to handle run configurations stored in arbitrary files within project content (not in .idea/runConfigurations or project.ipr file).
*/
class RunConfigurationInArbitraryFileScanner : IndexableFileScanner {
companion object {
fun isFileWithRunConfigs(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !StringUtil.endsWith(file.nameSequence, ".run.xml")) return false
var parent = file.parent
while (parent != null) {
if (StringUtil.equals(parent.nameSequence, ".idea")) return false
parent = parent.parent
}
return true
}
fun isFileWithRunConfigs(path: String) = !path.contains("/.idea/") && PathUtil.getFileName(path).endsWith(".run.xml")
}
override fun startSession(project: Project): IndexableFileScanner.ScanSession {
val runManagerImpl = RunManagerImpl.getInstanceImpl(project)
return IndexableFileScanner.ScanSession {
if (it is ModuleRootOrigin || it is ProjectFileOrDirOrigin)
IndexableFileScanner.IndexableFileVisitor { fileOrDir ->
if (isFileWithRunConfigs(fileOrDir)) {
runManagerImpl.updateRunConfigsFromArbitraryFiles(emptyList(), listOf(fileOrDir.path))
}
}
else null
}
}
} | apache-2.0 | 8a17c0c90c2aa5ec64c80bd0c90a7c24 | 44 | 142 | 0.745605 | 4.405467 | false | true | false | false |
ptkNktq/AndroidNotificationNotifier | AndroidApp/ui/src/main/java/me/nya_n/notificationnotifier/ui/screen/detail/DetailViewModel.kt | 1 | 2287 | package me.nya_n.notificationnotifier.ui.screen.detail
import android.content.Context
import androidx.lifecycle.*
import kotlinx.coroutines.launch
import me.nya_n.notificationnotifier.domain.usecase.DeleteTargetAppUseCase
import me.nya_n.notificationnotifier.domain.usecase.LoadFilterConditionUseCase
import me.nya_n.notificationnotifier.domain.usecase.SaveFilterConditionUseCase
import me.nya_n.notificationnotifier.model.InstalledApp
import me.nya_n.notificationnotifier.model.Message
import me.nya_n.notificationnotifier.ui.R
import me.nya_n.notificationnotifier.ui.util.AppIcon
import me.nya_n.notificationnotifier.ui.util.Event
class DetailViewModel(
context: Context,
private val loadFilterConditionUseCase: LoadFilterConditionUseCase,
private val saveFilterConditionUseCase: SaveFilterConditionUseCase,
private val deleteTargetAppUseCase: DeleteTargetAppUseCase,
private val target: InstalledApp
) : ViewModel() {
val targetIcon = liveData {
emit(AppIcon.get(target.packageName, context.packageManager))
}
val targetName = liveData {
emit(target.label)
}
private val _message = MutableLiveData<Event<Message>>()
val message: LiveData<Event<Message>> = _message
private val _targetDeleted = MutableLiveData<Event<InstalledApp>>()
val targetDeleted: LiveData<Event<InstalledApp>> = _targetDeleted
val filterCondition = MutableLiveData<String>()
init {
/**
* 通知条件を読み込む
*/
viewModelScope.launch {
val cond = loadFilterConditionUseCase(target)
filterCondition.postValue(cond)
}
}
/**
* 選択したアプリを通知対象から外す
*/
fun deleteTarget() {
viewModelScope.launch {
deleteTargetAppUseCase(target)
_message.postValue(Event(Message.Notice(R.string.deleted)))
_targetDeleted.postValue(Event(target))
}
}
/**
* 通知条件を保存
*/
fun save() {
viewModelScope.launch {
saveFilterConditionUseCase(
SaveFilterConditionUseCase.Args(target, filterCondition.value)
)
_message.postValue(Event(Message.Notice(R.string.condition_added)))
}
}
} | mit | 517c2199c49ba96ac03dfd06aab78eb6 | 32.69697 | 79 | 0.705803 | 4.428287 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/util/TextManipulators.kt | 1 | 3001 | /*
* Copyright (C) 2019 Veli Tasalı
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.util
import android.content.Context
import androidx.collection.ArrayMap
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.config.AppConfig
import java.net.NetworkInterface
import java.util.*
/**
* created by: Veli
* date: 12.11.2017 11:14
*/
object TextManipulators {
fun getWebShareAddress(context: Context, address: String?): String {
return context.getString(R.string.web_share_address, address, AppConfig.SERVER_PORT_WEBSHARE)
}
fun getLetters(text: String = "?", length: Int): String {
val breakAfter = length - 1
val stringBuilder = StringBuilder()
for (letter in text.split(" ".toRegex()).toTypedArray()) {
if (stringBuilder.length > breakAfter) break
if (letter.isEmpty()) continue
stringBuilder.append(letter[0])
}
return stringBuilder.toString().uppercase(Locale.getDefault())
}
fun String.toFriendlySsid() = this.replace("\"", "").let {
if (it.startsWith(AppConfig.PREFIX_ACCESS_POINT))
it.substring((AppConfig.PREFIX_ACCESS_POINT.length))
else it
}.replace("_", " ")
fun toNetworkTitle(adapterName: String): Int {
val unknownInterface = R.string.unknown_interface
val associatedNames: MutableMap<String, Int> = ArrayMap()
associatedNames["wlan"] = R.string.wifi
associatedNames["p2p"] = R.string.wifi_direct
associatedNames["bt-pan"] = R.string.bluetooth
associatedNames["eth"] = R.string.ethernet
associatedNames["tun"] = R.string.vpn_interface
associatedNames["unk"] = unknownInterface
for (displayName in associatedNames.keys) if (adapterName.startsWith(displayName)) {
return associatedNames[displayName] ?: unknownInterface
}
return -1
}
fun String.toNetworkTitle(context: Context): String {
val adapterNameResource = toNetworkTitle(this)
return if (adapterNameResource == -1) this else context.getString(adapterNameResource)
}
fun NetworkInterface.toNetworkTitle(context: Context): String {
return this.displayName.toNetworkTitle(context)
}
}
| gpl-2.0 | 5e2bf84aaa0a4dc026366c9cad296cea | 38.473684 | 101 | 0.694 | 4.297994 | false | true | false | false |
rodm/teamcity-gradle-init-scripts-plugin | server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/health/ProjectInspector.kt | 1 | 2689 | /*
* Copyright 2017 Rod MacKenzie.
*
* 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.github.rodm.teamcity.gradle.scripts.server.health
import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.FEATURE_TYPE
import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME
import com.github.rodm.teamcity.gradle.scripts.server.GradleScriptsManager
import jetbrains.buildServer.serverSide.BuildTypeTemplate
import jetbrains.buildServer.serverSide.SBuildType
import jetbrains.buildServer.serverSide.SProject
class ProjectInspector(val scriptsManager: GradleScriptsManager) {
fun report(project: SProject) : List<ProjectReport> {
val result = ArrayList<ProjectReport>()
val projects = mutableListOf(project)
projects.addAll(project.projects)
for (p in projects) {
inspectProject(p, result)
}
return result
}
fun inspectProject(project: SProject, result: ArrayList<ProjectReport>) {
val buildTypes = mutableMapOf<SBuildType, String>()
val buildTemplates = mutableMapOf<BuildTypeTemplate, String>()
for (buildType in project.ownBuildTypes) {
for (feature in buildType.getBuildFeaturesOfType(FEATURE_TYPE)) {
val scriptName = feature.parameters[INIT_SCRIPT_NAME]
val scriptContent = scriptsManager.findScript(project, scriptName!!)
if (scriptContent == null) {
buildTypes.put(buildType, scriptName)
}
}
}
for (buildTemplate in project.ownBuildTypeTemplates) {
for (feature in buildTemplate.getBuildFeaturesOfType(FEATURE_TYPE)) {
val scriptName = feature.parameters[INIT_SCRIPT_NAME]
val scriptContent = scriptsManager.findScript(project, scriptName!!)
if (scriptContent == null) {
buildTemplates.put(buildTemplate, scriptName)
}
}
}
if (!buildTypes.isEmpty() || !buildTemplates.isEmpty()) {
result.add(ProjectReport(project, buildTypes, buildTemplates))
}
}
}
| apache-2.0 | 23622670c317650a8d2dbb7cb2f9de81 | 40.369231 | 87 | 0.684641 | 4.692845 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/konan/worker/Worker.kt | 1 | 9077 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* 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 konan.worker
import konan.SymbolName
import konan.internal.ExportForCppRuntime
import kotlinx.cinterop.*
/**
* Workers: theory of operations.
*
* Worker represent asynchronous and concurrent computation, usually performed by other threads
* in the same process. Object passing between workers is performed using transfer operation, so that
* object graph belongs to one worker at the time, but can be disconnected and reconnected as needed.
* See 'Object Transfer Basics' below for more details on how objects shall be transferred.
* This approach ensures that no concurrent access happens to same object, while data may flow between
* workers as needed.
*/
/**
* State of the future object.
*/
enum class FutureState(val value: Int) {
INVALID(0),
// Future is scheduled for execution.
SCHEDULED(1),
// Future result is computed.
COMPUTED(2),
// Future is cancelled.
CANCELLED(3)
}
/**
* Object Transfer Basics.
*
* Objects can be passed between threads in one of two possible modes.
*
* - CHECKED - object subgraph is checked to be not reachable by other globals or locals, and passed
* if so, otherwise an exception is thrown
* - UNCHECKED - object is blindly passed to another worker, if there are references
* left in the passing worker - it may lead to crash or program malfunction
*
* Checked mode checks if object is no longer used in passing worker, using memory-management
* specific algorithm (ARC implementation relies on trial deletion on object graph rooted in
* passed object), and throws IllegalStateException if object graph rooted in transferred object
* is reachable by some other means,
*
* Unchecked mode, intended for most performance crititcal operations, where object graph ownership
* is expected to be correct (such as application debugged earlier in CHECKED mode), just transfers
* ownership without further checks.
*
* Note, that for some cases cycle collection need to be done to ensure that dead cycles do not affect
* reachability of passed object graph. See `konan.internal.GC.collect()`.
*
*/
enum class TransferMode(val value: Int) {
CHECKED(0),
UNCHECKED(1) // USE UNCHECKED MODE ONLY IF ABSOLUTELY SURE WHAT YOU'RE DOING!!!
}
/**
* Unique identifier of the worker. Workers can be used from other workers.
*/
typealias WorkerId = Int
/**
* Unique identifier of the future. Futures can be used from other workers.
*/
typealias FutureId = Int
/**
* Class representing abstract computation, whose result may become available in the future.
*/
// TODO: make me value class!
class Future<T> internal constructor(val id: FutureId) {
/**
* Blocks execution until the future is ready.
*/
inline fun <R> consume(code: (T) -> R) =
when (state) {
FutureState.SCHEDULED, FutureState.COMPUTED -> {
val value = @Suppress("UNCHECKED_CAST", "NON_PUBLIC_CALL_FROM_PUBLIC_INLINE") (consumeFuture(id) as T)
code(value)
}
FutureState.INVALID ->
throw IllegalStateException("Future is in an invalid state: $state")
FutureState.CANCELLED ->
throw IllegalStateException("Future is cancelled")
}
fun result(): T = consume { it -> it }
val state: FutureState
get() = FutureState.values()[stateOfFuture(id)]
override fun equals(other: Any?) = (other is Future<*>) && (id == other.id)
override fun hashCode() = id
}
/**
* Class representing worker.
*/
// TODO: make me value class!
class Worker(val id: WorkerId) {
/**
* Requests termination of the worker. `processScheduledJobs` controls is we shall wait
* until all scheduled jobs processed, or terminate immediately.
*/
fun requestTermination(processScheduledJobs: Boolean = true) =
Future<FutureId>(requestTerminationInternal(id, processScheduledJobs))
/**
* Schedule a job for further execution in the worker. Schedule is a two-phase operation,
* first `producer` function is executed, and resulting object and whatever it refers to
* is analyzed for being an isolated object subgraph, if in checked mode.
* Afterwards, this disconnected object graph and `job` function pointer is being added to jobs queue
* of the selected worker. Note that `job` must not capture any state itself, so that whole state is
* explicitly stored in object produced by `producer`. Scheduled job is being executed by the worker,
* and result of such a execution is being disconnected from worker's object graph. Whoever will consume
* the future, can use result of worker's computations.
*/
@Suppress("UNUSED_PARAMETER")
fun <T1, T2> schedule(mode: TransferMode, producer: () -> T1, @VolatileLambda job: (T1) -> T2): Future<T2> =
/**
* This function is a magical operation, handled by lowering in the compiler, and replaced with call to
* scheduleImpl(worker, mode, producer, job)
* but first ensuring that `job` parameter doesn't capture any state.
*/
throw RuntimeException("Shall not be called directly")
override fun equals(other: Any?) = (other is Worker) && (id == other.id)
override fun hashCode() = id
}
/**
* Start new scheduling primitive, such as thread, to accept new tasks via `schedule` interface.
* Typically new worker may be needed for computations offload to another core, for IO it may be
* better to use non-blocking IO combined with more lightweight coroutines.
*/
fun startWorker(): Worker = Worker(startInternal())
/**
* Wait for availability of futures in the collection. Returns set with all futures which have
* value available for the consumption.
*/
fun <T> Collection<Future<T>>.waitForMultipleFutures(millis: Int): Set<Future<T>> {
val result = mutableSetOf<Future<T>>()
while (true) {
val versionToken = versionToken()
for (future in this) {
if (future.state == FutureState.COMPUTED) {
result += future
}
}
if (result.isNotEmpty()) return result
if (waitForAnyFuture(versionToken, millis)) break
}
for (future in this) {
if (future.state == FutureState.COMPUTED) {
result += future
}
}
return result
}
/**
* Creates verbatim *shallow* copy of passed object, use carefully to create disjoint object graph.
*/
fun <T> T.shallowCopy(): T = @Suppress("UNCHECKED_CAST") (shallowCopyInternal(this) as T)
/**
* Creates verbatim *deep* copy of passed object's graph, use *VERY* carefully to create disjoint object graph.
* Note that this function could potentially duplicate a lot of objects.
*/
fun <T> T.deepCopy(): T = TODO()
// Implementation details.
@konan.internal.ExportForCompiler
internal fun scheduleImpl(worker: Worker, mode: TransferMode, producer: () -> Any?,
job: CPointer<CFunction<*>>): Future<Any?> =
Future<Any?>(scheduleInternal(worker.id, mode.value, producer, job))
@SymbolName("Kotlin_Worker_startInternal")
external internal fun startInternal(): WorkerId
@SymbolName("Kotlin_Worker_requestTerminationWorkerInternal")
external internal fun requestTerminationInternal(id: WorkerId, processScheduledJobs: Boolean): FutureId
@SymbolName("Kotlin_Worker_scheduleInternal")
external internal fun scheduleInternal(
id: WorkerId, mode: Int, producer: () -> Any?, job: CPointer<CFunction<*>>): FutureId
@SymbolName("Kotlin_Worker_shallowCopyInternal")
external internal fun shallowCopyInternal(value: Any?): Any?
@SymbolName("Kotlin_Worker_stateOfFuture")
external internal fun stateOfFuture(id: FutureId): Int
@SymbolName("Kotlin_Worker_consumeFuture")
@kotlin.internal.InlineExposed
external internal fun consumeFuture(id: FutureId): Any?
@SymbolName("Kotlin_Worker_waitForAnyFuture")
external internal fun waitForAnyFuture(versionToken: Int, millis: Int): Boolean
@SymbolName("Kotlin_Worker_versionToken")
external internal fun versionToken(): Int
@ExportForCppRuntime
internal fun ThrowWorkerUnsupported(): Unit =
throw UnsupportedOperationException("Workers are not supported")
@ExportForCppRuntime
internal fun ThrowWorkerInvalidState(): Unit =
throw IllegalStateException("Illegal transfer state")
@ExportForCppRuntime
internal fun WorkerLaunchpad(function: () -> Any?) = function()
| apache-2.0 | ab8d7ac09a7ed90e5b96a5e0660c85d4 | 37.299578 | 118 | 0.704969 | 4.336837 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/extensionProperties/genericValForPrimitiveType.kt | 5 | 690 | val <T> T.valProp: T
get() = this
class A {
val int: Int = 0
val long: Long = 0.toLong()
val short: Short = 0.toShort()
val byte: Byte = 0.toByte()
val double: Double = 0.0
val float: Float = 0.0f
val char: Char = '0'
val bool: Boolean = false
operator fun invoke() {
int.valProp
long.valProp
short.valProp
byte.valProp
double.valProp
float.valProp
char.valProp
bool.valProp
}
}
fun box(): String {
0.valProp
false.valProp
'0'.valProp
0.0.valProp
0.0f.valProp
0.toByte().valProp
0.toShort().valProp
0.toLong().valProp
A()()
return "OK"
} | apache-2.0 | afdf1feb25a8a87d82ab1422c4f426bd | 16.717949 | 34 | 0.544928 | 3.270142 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/components/components.kt | 1 | 14426 | // 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.
@file:Suppress("FunctionName")
package com.intellij.ui.components
import com.intellij.BundleBase
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.*
import com.intellij.openapi.ui.ComponentWithBrowseButton.BrowseFolderActionListener
import com.intellij.openapi.ui.DialogWrapper.IdeModalityType
import com.intellij.openapi.ui.ex.MultiLineLabel
import com.intellij.openapi.util.NlsContexts.*
import com.intellij.openapi.util.NlsContexts.Checkbox
import com.intellij.openapi.util.NlsContexts.Label
import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.*
import com.intellij.util.FontUtil
import com.intellij.util.SmartList
import com.intellij.util.io.URLUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.SwingHelper
import com.intellij.util.ui.SwingHelper.addHistoryOnExpansion
import com.intellij.util.ui.UIUtil
import java.awt.*
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.HyperlinkListener
import javax.swing.text.BadLocationException
import javax.swing.text.JTextComponent
import javax.swing.text.Segment
fun Label(@Label text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false) =
Label(text, style, fontColor, bold, null)
fun Label(@Label text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false, font: Font? = null): JLabel {
val finalText = BundleBase.replaceMnemonicAmpersand(text)
val label: JLabel
if (fontColor == null) {
label = if (finalText.contains('\n')) MultiLineLabel(finalText) else JLabel(finalText)
}
else {
label = JBLabel(finalText, UIUtil.ComponentStyle.REGULAR, fontColor)
}
if (font != null) {
label.font = font
} else {
style?.let { UIUtil.applyStyle(it, label) }
if (bold) {
label.font = label.font.deriveFont(Font.BOLD)
}
}
// surrounded by space to avoid false match
if (text.contains(" -> ")) {
label.text = text.replace(" -> ", " ${FontUtil.rightArrow(label.font)} ")
}
return label
}
fun Link(@Label text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit): JComponent {
val result = ActionLink(text) { action() }
style?.let { UIUtil.applyStyle(it, result) }
return result
}
@JvmOverloads
fun noteComponent(@Label note: String, linkHandler: ((url: String) -> Unit)? = null): JComponent {
val matcher = URLUtil.HREF_PATTERN.matcher(note)
if (!matcher.find()) {
return Label(note)
}
val noteComponent = SimpleColoredComponent()
var prev = 0
do {
if (matcher.start() != prev) {
noteComponent.append(note.substring(prev, matcher.start()))
}
val linkUrl = matcher.group(1)
val tag = if (linkHandler == null) SimpleColoredComponent.BrowserLauncherTag(linkUrl) else Runnable { linkHandler(linkUrl) }
noteComponent.append(matcher.group(2), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, tag)
prev = matcher.end()
}
while (matcher.find())
LinkMouseListenerBase.installSingleTagOn(noteComponent)
if (prev < note.length) {
noteComponent.append(note.substring(prev))
}
return noteComponent
}
@JvmOverloads
fun htmlComponent(@DetailedDescription text: String = "",
font: Font? = null,
background: Color? = null,
foreground: Color? = null,
lineWrap: Boolean = false,
hyperlinkListener: HyperlinkListener? = BrowserHyperlinkListener.INSTANCE): JEditorPane {
val pane = SwingHelper.createHtmlViewer(lineWrap, font, background, foreground)
pane.text = text
pane.border = null
pane.disabledTextColor = UIUtil.getLabelDisabledForeground()
if (hyperlinkListener != null) {
pane.addHyperlinkListener(hyperlinkListener)
}
return pane
}
fun RadioButton(@RadioButton text: String): JRadioButton = JRadioButton(BundleBase.replaceMnemonicAmpersand(text))
fun CheckBox(@Checkbox text: String, selected: Boolean = false, toolTip: String? = null): JCheckBox {
val component = JCheckBox(BundleBase.replaceMnemonicAmpersand(text), selected)
toolTip?.let { component.toolTipText = it }
return component
}
@JvmOverloads
fun Panel(@BorderTitle title: String? = null, layout: LayoutManager2? = BorderLayout()): JPanel {
return Panel(title, false, layout)
}
fun Panel(@BorderTitle title: String? = null, hasSeparator: Boolean = true, layout: LayoutManager2? = BorderLayout()): JPanel {
val panel = JPanel(layout)
title?.let { setTitledBorder(it, panel, hasSeparator) }
return panel
}
fun DialogPanel(@BorderTitle title: String? = null, layout: LayoutManager2? = BorderLayout()): DialogPanel {
val panel = DialogPanel(layout)
title?.let { setTitledBorder(it, panel, hasSeparator = true) }
return panel
}
private fun setTitledBorder(@BorderTitle title: String, panel: JPanel, hasSeparator: Boolean) {
val border = when {
hasSeparator -> IdeBorderFactory.createTitledBorder(title, false)
else -> IdeBorderFactory.createTitledBorder(title, false, JBUI.insetsTop(8)).setShowLine(false)
}
panel.border = border
border.acceptMinimumSize(panel)
}
/**
* Consider using [UI DSL](http://www.jetbrains.org/intellij/sdk/docs/user_interface_components/kotlin_ui_dsl.html).
*/
@JvmOverloads
fun dialog(@DialogTitle title: String,
panel: JComponent,
resizable: Boolean = false,
focusedComponent: JComponent? = null,
okActionEnabled: Boolean = true,
project: Project? = null,
parent: Component? = null,
@DialogMessage errorText: String? = null,
modality: IdeModalityType = IdeModalityType.IDE,
createActions: ((DialogManager) -> List<Action>)? = null,
ok: (() -> List<ValidationInfo>?)? = null): DialogWrapper {
return object : MyDialogWrapper(project, parent, modality) {
init {
setTitle(title)
setResizable(resizable)
if (!okActionEnabled) {
this.okAction.isEnabled = false
}
setErrorText(errorText)
init()
}
override fun createCenterPanel() = panel
override fun createActions(): Array<out Action> {
return if (createActions == null) super.createActions() else createActions(this).toTypedArray()
}
override fun getPreferredFocusedComponent() = focusedComponent ?: super.getPreferredFocusedComponent()
override fun doOKAction() {
if (okAction.isEnabled) {
performAction(ok)
}
}
}
}
interface DialogManager {
fun performAction(action: (() -> List<ValidationInfo>?)? = null)
}
private abstract class MyDialogWrapper(project: Project?,
parent: Component?,
modality: IdeModalityType) : DialogWrapper(project, parent, true, modality), DialogManager {
override fun performAction(action: (() -> List<ValidationInfo>?)?) {
val validationInfoList = action?.invoke()
if (validationInfoList == null || validationInfoList.isEmpty()) {
super.doOKAction()
}
else {
setErrorInfoAll(validationInfoList)
clearErrorInfoOnFirstChange(validationInfoList)
}
}
private fun getTextField(info: ValidationInfo): JTextComponent? {
val component = info.component ?: return null
return when (component) {
is JTextComponent -> component
is TextFieldWithBrowseButton -> component.textField
else -> null
}
}
private fun clearErrorInfoOnFirstChange(validationInfoList: List<ValidationInfo>) {
val unchangedFields = SmartList<Component>()
for (info in validationInfoList) {
val textField = getTextField(info) ?: continue
unchangedFields.add(textField)
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
textField.document.removeDocumentListener(this)
if (unchangedFields.remove(textField) && unchangedFields.isEmpty()) {
setErrorInfoAll(emptyList())
}
}
})
}
}
}
@JvmOverloads
fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?,
component: ComponentWithBrowseButton<T>,
textField: JTextField,
@DialogTitle browseDialogTitle: String?,
fileChooserDescriptor: FileChooserDescriptor,
textComponentAccessor: TextComponentAccessor<T>,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null) {
installFileCompletionAndBrowseDialog(
project, component, textField, browseDialogTitle, null, fileChooserDescriptor, textComponentAccessor, fileChosen)
}
@JvmOverloads
fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?,
component: ComponentWithBrowseButton<T>,
textField: JTextField,
@DialogTitle browseDialogTitle: String?,
@Label browseDialogDescription: String?,
fileChooserDescriptor: FileChooserDescriptor,
textComponentAccessor: TextComponentAccessor<T>,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null) {
if (ApplicationManager.getApplication() == null) {
// tests
return
}
component.addActionListener(
object : BrowseFolderActionListener<T>(
browseDialogTitle, browseDialogDescription, component, project, fileChooserDescriptor, textComponentAccessor
) {
override fun onFileChosen(chosenFile: VirtualFile) {
if (fileChosen == null) {
super.onFileChosen(chosenFile)
}
else {
textComponentAccessor.setText(myTextComponent, fileChosen(chosenFile))
}
}
})
FileChooserFactory.getInstance().installFileCompletion(textField, fileChooserDescriptor, true,
null /* infer disposable from UI context */)
}
@JvmOverloads
fun textFieldWithHistoryWithBrowseButton(project: Project?,
@DialogTitle browseDialogTitle: String,
fileChooserDescriptor: FileChooserDescriptor,
historyProvider: (() -> List<String>)? = null,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithHistoryWithBrowseButton {
val component = TextFieldWithHistoryWithBrowseButton()
val textFieldWithHistory = component.childComponent
textFieldWithHistory.setHistorySize(-1)
textFieldWithHistory.setMinimumAndPreferredWidth(0)
if (historyProvider != null) {
addHistoryOnExpansion(textFieldWithHistory, historyProvider)
}
installFileCompletionAndBrowseDialog(
project = project,
component = component,
textField = component.childComponent.textEditor,
browseDialogTitle = browseDialogTitle,
fileChooserDescriptor = fileChooserDescriptor,
textComponentAccessor = TextComponentAccessors.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT,
fileChosen = fileChosen
)
return component
}
@JvmOverloads
fun textFieldWithBrowseButton(project: Project?,
@DialogTitle browseDialogTitle: String?,
fileChooserDescriptor: FileChooserDescriptor,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithBrowseButton {
val component = TextFieldWithBrowseButton()
installFileCompletionAndBrowseDialog(
project = project,
component = component,
textField = component.textField,
browseDialogTitle = browseDialogTitle,
fileChooserDescriptor = fileChooserDescriptor,
textComponentAccessor = TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
fileChosen = fileChosen
)
return component
}
@JvmOverloads
fun textFieldWithBrowseButton(project: Project?,
@DialogTitle browseDialogTitle: String?,
textField: JTextField,
fileChooserDescriptor: FileChooserDescriptor,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithBrowseButton {
return textFieldWithBrowseButton(project, browseDialogTitle, null, textField, fileChooserDescriptor, fileChosen)
}
@JvmOverloads
fun textFieldWithBrowseButton(project: Project?,
@DialogTitle browseDialogTitle: String?,
@Label browseDialogDescription: String?,
textField: JTextField,
fileChooserDescriptor: FileChooserDescriptor,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithBrowseButton {
val component = TextFieldWithBrowseButton(textField)
installFileCompletionAndBrowseDialog(
project = project,
component = component,
textField = component.textField,
browseDialogTitle = browseDialogTitle,
browseDialogDescription = browseDialogDescription,
fileChooserDescriptor = fileChooserDescriptor,
textComponentAccessor = TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
fileChosen = fileChosen
)
return component
}
val JPasswordField.chars: CharSequence?
get() {
val doc = document
if (doc.length == 0) {
return ""
}
else try {
return Segment().also { doc.getText(0, doc.length, it) }
}
catch (e: BadLocationException) {
return null
}
}
| apache-2.0 | a86446c1d4d99538e507ebe93d914c01 | 38.094851 | 158 | 0.664287 | 5.178033 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/config/wizard/IntelliJGroovyNewProjectWizard.kt | 1 | 11282 | // 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.groovy.config.wizard
import com.intellij.CommonBundle
import com.intellij.facet.impl.ui.libraries.LibraryCompositionSettings
import com.intellij.framework.library.FrameworkLibraryVersion
import com.intellij.framework.library.FrameworkLibraryVersionFilter
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.projectWizard.generators.IntelliJNewProjectWizardStep
import com.intellij.ide.util.EditorHelper
import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.transform
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.libraryEditor.NewLibraryEditor
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory
import com.intellij.openapi.roots.ui.distribution.*
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiManager
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.layout.*
import com.intellij.util.download.DownloadableFileSetVersions
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.config.GroovyAwareModuleBuilder
import org.jetbrains.plugins.groovy.config.GroovyConfigUtils
import org.jetbrains.plugins.groovy.config.GroovyLibraryDescription
import org.jetbrains.plugins.groovy.config.loadLatestGroovyVersions
import java.awt.KeyboardFocusManager
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.SwingUtilities
class IntelliJGroovyNewProjectWizard : BuildSystemGroovyNewProjectWizard {
override val name: String = "IntelliJ"
override val ordinal: Int = 0
override fun createStep(parent: GroovyNewProjectWizard.Step): NewProjectWizardStep = Step(parent)
class Step(parentStep: GroovyNewProjectWizard.Step) : IntelliJNewProjectWizardStep<GroovyNewProjectWizard.Step>(parentStep) {
val distributionsProperty = propertyGraph.graphProperty<DistributionInfo?> { null }
var distribution by distributionsProperty
override fun Panel.customOptions() {
row(GroovyBundle.message("label.groovy.sdk")) {
val groovyLibraryDescription = GroovyLibraryDescription()
val comboBox = DistributionComboBox(context.project, object : FileChooserInfo {
override val fileChooserTitle = GroovyBundle.message("dialog.title.select.groovy.sdk")
override val fileChooserDescription: String? = null
override val fileChooserDescriptor = groovyLibraryDescription.createFileChooserDescriptor()
override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH
})
comboBox.specifyLocationActionName = GroovyBundle.message("dialog.title.specify.groovy.sdk")
comboBox.addLoadingItem()
val pathToGroovyHome = groovyLibraryDescription.findPathToGroovyHome()
if (pathToGroovyHome != null) {
comboBox.addDistributionIfNotExists(LocalDistributionInfo(pathToGroovyHome.path))
}
loadLatestGroovyVersions(object : DownloadableFileSetVersions.FileSetVersionsCallback<FrameworkLibraryVersion>() {
override fun onSuccess(versions: List<FrameworkLibraryVersion>) = SwingUtilities.invokeLater {
versions.sortedWith(::moveUnstableVersionToTheEnd)
.map(Step::FrameworkLibraryDistributionInfo)
.forEach(comboBox::addDistributionIfNotExists)
comboBox.removeLoadingItem()
}
override fun onError(errorMessage: String) {
comboBox.removeLoadingItem()
}
})
cell(comboBox)
.validationOnApply { validateGroovySdk() }
.bindItem(distributionsProperty.transform(
{ it?.let(DistributionComboBox.Item::Distribution) ?: DistributionComboBox.Item.NoDistribution },
{ (it as? DistributionComboBox.Item.Distribution)?.info }
))
.validationOnInput { validateGroovySdkPath(it) }
.columns(COLUMNS_MEDIUM)
}.bottomGap(BottomGap.SMALL)
}
private fun ValidationInfoBuilder.validateGroovySdkPath(comboBox: DistributionComboBox): ValidationInfo? {
val localDistribution = comboBox.selectedDistribution as? LocalDistributionInfo ?: return null
val path = localDistribution.path
if (path.isEmpty()) {
return error(GroovyBundle.message("dialog.title.validation.path.should.not.be.empty"))
}
else if (isInvalidSdk(localDistribution)) {
return error(GroovyBundle.message("dialog.title.validation.path.does.not.contain.groovy.sdk"))
}
else {
return null
}
}
private fun ValidationInfoBuilder.validateGroovySdk(): ValidationInfo? {
if (isBlankDistribution(distribution)) {
if (Messages.showDialog(GroovyBundle.message("dialog.title.no.jdk.specified.prompt"),
GroovyBundle.message("dialog.title.no.jdk.specified.title"),
arrayOf(CommonBundle.getYesButtonText(), CommonBundle.getNoButtonText()), 1,
Messages.getWarningIcon()) != Messages.YES) {
return error(GroovyBundle.message("dialog.title.no.jdk.specified.error"))
}
}
if (isInvalidSdk(distribution)) {
if (Messages.showDialog(
GroovyBundle.message(
"dialog.title.validation.directory.you.specified.does.not.contain.groovy.sdk.do.you.want.to.create.project.with.this.configuration"),
GroovyBundle.message("dialog.title.validation.invalid.sdk.specified.title"),
arrayOf(CommonBundle.getYesButtonText(), CommonBundle.getNoButtonText()), 1,
Messages.getWarningIcon()) != Messages.YES) {
return error(GroovyBundle.message("dialog.title.validation.invalid.sdk.specified.error"))
}
}
return null
}
private fun isBlankDistribution(distribution: DistributionInfo?): Boolean {
return distribution == null || (distribution is LocalDistributionInfo &&
distribution.path == "")
}
private fun isInvalidSdk(distribution: DistributionInfo?): Boolean {
return distribution == null || (distribution is LocalDistributionInfo &&
GroovyConfigUtils.getInstance().getSDKVersionOrNull(distribution.path) == null)
}
override fun setupProject(project: Project) {
reportFeature()
val groovyModuleBuilder = GroovyAwareModuleBuilder().apply {
val contentRoot = FileUtil.toSystemDependentName(contentRoot)
contentEntryPath = contentRoot
name = moduleName
moduleJdk = sdk
if (addSampleCode) {
addGroovySample("src")
}
val moduleFile = Paths.get(moduleFileLocation, moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION)
moduleFilePath = FileUtil.toSystemDependentName(moduleFile.toString())
}
val librariesContainer = LibrariesContainerFactory.createContainer(project)
val compositionSettings = createCompositionSettings(project, librariesContainer)
groovyModuleBuilder.addModuleConfigurationUpdater(object : ModuleBuilder.ModuleConfigurationUpdater() {
override fun update(module: Module, rootModel: ModifiableRootModel) {
compositionSettings?.addLibraries(rootModel, mutableListOf(), librariesContainer)
}
})
groovyModuleBuilder.commit(project)
if (addSampleCode) {
openSampleCodeInEditorLater(project, contentRoot)
}
}
private fun openSampleCodeInEditorLater(project: Project, contentEntryPath: String) {
StartupManager.getInstance(project).runAfterOpened {
val file = LocalFileSystem.getInstance().refreshAndFindFileByPath("$contentEntryPath/src/Main.groovy")
if (file != null) {
runReadAction {
PsiManager.getInstance(project).findFile(file)?.let {
ApplicationManager.getApplication().invokeLater { EditorHelper.openInEditor(it) }
}
}
}
}
}
private fun reportFeature() {
val (distributionType, version) = when (val distr = distribution) {
is FrameworkLibraryDistributionInfo -> GroovyNewProjectWizardUsageCollector.DistributionType.MAVEN to distr.version.versionString
is LocalDistributionInfo -> GroovyNewProjectWizardUsageCollector.DistributionType.LOCAL to GroovyConfigUtils.getInstance().getSDKVersionOrNull(
distr.path)
else -> return
}
if (version == null) {
return
}
GroovyNewProjectWizardUsageCollector.logGroovyLibrarySelected(context, distributionType, version)
}
private fun createCompositionSettings(project: Project, container: LibrariesContainer): LibraryCompositionSettings? {
val libraryDescription = GroovyLibraryDescription()
val versionFilter = FrameworkLibraryVersionFilter.ALL
val pathProvider = { project.basePath ?: "./" }
when (val distribution = distribution) {
is FrameworkLibraryDistributionInfo -> {
val allVersions = listOf(distribution.version)
return LibraryCompositionSettings(libraryDescription, pathProvider, versionFilter, allVersions).apply {
setDownloadLibraries(true)
downloadFiles(null)
}
}
is LocalDistributionInfo -> {
val settings = LibraryCompositionSettings(libraryDescription, pathProvider, versionFilter, emptyList())
val virtualFile = VfsUtil.findFile(Path.of(distribution.path), false) ?: return settings
val keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager()
val activeWindow = keyboardFocusManager.activeWindow
val newLibraryConfiguration = libraryDescription.createLibraryConfiguration(activeWindow, virtualFile) ?: return settings
val libraryEditor = NewLibraryEditor(newLibraryConfiguration.libraryType, newLibraryConfiguration.properties)
libraryEditor.name = container.suggestUniqueLibraryName(newLibraryConfiguration.defaultLibraryName)
newLibraryConfiguration.addRoots(libraryEditor)
settings.setNewLibraryEditor(libraryEditor)
return settings
}
else -> return null
}
}
private class FrameworkLibraryDistributionInfo(val version: FrameworkLibraryVersion) : AbstractDistributionInfo() {
override val name: String = version.versionString
override val description: String? = null
}
}
} | apache-2.0 | b3644b070079705353db2fd890a6e1ee | 48.056522 | 151 | 0.733912 | 5.326723 | false | true | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt | 1 | 922 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR"
}
} | agpl-3.0 | e90344edf3126cc00787b7a4a4edb537 | 29.766667 | 91 | 0.669197 | 4.248848 | false | false | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/models/RefTagTest.kt | 1 | 7534 | package com.kickstarter.models
import com.kickstarter.libs.RefTag
import com.kickstarter.services.DiscoveryParams
import junit.framework.TestCase
import org.junit.Test
class RefTagTest : TestCase() {
@Test
fun testEquals_whenTagSame_shouldReturnTrue() {
val reftag1 = RefTag.builder().build()
val reftag2 = RefTag.builder().build()
assertEquals(reftag1, reftag2)
}
@Test
fun testEquals_whenTagDifferent_shouldReturnFalse() {
val reftag1 = RefTag.builder().tag("aTag").build()
val reftag2 = RefTag.builder().build()
assertFalse(reftag1 == reftag2)
}
@Test
fun testDefaultInit() {
val reftag = RefTag.builder().tag("aTag").build()
assertEquals(reftag.tag(), "aTag")
}
@Test
fun testDefaultToBuilder() {
val reftag = RefTag.builder().build().toBuilder().tag("thisIsATag").build()
assertEquals(reftag.tag(), "thisIsATag")
}
@Test
fun testFrom_shouldReturnReftag() {
val reftag = RefTag.from("anotherTag")
assertTrue(reftag is RefTag)
assertEquals(reftag.tag(), "anotherTag")
}
@Test
fun testActivity_returnsActivityRefTag() {
val activityRefTag = RefTag.activity()
assertTrue(activityRefTag is RefTag)
assertEquals(activityRefTag.tag(), "activity")
}
@Test
fun testActivitySample_returnsActivitySampleRefTag() {
val activitySampleRefTag = RefTag.activitySample()
assertTrue(activitySampleRefTag is RefTag)
assertEquals(activitySampleRefTag.tag(), "discovery_activity_sample")
}
@Test
fun testCategory_returnsCategoryRefTag() {
val categoryRefTag = RefTag.category()
assertTrue(categoryRefTag is RefTag)
assertEquals(categoryRefTag.tag(), "category")
}
@Test
fun testCategoryWithSort_returnsCategoryWithSortRefTag() {
val categoryWithSortRefTag = RefTag.category(DiscoveryParams.Sort.POPULAR)
assertTrue(categoryWithSortRefTag is RefTag)
assertEquals(categoryWithSortRefTag.tag(), "category_popular")
}
@Test
fun testCategoryFeatured_returnsCategroryFeaturedRefTag() {
val categoryFeatured = RefTag.categoryFeatured()
assertTrue(categoryFeatured is RefTag)
assertEquals(categoryFeatured.tag(), "category_featured")
}
@Test
fun testCity_returnsCityRefTag() {
val cityRefTag = RefTag.city()
assertTrue(cityRefTag is RefTag)
assertEquals(cityRefTag.tag(), "city")
}
@Test
fun testCollection_returnsCollectionRefTag() {
val collectRefTag = RefTag.collection(31)
assertTrue(collectRefTag is RefTag)
assertEquals(collectRefTag.tag(), "android_project_collection_tag_31")
}
@Test
fun testDashboard_returnsDashboardRefTag() {
val dashboardRefTag = RefTag.dashboard()
assertTrue(dashboardRefTag is RefTag)
assertEquals(dashboardRefTag.tag(), "dashboard")
}
@Test
fun testDeeplink_returnsDeeplinkRefTag() {
val deeplinkRefTag = RefTag.deepLink()
assertTrue(deeplinkRefTag is RefTag)
assertEquals(deeplinkRefTag.tag(), "android_deep_link")
}
@Test
fun testDiscovery_returnsDiscoveryRefTag() {
val discoveryRefTag = RefTag.discovery()
assertTrue(discoveryRefTag is RefTag)
assertEquals(discoveryRefTag.tag(), "discovery")
}
@Test
fun testPledgeInfo_returnsPledgeInfoRefTag() {
val pledgeInfoRefTag = RefTag.pledgeInfo()
assertTrue(pledgeInfoRefTag is RefTag)
assertEquals(pledgeInfoRefTag.tag(), "pledge_info")
}
@Test
fun testProjectShare_returnsProjectShareRefTag() {
val projectShare = RefTag.projectShare()
assertTrue(projectShare is RefTag)
assertEquals(projectShare.tag(), "android_project_share")
}
@Test
fun testPush_returnsPushRefTag() {
val pushRefTag = RefTag.push()
assertTrue(pushRefTag is RefTag)
assertEquals(pushRefTag.tag(), "push")
}
@Test
fun testRecommended_returnsRecommendedRefTag() {
val recommendedRefTag = RefTag.recommended()
assertTrue(recommendedRefTag is RefTag)
assertEquals(recommendedRefTag.tag(), "recommended")
}
@Test
fun testRecommendedWithSort_returnsRecommendedWithSortRefTag() {
val recommendedWithSortRefTag = RefTag.recommended(DiscoveryParams.Sort.DISTANCE)
assertTrue(recommendedWithSortRefTag is RefTag)
assertEquals(recommendedWithSortRefTag.tag(), "recommended_distance")
}
@Test
fun testSearch_returnsSearchRefTag() {
val searchRefTag = RefTag.search()
assertTrue(searchRefTag is RefTag)
assertEquals(searchRefTag.tag(), "search")
}
@Test
fun testSearchFeatured_returnsSearchFeaturedRefTag() {
val searchFeaturedRefTag = RefTag.searchFeatured()
assertTrue(searchFeaturedRefTag is RefTag)
assertEquals(searchFeaturedRefTag.tag(), "search_featured")
}
@Test
fun testSearchPopular_returnsSearchPopularRefTag() {
val searchPopularRefTag = RefTag.searchPopular()
assertTrue(searchPopularRefTag is RefTag)
assertEquals(searchPopularRefTag.tag(), "search_popular_title_view")
}
@Test
fun testSearchPopularFeatured_returnsSearchPopularFeaturedRefTag() {
val searchPopularFeaturedRefTag = RefTag.searchPopularFeatured()
assertTrue(searchPopularFeaturedRefTag is RefTag)
assertEquals(searchPopularFeaturedRefTag.tag(), "search_popular_featured")
}
@Test
fun testSocial_returnsSocialRefTag() {
val socialRefTag = RefTag.social()
assertTrue(socialRefTag is RefTag)
assertEquals(socialRefTag.tag(), "social")
}
@Test
fun testSurvey_returnsSurveyRefTag() {
val surveyRefTag = RefTag.survey()
assertTrue(surveyRefTag is RefTag)
assertEquals(surveyRefTag.tag(), "survey")
}
@Test
fun testThanks_returnsThanksRefTag() {
val thanksRefTag = RefTag.thanks()
assertTrue(thanksRefTag is RefTag)
assertEquals(thanksRefTag.tag(), "thanks")
}
@Test
fun testThanksFacebookShare_returnsThanksFacebookShareRefTag() {
val thanksFacebookShareRefTag = RefTag.thanksFacebookShare()
assertTrue(thanksFacebookShareRefTag is RefTag)
assertEquals(thanksFacebookShareRefTag.tag(), "android_thanks_facebook_share")
}
@Test
fun testThanksTwitterShare_returnsThanksTwitterShareRefTag() {
val thanksTwitterShareRefTag = RefTag.thanksTwitterShare()
assertTrue(thanksTwitterShareRefTag is RefTag)
assertEquals(thanksTwitterShareRefTag.tag(), "android_thanks_twitter_share")
}
@Test
fun testThanksShare_returnsThanksShareRefTag() {
val thanksShareRefTag = RefTag.thanksShare()
assertTrue(thanksShareRefTag is RefTag)
assertEquals(thanksShareRefTag.tag(), "android_thanks_share")
}
@Test
fun testUpdate_returnsUpdateRefTag() {
val updateRefTag = RefTag.update()
assertTrue(updateRefTag is RefTag)
assertEquals(updateRefTag.tag(), "update")
}
@Test
fun testUpdateShare_returnsUpdateShareRefTag() {
val updateShareRefTag = RefTag.updateShare()
assertTrue(updateShareRefTag is RefTag)
assertEquals(updateShareRefTag.tag(), "android_update_share")
}
}
| apache-2.0 | 33358f29db85b48f9bb84ce406cc2848 | 27.755725 | 89 | 0.683435 | 4.622086 | false | true | false | false |
ingokegel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/KtInterface.kt | 1 | 2960 | // 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.workspaceModel.codegen.deft.model
class KtInterface(
val module: KtObjModule,
parentScope: KtScope,
val nameRange: SrcRange,
val superTypes: List<KtType>,
private val predefinedKind: KtInterfaceKind?,
val annotations: KtAnnotations = KtAnnotations()
) {
val open: Boolean = annotations.flags.open
val abstract: Boolean = annotations.flags.abstract
val sealed: Boolean = annotations.flags.sealed
val name: String = nameRange.text
override fun toString(): String = name
val scope: KtScope = KtScope(parentScope, this)
val file: KtFile? get() = scope.file
lateinit var body: KtBlock
val objType: DefType? by lazy(::asObjType)
val simpleType: DefType? by lazy(::asSimpleType)
val kind: KtInterfaceKind? by lazy {
if (predefinedKind != null) return@lazy predefinedKind
if (superTypes.isEmpty()) null
else if (superTypes.any { it.classifier == "ObjBuilder" }) null
else if (superTypes.any { it.classifier == "Obj" }) ObjInterface
else if (superTypes.any { it.classifier in "WorkspaceEntity" }) WsEntityInterface()
else if (superTypes.any { it.classifier in "WorkspaceEntityWithPersistentId" }) WsEntityWithPersistentId
else superTypes.firstNotNullOfOrNull { scope.resolve(it.classifier)?.ktInterface?.kind }
}
private fun asObjType(): DefType? {
if (kind == null || kind is WsPropertyClass) return null
var base: DefType? = null
superTypes.forEach {
val superType = scope.resolve(it.classifier)
val ktInterface = superType?.ktInterface
if (ktInterface?.kind != null) {
base = ktInterface.objType!!
}
}
var topLevelClass: KtScope = scope
val outerNames = mutableListOf<String>()
do {
if (topLevelClass.isRoot) break
outerNames.add(topLevelClass.ktInterface!!.name)
topLevelClass = topLevelClass.parent!!
}
while (true)
outerNames.reversed().joinToString(".")
val name = outerNames.reversed().joinToString(".")
val type = DefType(module, name, base, this)
return type
}
private fun asSimpleType(): DefType? {
if (kind == null || kind !is WsPropertyClass) return null
var base: DefType? = null
superTypes.forEach {
val superType = scope.resolve(it.classifier)
val ktInterface = superType?.ktInterface
if (ktInterface?.kind != null) {
base = ktInterface.simpleType
}
}
var topLevelClass: KtScope = scope
val outerNames = mutableListOf<String>()
do {
if (topLevelClass.isRoot) break
outerNames.add(topLevelClass.ktInterface!!.name)
topLevelClass = topLevelClass.parent!!
}
while (true)
outerNames.reversed().joinToString(".")
val name = outerNames.reversed().joinToString(".")
val type = DefType(module, name, base, this)
return type
}
}
| apache-2.0 | 113d7f3eacaf7b7e61424ff879a36cac | 31.527473 | 120 | 0.691216 | 4.180791 | false | false | false | false |
siosio/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/ImmutableZipFileDataLoader.kt | 1 | 1184 | // 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.ide.plugins
import com.intellij.platform.util.plugins.DataLoader
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.lang.ZipFilePool.EntryResolver
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
@ApiStatus.Internal
class ImmutableZipFileDataLoader(private val resolver: EntryResolver,
private val zipPath: Path,
override val pool: ZipFilePool) : DataLoader {
override fun load(path: String): ByteArray? {
// well, path maybe specified as `/META-INF/*` in plugin descriptor and
// it is our responsibility to normalize path for ImmutableZipFile API
// do not use kotlin stdlib here
return resolver.loadZipEntry(if (path[0] == '/') path.substring(1) else path)
}
// yes, by identity - ImmutableZipFileDataLoader is created for the same Path object from plugin JARs list
override fun isExcludedFromSubSearch(jarFile: Path) = jarFile === zipPath
override fun toString() = resolver.toString()
} | apache-2.0 | c683b57b10a46cfe22ad510d3c788527 | 46.4 | 140 | 0.730574 | 4.519084 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/propertyModification.kt | 4 | 264 | // "Replace with 'new'" "true"
// WITH_RUNTIME
class A {
@Deprecated("msg", ReplaceWith("new"))
var old
get() = new
set(value) {
new = value
}
var new = ""
}
fun foo() {
val a = A()
a.<caret>old += "foo"
} | apache-2.0 | 87c2f5d605874e1733a6031e2cea0b4d | 13.722222 | 42 | 0.450758 | 3.259259 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/intrinsic/functions/factories/LongOperationFIF.kt | 3 | 5538 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.js.translate.intrinsic.functions.factories
import org.jetbrains.kotlin.js.backend.ast.JsExpression
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.js.patterns.PatternBuilder.pattern
import org.jetbrains.kotlin.js.translate.context.Namer
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsic
import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsicWithReceiverComputed
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.*
import org.jetbrains.kotlin.utils.identity as ID
// TODO Move to FunctionCallCases
object LongOperationFIF : FunctionIntrinsicFactory {
val LONG_EQUALS_ANY = pattern("Long.equals")
val LONG_BINARY_OPERATION_LONG = pattern("Long.compareTo|rangeTo|plus|minus|times|div|mod|rem|and|or|xor(Long)")
val LONG_BIT_SHIFTS = pattern("Long.shl|shr|ushr(Int)")
val LONG_BINARY_OPERATION_INTEGER = pattern("Long.compareTo|rangeTo|plus|minus|times|div|mod|rem(Int|Short|Byte)")
val LONG_BINARY_OPERATION_FLOATING_POINT = pattern("Long.compareTo|plus|minus|times|div|mod|rem(Double|Float)")
val INTEGER_BINARY_OPERATION_LONG = pattern("Int|Short|Byte.compareTo|rangeTo|plus|minus|times|div|mod|rem(Long)")
val FLOATING_POINT_BINARY_OPERATION_LONG = pattern("Double|Float.compareTo|plus|minus|times|div|mod|rem(Long)")
private val longBinaryIntrinsics =
(
listOf(
"equals" to Namer.EQUALS_METHOD_NAME,
"compareTo" to Namer.COMPARE_TO_METHOD_NAME,
"rangeTo" to "rangeTo",
"plus" to "add",
"minus" to "subtract",
"times" to "multiply",
"div" to "div",
"mod" to "modulo",
"rem" to "modulo",
"shl" to "shiftLeft",
"shr" to "shiftRight",
"ushr" to "shiftRightUnsigned",
"and" to "and",
"or" to "or",
"xor" to "xor"
).map { it.first to methodIntrinsic(it.second) }).toMap()
private val floatBinaryIntrinsics: Map<String, BaseBinaryIntrinsic> =
mapOf(
"compareTo" to BaseBinaryIntrinsic(::primitiveCompareTo),
"plus" to BaseBinaryIntrinsic(::sum),
"minus" to BaseBinaryIntrinsic(::subtract),
"times" to BaseBinaryIntrinsic(::mul),
"div" to BaseBinaryIntrinsic(::div),
"mod" to BaseBinaryIntrinsic(::mod),
"rem" to BaseBinaryIntrinsic(::mod)
)
class BaseBinaryIntrinsic(val applyFun: (left: JsExpression, right: JsExpression) -> JsExpression) :
FunctionIntrinsicWithReceiverComputed() {
override fun apply(receiver: JsExpression?, arguments: List<JsExpression>, context: TranslationContext): JsExpression {
assert(receiver != null)
assert(arguments.size == 1)
return applyFun(receiver!!, arguments.get(0))
}
}
fun methodIntrinsic(methodName: String): BaseBinaryIntrinsic =
BaseBinaryIntrinsic() { left, right -> invokeMethod(left, methodName, right) }
fun wrapIntrinsicIfPresent(intrinsic: BaseBinaryIntrinsic?, toLeft: (JsExpression) -> JsExpression, toRight: (JsExpression) -> JsExpression): FunctionIntrinsic? =
if (intrinsic != null) BaseBinaryIntrinsic() { left, right -> intrinsic.applyFun(toLeft(left), toRight(right)) } else null
override fun getIntrinsic(descriptor: FunctionDescriptor): FunctionIntrinsic? {
val operationName = descriptor.name.asString()
return when {
LONG_EQUALS_ANY.apply(descriptor) || LONG_BINARY_OPERATION_LONG.apply(descriptor) || LONG_BIT_SHIFTS.apply(descriptor) ->
longBinaryIntrinsics[operationName]
INTEGER_BINARY_OPERATION_LONG.apply(descriptor) ->
wrapIntrinsicIfPresent(longBinaryIntrinsics[operationName], { longFromInt(it) }, ID())
LONG_BINARY_OPERATION_INTEGER.apply(descriptor) ->
wrapIntrinsicIfPresent(longBinaryIntrinsics[operationName], ID(), { longFromInt(it) })
FLOATING_POINT_BINARY_OPERATION_LONG.apply(descriptor) ->
wrapIntrinsicIfPresent(floatBinaryIntrinsics[operationName], ID(), { invokeMethod(it, Namer.LONG_TO_NUMBER) })
LONG_BINARY_OPERATION_FLOATING_POINT.apply(descriptor) ->
wrapIntrinsicIfPresent(floatBinaryIntrinsics[operationName], { invokeMethod(it, Namer.LONG_TO_NUMBER) }, ID())
else ->
null
}
}
}
| apache-2.0 | e4612c1573c0d1841b942d60bf2c3180 | 52.76699 | 166 | 0.64572 | 4.487844 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinLambdaInfo.kt | 4 | 2115 | // 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.debugger.stepping.smartStepInto
import org.jetbrains.kotlin.coroutines.isSuspendLambda
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.util.OperatorNameConventions
data class KotlinLambdaInfo(
val parameterName: String,
val callerMethodOrdinal: Int,
val parameterIndex: Int,
val isSuspend: Boolean,
val isSam: Boolean,
val isNoinline: Boolean,
val isNameMangledInBytecode: Boolean,
val methodName: String,
val callerMethodInfo: CallableMemberInfo
) {
val isInline = callerMethodInfo.isInline && !isNoinline && !isSam
constructor(
callerMethodDescriptor: CallableMemberDescriptor,
parameterDescriptor: ValueParameterDescriptor,
callerMethodOrdinal: Int,
isNameMangledInBytecode: Boolean,
isSam: Boolean = false,
methodName: String = OperatorNameConventions.INVOKE.asString()
) : this(
parameterDescriptor.name.asString(),
callerMethodOrdinal,
countParameterIndex(callerMethodDescriptor, parameterDescriptor),
parameterDescriptor.isSuspendLambda,
isSam,
parameterDescriptor.isNoinline,
isNameMangledInBytecode,
methodName,
CallableMemberInfo(callerMethodDescriptor)
)
fun getLabel() =
"${callerMethodInfo.name}: $parameterName.$methodName()"
}
private fun countParameterIndex(callerMethodDescriptor: CallableMemberDescriptor, parameterDescriptor: ValueParameterDescriptor): Int {
var resultIndex = parameterDescriptor.index
if (callerMethodDescriptor.extensionReceiverParameter != null)
resultIndex++
if (callerMethodDescriptor.containingDeclaration.isInlineClass())
resultIndex++
return resultIndex
}
| apache-2.0 | ea77dd0c06da03cf9550ed9fc27e0305 | 38.166667 | 158 | 0.741844 | 5.595238 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt | 1 | 1914 | // 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.quickfix.createFromUsage.createCallable
import com.intellij.psi.util.findParentOfType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
object CreateHasNextFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? {
return diagnostic.psiElement.findParentOfType(strict = false)
}
override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? {
val diagnosticWithParameters =
DiagnosticFactory.cast(diagnostic, Errors.HAS_NEXT_MISSING, Errors.HAS_NEXT_FUNCTION_NONE_APPLICABLE)
val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE)
val returnType = TypeInfo(element.builtIns.booleanType, Variance.OUT_VARIANCE)
return FunctionInfo(
OperatorNameConventions.HAS_NEXT.asString(),
ownerType,
returnType,
modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD)
)
}
}
| apache-2.0 | 6378a84d9a53f88ad30f5c0c8b9c17fc | 52.166667 | 158 | 0.798328 | 5.010471 | false | false | false | false |
dowenliu-xyz/ketcd | ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/resolver/DnsSrvNameResolverFactory.kt | 1 | 1253 | package xyz.dowenliu.ketcd.resolver
import io.grpc.Attributes
import io.grpc.NameResolver
import io.grpc.internal.GrpcUtil
import java.net.URI
/**
* A custom name resolver factory which creates etcd name resolver
*
* create at 2017/4/9
* @author liufl
* @since 0.1.0
*/
class DnsSrvNameResolverFactory : AbstractEtcdNameResolverFactory() {
/**
* Companion object of [DnsSrvNameResolverFactory]
*/
companion object {
private const val SCHEME = "dns+srv"
private const val NAME = "dns+srv"
}
override fun newNameResolver(targetUri: URI?, params: Attributes?): NameResolver? {
if (targetUri == null) return null
if (SCHEME != targetUri.scheme) return null
val targetPath = requireNotNull(targetUri.path, { "targetPath is null." })
require(targetPath.startsWith('/'),
{ "the path component ($targetPath) of the target ($targetUri) must start with '/'" })
var name = targetPath.substring(1)
if (!name.startsWith("_etcd-server._tcp.")) name = "_etcd-server._tcp.$name"
return DnsSrvNameResolver(name, GrpcUtil.SHARED_CHANNEL_EXECUTOR)
}
override fun getDefaultScheme(): String = SCHEME
override fun name(): String = NAME
} | apache-2.0 | a7b243aac18b6d787d52c54b09ef2c4c | 32 | 102 | 0.671987 | 4.108197 | false | false | false | false |
taigua/exercism | kotlin/beer-song/src/main/kotlin/BeerSong.kt | 1 | 1036 | object BeerSong {
val lyrics = verses(99, 0)
fun verses(start: Int, end: Int) = start.downTo(end).map { verse(it) }.joinToString("\n")
fun verse(n: Int) : String {
if (n < 0 || n > 99) throw IllegalArgumentException()
return "${wallFirst(n)}, ${beer(n)}.\n${takeBeer(n)}, ${wall((n + 99) % 100)}.\n"
}
private fun wallFirst(n: Int) : String {
val s = wall(n)
return when (n) {
0 -> s.capitalize()
else -> s
}
}
private fun wall(n: Int) = "${beer(n)} on the wall"
private fun beer(n: Int) : String {
val helper = { x: Int ->
when (x) {
0 -> "no more bottles"
1 -> "1 bottle"
else -> "$x bottles"
}
}
return "${helper(n)} of beer"
}
private fun takeBeer(n: Int) = when (n) {
0 -> "Go to the store and buy some more"
1 -> "Take it down and pass it around"
else -> "Take one down and pass it around"
}
} | mit | c9e3459bb05e6948de0c8cea1faf29db | 25.589744 | 93 | 0.473938 | 3.52381 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/BodyTemperatureRecord.kt | 3 | 2656 | /*
* 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 androidx.health.connect.client.records
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.Temperature
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the body temperature of a user. Each record represents a single instantaneous body
* temperature measurement.
*/
public class BodyTemperatureRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/** Temperature in [Temperature] unit. Required field. Valid range: 0-100 Celsius degrees. */
public val temperature: Temperature,
/**
* Where on the user's body the temperature measurement was taken from. Optional field. Allowed
* values: [BodyTemperatureMeasurementLocation].
*
* @see BodyTemperatureMeasurementLocation
*/
@property:BodyTemperatureMeasurementLocations
public val measurementLocation: Int =
BodyTemperatureMeasurementLocation.MEASUREMENT_LOCATION_UNKNOWN,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is BodyTemperatureRecord) return false
if (temperature != other.temperature) return false
if (measurementLocation != other.measurementLocation) return false
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (metadata != other.metadata) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = temperature.hashCode()
result = 31 * result + measurementLocation
result = 31 * result + time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
}
| apache-2.0 | d6ca410241ae39f36882af4dfb1194e1 | 36.408451 | 99 | 0.697289 | 4.635253 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWithNullsMultipleImpl.kt | 2 | 6502 | // 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.workspaceModel.storage.entities.test.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.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildWithNullsMultipleImpl(val dataSource: ChildWithNullsMultipleData) : ChildWithNullsMultiple, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val childData: String
get() = dataSource.childData
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ChildWithNullsMultipleData?) : ModifiableWorkspaceEntityBase<ChildWithNullsMultiple, ChildWithNullsMultipleData>(
result), ChildWithNullsMultiple.Builder {
constructor() : this(ChildWithNullsMultipleData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildWithNullsMultiple is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isChildDataInitialized()) {
error("Field ChildWithNullsMultiple#childData should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildWithNullsMultiple
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.childData != dataSource.childData) this.childData = dataSource.childData
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData(true).childData = value
changedProperty.add("childData")
}
override fun getEntityClass(): Class<ChildWithNullsMultiple> = ChildWithNullsMultiple::class.java
}
}
class ChildWithNullsMultipleData : WorkspaceEntityData<ChildWithNullsMultiple>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildWithNullsMultiple> {
val modifiable = ChildWithNullsMultipleImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildWithNullsMultiple {
return getCached(snapshot) {
val entity = ChildWithNullsMultipleImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildWithNullsMultiple::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildWithNullsMultiple(childData, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildWithNullsMultipleData
if (this.entitySource != other.entitySource) return false
if (this.childData != other.childData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildWithNullsMultipleData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 6e8547b27f4296b18d398b9bbde2e235 | 32.515464 | 137 | 0.739772 | 5.369116 | false | false | false | false |
GunoH/intellij-community | platform/statistics/src/com/intellij/internal/statistic/service/fus/collectors/FUStateUsagesLogger.kt | 2 | 7866 | // 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", "UnstableApiUsage", "ReplacePutWithAssignment")
package com.intellij.internal.statistic.service.fus.collectors
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.EventLogSystemEvents
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.StatisticsEventLogProviderUtil.getEventLogProvider
import com.intellij.internal.statistic.eventLog.StatisticsEventLogger
import com.intellij.internal.statistic.eventLog.fus.FeatureUsageLogger.logState
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.future.asDeferred
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.concurrency.asDeferred
/**
* Called by a scheduler once a day and records IDE/project state. <br></br>
*
* **Don't** use it directly unless absolutely necessary.
* Implement [ApplicationUsagesCollector] or [ProjectUsagesCollector] instead.
*
* To record IDE events (e.g. invoked action, opened dialog) use [CounterUsagesCollector]
*/
@Service(Service.Level.APP)
@Internal
class FUStateUsagesLogger private constructor(): UsagesCollectorConsumer {
// https://github.com/Kotlin/kotlinx.coroutines/issues/2603#issuecomment-808859170
private val logAppStateRequests = MutableSharedFlow<Boolean?>()
private val logProjectStateRequests = MutableSharedFlow<Project?>()
init {
ApplicationManager.getApplication().coroutineScope.launch {
logAppStateRequests
.filterNotNull()
.collectLatest(::logApplicationStates)
}
ApplicationManager.getApplication().coroutineScope.launch {
logProjectStateRequests
.filterNotNull()
.collectLatest { project ->
coroutineScope {
val recorderLoggers = HashMap<String, StatisticsEventLogger>()
for (usagesCollector in ProjectUsagesCollector.getExtensions(this@FUStateUsagesLogger)) {
if (!getPluginInfo(usagesCollector.javaClass).isDevelopedByJetBrains()) {
@Suppress("removal", "DEPRECATION")
LOG.warn("Skip '${usagesCollector.groupId}' because its registered in a third-party plugin")
continue
}
launch {
val metrics = usagesCollector.getMetrics(project, null)
logMetricsOrError(project = project,
recorderLoggers = recorderLoggers,
usagesCollector = usagesCollector,
metrics = metrics.asDeferred().await() ?: emptySet())
}
}
}
}
}
}
companion object {
private val LOG = Logger.getInstance(FUStateUsagesLogger::class.java)
fun getInstance(): FUStateUsagesLogger = ApplicationManager.getApplication().getService(FUStateUsagesLogger::class.java)
private suspend fun logMetricsOrError(project: Project?,
recorderLoggers: MutableMap<String, StatisticsEventLogger>,
usagesCollector: FeatureUsagesCollector,
metrics: Set<MetricEvent>) {
var group = usagesCollector.group
if (group == null) {
@Suppress("removal", "DEPRECATION")
group = EventLogGroup(usagesCollector.groupId, usagesCollector.version)
}
val recorder = group.recorder
var logger = recorderLoggers.get(recorder)
if (logger == null) {
logger = getEventLogProvider(recorder).logger
recorderLoggers.put(recorder, logger)
}
try {
logUsagesAsStateEvents(project = project, group = group, metrics = metrics, logger = logger)
}
catch (e: Throwable) {
if (project != null && project.isDisposed) {
return
}
val data = FeatureUsageData().addProject(project)
@Suppress("UnstableApiUsage")
logger.logAsync(group, EventLogSystemEvents.STATE_COLLECTOR_FAILED, data.build(), true).asDeferred().join()
}
}
private suspend fun logUsagesAsStateEvents(project: Project?,
group: EventLogGroup,
metrics: Set<MetricEvent>,
logger: StatisticsEventLogger) {
if (project != null && project.isDisposed) {
return
}
coroutineScope {
if (!metrics.isEmpty()) {
val groupData = addProject(project)
for (metric in metrics) {
val data = mergeWithEventData(groupData, metric.data)
val eventData = data?.build() ?: emptyMap()
launch {
logger.logAsync(group, metric.eventId, eventData, true).asDeferred().join()
}
}
}
launch {
logger.logAsync(group, EventLogSystemEvents.STATE_COLLECTOR_INVOKED, FeatureUsageData().addProject(project).build(), true).join()
}
}
}
private fun addProject(project: Project?): FeatureUsageData? = if (project == null) null else FeatureUsageData().addProject(project)
fun mergeWithEventData(groupData: FeatureUsageData?, data: FeatureUsageData?): FeatureUsageData? {
if (data == null) {
return groupData
}
val newData = groupData?.copy() ?: FeatureUsageData()
newData.merge(data, "event_")
return newData
}
/**
* Low-level API to record IDE/project state.
* Using it directly is error-prone because you'll need to think about metric baseline.
* **Don't** use it unless absolutely necessary.
*
* Consider using counter events [CounterUsagesCollector] or
* state events recorded by a scheduler [ApplicationUsagesCollector] or [ProjectUsagesCollector]
*/
fun logStateEvent(group: EventLogGroup, event: String, data: FeatureUsageData) {
logState(group, event, data.build())
logState(group, EventLogSystemEvents.STATE_COLLECTOR_INVOKED)
}
}
suspend fun logProjectStates(project: Project) {
logProjectStateRequests.emit(project)
logProjectStateRequests.emit(null)
}
suspend fun logApplicationStates() {
logAppStateRequests.emit(false)
logAppStateRequests.emit(null)
}
suspend fun logApplicationStatesOnStartup() {
logAppStateRequests.emit(true)
logAppStateRequests.emit(null)
}
private suspend fun logApplicationStates(onStartup: Boolean) {
coroutineScope {
val recorderLoggers = HashMap<String, StatisticsEventLogger>()
val collectors = ApplicationUsagesCollector.getExtensions(this@FUStateUsagesLogger, onStartup)
for (usagesCollector in collectors) {
if (!getPluginInfo(usagesCollector.javaClass).isDevelopedByJetBrains()) {
@Suppress("removal", "DEPRECATION")
LOG.warn("Skip '${usagesCollector.groupId}' because its registered in a third-party plugin")
continue
}
launch {
logMetricsOrError(project = null,
recorderLoggers = recorderLoggers,
usagesCollector = usagesCollector,
metrics = usagesCollector.getMetricsAsync())
}
}
}
}
} | apache-2.0 | 6bc09c8e2b6302a9bd9b3696aff93dbd | 38.93401 | 139 | 0.668446 | 5.21618 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CanBeParameterInspection.kt | 2 | 6821 | // 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.inspections
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.quickfix.RemoveValVarFromParameterFix
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators
import org.jetbrains.kotlin.idea.search.usagesSearch.getAccessorNames
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
internal val CONSTRUCTOR_VAL_VAR_MODIFIERS = listOf(
OPEN_KEYWORD, FINAL_KEYWORD, OVERRIDE_KEYWORD,
PUBLIC_KEYWORD, INTERNAL_KEYWORD, PROTECTED_KEYWORD, PRIVATE_KEYWORD,
LATEINIT_KEYWORD
)
class CanBeParameterInspection : AbstractKotlinInspection() {
private fun PsiReference.usedAsPropertyIn(klass: KtClass): Boolean {
if (this !is KtSimpleNameReference) return true
val nameExpression = element
// receiver.x
val parent = element.parent
if (parent is KtQualifiedExpression) {
if (parent.selectorExpression == element) return true
}
// x += something
if (parent is KtBinaryExpression &&
parent.left == element &&
KtPsiUtil.isAssignment(parent)
) return true
// init / constructor / non-local property?
var parameterUser: PsiElement = nameExpression
do {
parameterUser = PsiTreeUtil.getParentOfType(
parameterUser, KtProperty::class.java, KtPropertyAccessor::class.java,
KtClassInitializer::class.java,
KtFunction::class.java, KtObjectDeclaration::class.java,
KtSuperTypeCallEntry::class.java
) ?: return true
} while (parameterUser is KtProperty && parameterUser.isLocal)
return when (parameterUser) {
is KtProperty -> parameterUser.containingClassOrObject !== klass
is KtClassInitializer -> parameterUser.containingDeclaration !== klass
is KtFunction, is KtObjectDeclaration, is KtPropertyAccessor -> true
is KtSuperTypeCallEntry -> parameterUser.getStrictParentOfType<KtClassOrObject>() !== klass
else -> true
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return parameterVisitor(fun(parameter) {
// Applicable to val / var parameters of a class / object primary constructors
val valOrVar = parameter.valOrVarKeyword ?: return
val name = parameter.name ?: return
if (parameter.hasModifier(OVERRIDE_KEYWORD) || parameter.hasModifier(ACTUAL_KEYWORD)) return
if (parameter.annotationEntries.isNotEmpty()) return
val constructor = parameter.parent.parent as? KtPrimaryConstructor ?: return
val klass = constructor.getContainingClassOrObject() as? KtClass ?: return
if (klass.isData()) return
val useScope = parameter.useScope
val restrictedScope = if (useScope is GlobalSearchScope) {
val psiSearchHelper = PsiSearchHelper.getInstance(parameter.project)
for (accessorName in parameter.getAccessorNames()) {
when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(accessorName, useScope, null, null)) {
ZERO_OCCURRENCES -> {
} // go on
else -> return // accessor in use: should remain a property
}
}
// TOO_MANY_OCCURRENCES: too expensive
// ZERO_OCCURRENCES: unused at all, reported elsewhere
if (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null) != FEW_OCCURRENCES) return
KotlinSourceFilterScope.projectSources(useScope, parameter.project)
} else useScope
// Find all references and check them
val references = ReferencesSearch.search(parameter, restrictedScope)
if (references.none()) return
if (references.any { it.element.parent is KtCallableReferenceExpression || it.usedAsPropertyIn(klass) }) return
holder.registerProblem(
valOrVar,
KotlinBundle.message("constructor.parameter.is.never.used.as.a.property"),
RemoveValVarFix(parameter)
)
})
}
class RemoveValVarFix(private val fix : RemoveValVarFromParameterFix) : LocalQuickFix {
constructor(parameter: KtParameter): this(RemoveValVarFromParameterFix(parameter))
override fun getName() = fix.text
override fun getFamilyName() = fix.familyName
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val parameter = descriptor.psiElement.getParentOfType<KtParameter>(strict = true) ?: return
parameter.valOrVarKeyword?.delete()
// Delete visibility / open / final / lateinit, if any
// Retain annotations / vararg
// override should never be here
val modifierList = parameter.modifierList ?: return
for (modifier in CONSTRUCTOR_VAL_VAR_MODIFIERS) {
modifierList.getModifier(modifier)?.delete()
}
}
override fun getFileModifierForPreview(target: PsiFile): FileModifier? {
val newFix = fix.getFileModifierForPreview(target) as? RemoveValVarFromParameterFix
return newFix?.let(::RemoveValVarFix)
}
}
}
| apache-2.0 | 28c5e1e3784b343b687327095c3985ae | 48.788321 | 132 | 0.696965 | 5.478715 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/core/OptionalParametersHelper.kt | 4 | 6347 | // Copyright 2000-2022 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.core
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import java.util.*
object OptionalParametersHelper {
fun detectArgumentsToDropForDefaults(
resolvedCall: ResolvedCall<out CallableDescriptor>,
project: Project,
canDrop: (ValueArgument) -> Boolean = { true }
): Collection<ValueArgument> {
if (!resolvedCall.isReallySuccess()) return emptyList()
val descriptor = resolvedCall.resultingDescriptor
val parameterToDefaultValue = descriptor.valueParameters
.mapNotNull { parameter -> defaultParameterValue(parameter, project)?.let { parameter to it } }
.toMap()
if (parameterToDefaultValue.isEmpty()) return emptyList()
//TODO: drop functional literal out of parenthesis too
val arguments = resolvedCall.call.getValueArgumentsInParentheses()
val argumentsToDrop = ArrayList<ValueArgument>()
for (argument in arguments.asReversed()) {
if (!canDrop(argument) || !argument.matchesDefault(resolvedCall, parameterToDefaultValue)) {
if (!argument.isNamed()) break else continue // for a named argument we can try to drop arguments before it as well
}
argumentsToDrop.add(argument)
}
return argumentsToDrop
}
private fun ValueArgument.matchesDefault(
resolvedCall: ResolvedCall<out CallableDescriptor>,
parameterToDefaultValue: Map<ValueParameterDescriptor, DefaultValue>
): Boolean {
val parameter = resolvedCall.getParameterForArgument(this) ?: return false
val defaultValue = parameterToDefaultValue[parameter] ?: return false
val expression = defaultValue.substituteArguments(resolvedCall)
val argumentExpression = getArgumentExpression()!!
return argumentExpression.text == expression.text //TODO
}
private fun DefaultValue.substituteArguments(resolvedCall: ResolvedCall<out CallableDescriptor>): KtExpression {
if (parameterUsages.isEmpty()) return expression
val key = Key<KtExpression>("SUBSTITUTION")
for ((parameter, usages) in parameterUsages) {
val resolvedArgument = resolvedCall.valueArguments[parameter]!!
if (resolvedArgument is ExpressionValueArgument) {
val argument = resolvedArgument.valueArgument!!.getArgumentExpression()!!
usages.forEach { it.putCopyableUserData(key, argument) }
}
//TODO: vararg
}
var expressionCopy = expression.copied()
expression.forEachDescendantOfType<KtExpression> { it.putCopyableUserData(key, null) }
val replacements = ArrayList<Pair<KtExpression, KtExpression>>()
expressionCopy.forEachDescendantOfType<KtExpression> {
val replacement = it.getCopyableUserData(key)
if (replacement != null) {
replacements.add(it to replacement)
}
}
for ((expression, replacement) in replacements) {
val replaced = expression.replace(replacement) as KtExpression
if (expression == expressionCopy) {
expressionCopy = replaced
}
}
return expressionCopy
}
data class DefaultValue(
val expression: KtExpression,
val parameterUsages: Map<ValueParameterDescriptor, Collection<KtExpression>>
)
fun defaultParameterValueExpression(parameter: ValueParameterDescriptor, project: Project): KtExpression? {
if (!parameter.hasDefaultValue()) return null
if (!parameter.declaresDefaultValue()) {
val overridden = parameter.overriddenDescriptors.firstOrNull { it.hasDefaultValue() } ?: return null
return defaultParameterValueExpression(overridden, project)
}
//TODO: parameter in overriding method!
//TODO: it's a temporary code while we don't have default values accessible from descriptors
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, parameter)?.navigationElement as? KtParameter
return declaration?.defaultValue
}
//TODO: handle imports
//TODO: handle implicit receivers
fun defaultParameterValue(parameter: ValueParameterDescriptor, project: Project): DefaultValue? {
val expression = defaultParameterValueExpression(parameter, project) ?: return null
val allParameters = parameter.containingDeclaration.valueParameters.toSet()
val parameterUsages = HashMap<ValueParameterDescriptor, MutableCollection<KtExpression>>()
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
expression.forEachDescendantOfType<KtSimpleNameExpression> {
val target = bindingContext[BindingContext.REFERENCE_TARGET, it]
if (target is ValueParameterDescriptor && target in allParameters) {
parameterUsages.getOrPut(target) { ArrayList() }.add(it)
}
}
return DefaultValue(expression, parameterUsages)
}
} | apache-2.0 | 2de6bfd587094cda59d29b6eee0ffd71 | 44.342857 | 158 | 0.723334 | 5.577329 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt | 1 | 5787 | // 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.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcess
import com.intellij.debugger.impl.DebuggerUtilsAsync
import com.intellij.debugger.jdi.VirtualMachineProxyImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.containers.ConcurrentFactoryMap
import com.sun.jdi.Location
import com.sun.jdi.ReferenceType
import com.sun.jdi.VirtualMachine
import org.jetbrains.kotlin.codegen.inline.SMAP
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.util.getLineCount
import org.jetbrains.kotlin.idea.core.util.getLineStartOffset
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.concurrent.ConcurrentMap
fun isInlineFunctionLineNumber(file: VirtualFile, lineNumber: Int, project: Project): Boolean {
if (ProjectRootsUtil.isProjectSourceFile(project, file)) {
val linesInFile = file.toPsiFile(project)?.getLineCount() ?: return false
return lineNumber > linesInFile
}
return true
}
fun createWeakBytecodeDebugInfoStorage(): ConcurrentMap<BinaryCacheKey, SMAP?> {
return ConcurrentFactoryMap.createWeakMap<BinaryCacheKey, SMAP?> { key ->
val bytes = ClassBytecodeFinder(key.project, key.jvmName, key.file).find() ?: return@createWeakMap null
return@createWeakMap readDebugInfo(bytes)
}
}
data class BinaryCacheKey(val project: Project, val jvmName: JvmClassName, val file: VirtualFile)
fun getLocationsOfInlinedLine(type: ReferenceType, position: SourcePosition, sourceSearchScope: GlobalSearchScope): List<Location> {
val line = position.line
val file = position.file
val project = position.file.project
val lineStartOffset = file.getLineStartOffset(line) ?: return listOf()
val element = file.findElementAt(lineStartOffset) ?: return listOf()
val ktElement = element.parents.firstIsInstanceOrNull<KtElement>() ?: return listOf()
val isInInline = runReadAction { element.parents.any { it is KtFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) } }
if (!isInInline) {
// Lambdas passed to crossinline arguments are inlined when they are used in non-inlined lambdas
val isInCrossinlineArgument = isInCrossinlineArgument(ktElement)
if (!isInCrossinlineArgument) {
return listOf()
}
}
val lines = inlinedLinesNumbers(line + 1, position.file.name, FqName(type.name()), type.sourceName(), project, sourceSearchScope)
return lines.flatMap { DebuggerUtilsAsync.locationsOfLineSync(type, it) }
}
fun isInCrossinlineArgument(ktElement: KtElement): Boolean {
val argumentFunctions = runReadAction {
ktElement.parents.filter {
when (it) {
is KtFunctionLiteral -> it.parent is KtLambdaExpression &&
(it.parent.parent is KtValueArgument || it.parent.parent is KtLambdaArgument)
is KtFunction -> it.parent is KtValueArgument
else -> false
}
}.filterIsInstance<KtFunction>()
}
val bindingContext = ktElement.analyze(BodyResolveMode.PARTIAL)
return argumentFunctions.any {
val argumentDescriptor = InlineUtil.getInlineArgumentDescriptor(it, bindingContext)
argumentDescriptor?.isCrossinline ?: false
}
}
private fun inlinedLinesNumbers(
inlineLineNumber: Int, inlineFileName: String,
destinationTypeFqName: FqName, destinationFileName: String,
project: Project, sourceSearchScope: GlobalSearchScope
): List<Int> {
val internalName = destinationTypeFqName.asString().replace('.', '/')
val jvmClassName = JvmClassName.byInternalName(internalName)
val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName)
?: return listOf()
val virtualFile = file.virtualFile ?: return listOf()
val smapData = KotlinDebuggerCaches.getSmapCached(project, jvmClassName, virtualFile) ?: return listOf()
val mappingsToInlinedFile = smapData.fileMappings.filter { it.name == inlineFileName }
val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings }
return mappingIntervals.asSequence().filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) }
.map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }.filter { line -> line != -1 }.toList()
}
@Volatile
var emulateDexDebugInTests: Boolean = false
fun DebugProcess.isDexDebug(): Boolean {
val virtualMachine = (this.virtualMachineProxy as? VirtualMachineProxyImpl)?.virtualMachine
return virtualMachine.isDexDebug()
}
fun VirtualMachine?.isDexDebug(): Boolean {
// TODO: check other machine names
return (emulateDexDebugInTests && ApplicationManager.getApplication().isUnitTestMode) || this?.name() == "Dalvik"
}
| apache-2.0 | 47c71c50705def324794c4925d05e62e | 43.515385 | 158 | 0.765682 | 4.611155 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemFilter.kt | 1 | 3777 | // 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.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel.renderSeverity
import com.intellij.util.ui.tree.TreeUtil.promiseExpandAll
import org.jetbrains.annotations.Nls
internal class ProblemFilter(val state: ProblemsViewState) : (Problem) -> Boolean {
override fun invoke(problem: Problem): Boolean {
val highlighting = problem as? HighlightingProblem ?: return true
return !(state.hideBySeverity.contains(highlighting.severity))
}
}
internal class SeverityFiltersActionGroup : DumbAware, ActionGroup() {
override fun getChildren(event: AnActionEvent?): Array<AnAction> {
val project = event?.project ?: return AnAction.EMPTY_ARRAY
if (project.isDisposed) return AnAction.EMPTY_ARRAY
val panel = ProblemsView.getSelectedPanel(project) as? HighlightingPanel ?: return AnAction.EMPTY_ARRAY
val severities = SeverityRegistrar.getSeverityRegistrar(project).allSeverities.reversed()
.filter { it != HighlightSeverity.INFO && it > HighlightSeverity.INFORMATION && it < HighlightSeverity.ERROR }
val (mainSeverities, otherSeverities) = severities.partition { it >= HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING }
val actions = mainSeverities.mapTo(ArrayList<AnAction>()) {
SeverityFilterAction(ProblemsViewBundle.message("problems.view.highlighting.severity.show", renderSeverity(it)), it.myVal, panel)
}
actions.add(OtherSeveritiesFilterAction(otherSeverities.map { it.myVal }, panel))
return actions.toTypedArray()
}
}
private abstract class SeverityFilterActionBase(name: @Nls String, protected val panel: HighlightingPanel): DumbAwareToggleAction(name) {
abstract fun updateState(selected: Boolean): Boolean
override fun setSelected(event: AnActionEvent, selected: Boolean) {
val changed = updateState(selected)
if (changed) {
val wasEmpty = panel.tree.isEmpty
panel.state.intIncrementModificationCount()
panel.treeModel.structureChanged(null)
panel.powerSaveStateChanged()
// workaround to expand a root without handle
if (wasEmpty) {
promiseExpandAll(panel.tree)
}
}
}
}
private class OtherSeveritiesFilterAction(
private val severities: Collection<Int>,
panel: HighlightingPanel
): SeverityFilterActionBase(ProblemsViewBundle.message("problems.view.highlighting.other.problems.show"), panel) {
override fun isSelected(event: AnActionEvent): Boolean {
val state = panel.state.hideBySeverity
return !severities.all { state.contains(it) }
}
override fun updateState(selected: Boolean): Boolean {
val state = panel.state.hideBySeverity
return when {
selected -> state.removeAll(severities)
else -> state.addAll(severities)
}
}
}
private class SeverityFilterAction(@Nls name: String, val severity: Int, panel: HighlightingPanel): SeverityFilterActionBase(name, panel) {
override fun isSelected(event: AnActionEvent) = !panel.state.hideBySeverity.contains(severity)
override fun updateState(selected: Boolean): Boolean {
val state = panel.state.hideBySeverity
return when {
selected -> state.remove(severity)
else -> state.add(severity)
}
}
}
| apache-2.0 | 3c6d4f1111f48ddec4a59c3f89bffa05 | 43.435294 | 139 | 0.769394 | 4.517943 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InnerClassConversion.kt | 6 | 1825 | // 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.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.isLocalClass
import org.jetbrains.kotlin.nj2k.tree.JKClass
import org.jetbrains.kotlin.nj2k.tree.JKOtherModifierElement
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
import org.jetbrains.kotlin.nj2k.tree.OtherModifier
class InnerClassConversion(context : NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKClass) return recurse(element)
return recurseArmed(element, element)
}
private fun recurseArmed(element: JKTreeElement, outer: JKClass): JKTreeElement {
return applyRecursive(element, outer, ::applyArmed)
}
private fun applyArmed(element: JKTreeElement, outer: JKClass): JKTreeElement {
if (element !is JKClass) return recurseArmed(element, outer)
if (element.classKind == JKClass.ClassKind.COMPANION) return recurseArmed(element, outer)
if (element.isLocalClass()) return recurseArmed(element, outer)
val static = element.otherModifierElements.find { it.otherModifier == OtherModifier.STATIC }
if (static != null) {
element.otherModifierElements -= static
} else if (element.classKind != JKClass.ClassKind.INTERFACE &&
outer.classKind != JKClass.ClassKind.INTERFACE &&
element.classKind != JKClass.ClassKind.ENUM
) {
element.otherModifierElements += JKOtherModifierElement(OtherModifier.INNER)
}
return recurseArmed(element, element)
}
} | apache-2.0 | 081c6db5a033be4a581b8cbb8dea2ada | 47.052632 | 158 | 0.738082 | 4.39759 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ReplaceWithArrayCallInAnnotationFix.kt | 4 | 2189 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinPsiOnlyQuickFixAction
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.PsiElementSuitabilityCheckers
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class ReplaceWithArrayCallInAnnotationFix(argument: KtExpression) : KotlinPsiOnlyQuickFixAction<KtExpression>(argument) {
override fun getText() = KotlinBundle.message("replace.with.array.call")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val argument = element?.getParentOfType<KtValueArgument>(false) ?: return
val spreadElement = argument.getSpreadElement()
if (spreadElement != null)
spreadElement.delete()
else
surroundWithArrayLiteral(argument)
}
private fun surroundWithArrayLiteral(argument: KtValueArgument) {
val argumentExpression = argument.getArgumentExpression() ?: return
val factory = KtPsiFactory(argumentExpression)
val surrounded = factory.createExpressionByPattern("[$0]", argumentExpression)
argumentExpression.replace(surrounded)
}
companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement as? KtExpression ?: return emptyList()
return listOf(ReplaceWithArrayCallInAnnotationFix(element))
}
}
}
| apache-2.0 | 27c33d9bec6c50b37d8b49bb61685d71 | 45.574468 | 128 | 0.769758 | 5.043779 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/MoveLesson.kt | 3 | 2415 | // 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 training.learn.lesson.general
import training.dsl.LessonContext
import training.dsl.LessonSample
import training.dsl.LessonUtil
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
class MoveLesson(private val caretText: String, private val sample: LessonSample)
: KLesson("Move", LessonsBundle.message("move.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit
get() = {
prepareSample(sample)
actionTask("MoveLineDown") {
restoreIfModifiedOrMoved(sample)
LessonsBundle.message("move.pull.down", action(it))
}
actionTask("MoveLineUp") {
restoreIfModifiedOrMoved()
LessonsBundle.message("move.pull.up", action(it))
}
caret(caretText)
task("MoveStatementUp") {
restoreIfModifiedOrMoved()
text(LessonsBundle.message("move.whole.method.up", action(it)))
trigger(it, { editor.document.text }, { before, now ->
checkSwapMoreThan2Lines(before, now)
})
test { actions(it) }
}
actionTask("MoveStatementDown") {
restoreIfModifiedOrMoved()
LessonsBundle.message("move.whole.method.down", action(it))
}
}
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("help.lines.of.code"),
LessonUtil.getHelpLink("working-with-source-code.html#editor_lines_code_blocks")),
)
}
fun checkSwapMoreThan2Lines(before: String, now: String): Boolean {
val beforeLines = before.split("\n")
val nowLines = now.split("\n")
if (beforeLines.size != nowLines.size) {
return false
}
val change = beforeLines.size - commonPrefix(beforeLines, nowLines) - commonSuffix(beforeLines, nowLines)
return change >= 4
}
private fun <T> commonPrefix(list1: List<T>, list2: List<T>): Int {
val size = Integer.min(list1.size, list2.size)
for (i in 0 until size) {
if (list1[i] != list2[i])
return i
}
return size
}
private fun <T> commonSuffix(list1: List<T>, list2: List<T>): Int {
val size = Integer.min(list1.size, list2.size)
for (i in 0 until size) {
if (list1[list1.size - i - 1] != list2[list2.size - i - 1])
return i
}
return size
}
| apache-2.0 | 2f59582fe5a95cf2a22c9269afc27a38 | 32.082192 | 140 | 0.679503 | 3.79717 | false | false | false | false |
GluigiPP/KotlinChat | src/main/kotlin/com/gluigip/kotlin/kotlinchat/ui/component/ChatComponent.kt | 1 | 3186 | package com.gluigip.kotlin.kotlinchat.ui.component
import com.gluigip.kotlin.kotlinchat.logic.ChatBroadcaster
import com.gluigip.kotlin.kotlinchat.model.Message
import com.gluigip.kotlin.kotlinchat.ui.logic.Session
import com.gluigip.kotlin.kotlinchat.ui.utils.*
import com.vaadin.event.ShortcutAction
import com.vaadin.shared.ui.ContentMode
import com.vaadin.spring.annotation.UIScope
import com.vaadin.ui.Button
import com.vaadin.ui.themes.ValoTheme
import org.vaadin.viritin.fields.MTextField
import org.vaadin.viritin.label.MLabel
import org.vaadin.viritin.layouts.MPanel
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Named
/**
* Created by gianluigi.pierini on 07/07/2017.
*/
@Named
@UIScope
open class ChatComponent(val broadcaster: ChatBroadcaster, val session: Session) : ExtendedCustomComponent() {
private val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.MEDIUM)
private lateinit var chatBox: MPanel
private lateinit var chatLabel: MLabel
private var chatContent = StringBuilder()
private lateinit var input: MTextField
init {
setSizeFull()
panel("Chat") {
withFullHeight().withFullWidth()
verticalLayout {
withFullWidth().withFullHeight()
chatBox = panel {
withFullHeight().withFullWidth().withStyleName(ValoTheme.PANEL_WELL)
verticalLayout {
withFullWidth()
chatLabel = label("").withFullWidth().withContentMode(ContentMode.HTML)
}
}
expand(chatBox)
horizontalLayout {
input = textField { focus() }.withPlaceholder("New message")
expand(input)
button("Enviar") {
addClickListener({ _: Button.ClickEvent? -> sendMessage() })
}.withClickShortcut(ShortcutAction.KeyCode.ENTER).withStyleName(ValoTheme.BUTTON_PRIMARY)
}
}
}
initChatBox(broadcaster.registerListener { receiveMessage(it) })
}
private fun sendMessage() {
if (input.value.isEmpty()) {
return
}
broadcaster.sendMessage(Message(input.value, session.user!!))
input.value = ""
}
private fun receiveMessage(message: Message) {
ui.access {
chatLabel.value = updateChatContent(message)
chatBox.scrollTop = Integer.MAX_VALUE
}
}
private fun initChatBox(messages: List<Message>) {
messages.forEach { updateChatContent(it) }
chatLabel.value = chatContent.toString()
chatBox.scrollTop = Integer.MAX_VALUE
}
private fun updateChatContent(message: Message): String {
chatContent.append("""<p style="margin: 0px; font-weight: bold; font-size: 13px;">
${message.date.format(formatter)} - ${message.user.displayName}:
</p> ${message.text}""")
return chatContent.toString()
}
} | apache-2.0 | fa95f66b4950a4377d374b22568ac502 | 32.904255 | 110 | 0.634652 | 4.394483 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/data/network/retrofit/response/enity/Video.kt | 1 | 1695 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.data.network.retrofit.response.enity
import android.annotation.SuppressLint
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/08/30
* Contact with <[email protected]>
* ================================================
*/
@SuppressLint("ParcelCreator")
@Parcelize
open class Video(var _id: String?, var createdAt: String?, var desc: String?, var publishedAt: String?,
var source: String?, var type: String?, var url: String?,
var isUsed: Boolean = false, var who: String?, var image: Image?) : Parcelable {
/**
* _id : 59906c33421aa90f4919c7e1
* createdAt : 2017-08-13T23:11:47.518Z
* desc : DC最快的闪电侠,在你看标题时就已跑到银河尽头
* publishedAt : 2017-08-14T17:04:50.266Z
* source : chrome
* type : 休息视频
* url : http://www.bilibili.com/video/av13207512/
* used : true
* who : LHF
*/
}
| apache-2.0 | 02a3f5a24d45e8377a24c58940c20471 | 34.76087 | 103 | 0.632827 | 3.680089 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInspection/Java9ReflectionClassVisibilityTest.kt | 1 | 3152 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.java.codeInspection
import com.intellij.JavaTestUtil
import com.intellij.codeInspection.reflectiveAccess.Java9ReflectionClassVisibilityInspection
import com.intellij.openapi.util.io.FileUtil
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.MAIN
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import org.intellij.lang.annotations.Language
/**
* @author Pavel.Dolgov
*/
class Java9ReflectionClassVisibilityTest : LightJava9ModulesCodeInsightFixtureTestCase() {
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/inspection/java9ReflectionClassVisibility"
override fun setUp() {
super.setUp()
myFixture.enableInspections(Java9ReflectionClassVisibilityInspection())
(myFixture as CodeInsightTestFixtureImpl).setVirtualFileFilter({ it.name != "module-info.java"})
}
fun testOpenModule() {
moduleInfo("module MAIN { requires API; }", MAIN)
moduleInfo("open module API { }", M2)
doTest()
}
fun testOpensPackage() {
moduleInfo("module MAIN { requires API; }", MAIN)
moduleInfo("module API { opens my.api; }", M2)
doTest()
}
fun testExportsPackage() {
moduleInfo("module MAIN { requires API; }", MAIN)
moduleInfo("module API { exports my.api; }", M2)
javaClass("my.api", "PackageLocal", M2, "")
doTest()
}
fun testNotInRequirements() {
moduleInfo("module MAIN { }", MAIN)
moduleInfo("open module API { }", M2)
doTest()
}
private fun doTest() {
javaClass("my.api", "Api", M2)
javaClass("my.impl", "Impl", M2)
val testPath = "$testDataPath/${getTestName(false)}.java"
val mainFile = FileUtil.findFirstThatExist(testPath)
assertNotNull("Test data: $testPath", mainFile)
val mainText = String(FileUtil.loadFileText(mainFile!!))
myFixture.configureFromExistingVirtualFile(addFile("my/main/Main.java", mainText, MAIN))
myFixture.checkHighlighting()
}
private fun javaClass(packageName: String, className: String, descriptor: ModuleDescriptor, modifier: String = "public") {
addFile("${packageName.replace('.', '/')}/$className.java", "package $packageName; $modifier class $className {}", descriptor)
}
}
| apache-2.0 | 02572e2533df2dac32975b1115c3e19b | 37.439024 | 130 | 0.749683 | 4.490028 | false | true | false | false |
sksamuel/ktest | kotest-framework/kotest-framework-engine/src/commonTest/kotlin/com/sksamuel/kotest/engine/TestCaseOrderTest.kt | 1 | 1733 | package com.sksamuel.kotest.engine
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.style.StringSpec
import io.kotest.core.test.TestCaseOrder
import io.kotest.core.spec.materializeAndOrderRootTests
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
class TestCaseOrderTest : FunSpec() {
init {
test("sequential test case ordering") {
SequentialSpec().materializeAndOrderRootTests().map { it.testCase.description.name.name } shouldBe
listOf("c", "b", "d", "e", "a")
}
test("Lexicographic test case ordering") {
LexicographicSpec().materializeAndOrderRootTests().map { it.testCase.description.name.name } shouldBe
listOf("a", "b", "c", "d", "e")
}
test("random test case ordering") {
val a = RandomSpec().materializeAndOrderRootTests().map { it.testCase.description.name.name }
val b = RandomSpec().materializeAndOrderRootTests().map { it.testCase.description.name.name }
a shouldNotBe b
}
}
}
class SequentialSpec : StringSpec() {
override fun testCaseOrder() = TestCaseOrder.Sequential
init {
"c" {}
"b" {}
"d" {}
"e" {}
"a" {}
}
}
class LexicographicSpec : StringSpec() {
override fun testCaseOrder() = TestCaseOrder.Lexicographic
init {
"b" {}
"d" {}
"a" {}
"e" {}
"c" {}
}
}
class RandomSpec : StringSpec() {
override fun testCaseOrder() = TestCaseOrder.Random
init {
"a" {}
"b" {}
"c" {}
"d" {}
"e" {}
"f" {}
"g" {}
"h" {}
"i" {}
"j" {}
"k" {}
"l" {}
"m" {}
"n" {}
"o" {}
"p" {}
}
}
| mit | 475995f447899af48c9daaefd3fb6391 | 21.802632 | 110 | 0.568379 | 3.663848 | false | true | false | false |
drmashu/koshop | src/main/kotlin/io/github/drmashu/koshop/dao/utils.kt | 1 | 2748 | import java.math.BigInteger
import kotlin.math.plus
import kotlin.math.times
val code63 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()
val rev63 = mapOf<Char, BigInteger>(
'0' to BigInteger("0"),
'1' to BigInteger("1"),
'2' to BigInteger("2"),
'3' to BigInteger("3"),
'4' to BigInteger("4"),
'5' to BigInteger("5"),
'6' to BigInteger("6"),
'7' to BigInteger("7"),
'8' to BigInteger("8"),
'9' to BigInteger("9"),
'a' to BigInteger("10"),
'b' to BigInteger("11"),
'c' to BigInteger("12"),
'd' to BigInteger("13"),
'e' to BigInteger("14"),
'f' to BigInteger("15"),
'g' to BigInteger("16"),
'h' to BigInteger("17"),
'i' to BigInteger("18"),
'j' to BigInteger("19"),
'k' to BigInteger("20"),
'l' to BigInteger("21"),
'm' to BigInteger("22"),
'n' to BigInteger("23"),
'o' to BigInteger("24"),
'p' to BigInteger("25"),
'q' to BigInteger("26"),
'r' to BigInteger("27"),
's' to BigInteger("28"),
't' to BigInteger("29"),
'u' to BigInteger("30"),
'v' to BigInteger("31"),
'w' to BigInteger("32"),
'x' to BigInteger("33"),
'y' to BigInteger("34"),
'z' to BigInteger("35"),
'A' to BigInteger("36"),
'B' to BigInteger("37"),
'C' to BigInteger("38"),
'D' to BigInteger("39"),
'E' to BigInteger("40"),
'F' to BigInteger("41"),
'G' to BigInteger("42"),
'H' to BigInteger("43"),
'I' to BigInteger("44"),
'J' to BigInteger("45"),
'K' to BigInteger("46"),
'L' to BigInteger("47"),
'M' to BigInteger("48"),
'N' to BigInteger("49"),
'O' to BigInteger("51"),
'P' to BigInteger("52"),
'Q' to BigInteger("53"),
'R' to BigInteger("54"),
'S' to BigInteger("55"),
'T' to BigInteger("56"),
'U' to BigInteger("57"),
'V' to BigInteger("58"),
'W' to BigInteger("59"),
'X' to BigInteger("60"),
'Y' to BigInteger("61"),
'Z' to BigInteger("62")
)
val BASE = BigInteger("63")
fun decode63(value: String): BigInteger {
var result = BigInteger.ZERO
for (ch in value.toCharArray()) {
result = result * BASE + (rev63[ch] ?: BigInteger.ZERO)
}
return result
}
fun encode63(value: BigInteger): String {
var result = ""
var newValue = value
for (idx in 1..20) {
val (dev, rem) = newValue.divideAndRemainder(BASE)
newValue = dev
result = code63[rem.intValueExact()] + result
}
return result
} | apache-2.0 | 4d2a822cc96e421bb2869ae2e4f47fc4 | 30.597701 | 91 | 0.510917 | 3.748977 | false | false | false | false |
slisson/intellij-community | platform/platform-impl/src/org/jetbrains/util/concurrency/AsyncPromise.kt | 3 | 6747 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.jetbrains.util.concurrency
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.concurrency.Obsolescent
import java.util.ArrayList
public class AsyncPromise<T> : Promise<T> {
companion object {
private val LOG = Logger.getInstance(javaClass<AsyncPromise<Any>>())
public val OBSOLETE_ERROR: RuntimeException = MessageError("Obsolete")
private fun <T> setHandler(oldConsumer: ((T) -> Unit)?, newConsumer: (T) -> Unit): (T) -> Unit {
return when (oldConsumer) {
null -> newConsumer
is CompoundConsumer<*> -> {
(oldConsumer as CompoundConsumer<T>).add(newConsumer)
return oldConsumer
}
else -> CompoundConsumer(oldConsumer, newConsumer)
}
}
private class CompoundConsumer<T>(c1: (T) -> Unit, c2: (T) -> Unit) : (T) -> Unit {
private var consumers: MutableList<(T) -> Unit>? = ArrayList()
init {
synchronized (this) {
consumers!!.add(c1)
consumers!!.add(c2)
}
}
override fun invoke(p1: T) {
var list = synchronized (this) {
var list = consumers!!
consumers = null
list
}
for (consumer in list) {
if (!consumer.isObsolete()) {
consumer(p1)
}
}
}
fun add(consumer: (T) -> Unit) {
synchronized (this) {
consumers?.add(consumer)
}
}
}
}
private volatile var done: ((T) -> Unit)? = null
private volatile var rejected: ((Throwable) -> Unit)? = null
override volatile var state = Promise.State.PENDING
private set
// result object or error message
private volatile var result: Any? = null
override fun done(done: (T) -> Unit): Promise<T> {
if (done.isObsolete()) {
return this
}
when (state) {
Promise.State.PENDING -> {
}
Promise.State.FULFILLED -> {
@suppress("UNCHECKED_CAST")
done(result as T)
return this
}
Promise.State.REJECTED -> return this
}
this.done = setHandler(this.done, done)
return this
}
override fun rejected(rejected: (Throwable) -> Unit): Promise<T> {
if (rejected.isObsolete()) {
return this
}
when (state) {
Promise.State.PENDING -> {
}
Promise.State.FULFILLED -> return this
Promise.State.REJECTED -> {
rejected(result as Throwable)
return this
}
}
this.rejected = setHandler(this.rejected, rejected)
return this
}
public fun get(): T {
@suppress("UNCHECKED_CAST")
return when (state) {
Promise.State.FULFILLED -> result as T
else -> null
}
}
override fun <SUB_RESULT> then(done: (T) -> SUB_RESULT) = thenImpl<SUB_RESULT>(done, false)
override fun <SUB_RESULT> thenAsync(done: (T) -> Promise<SUB_RESULT>): Promise<SUB_RESULT> = thenImpl(done, true)
private fun <SUB_RESULT> thenImpl(done: (T) -> Any, asyncResult: Boolean): Promise<SUB_RESULT> {
when (state) {
Promise.State.PENDING -> {
}
Promise.State.FULFILLED -> {
@suppress("UNCHECKED_CAST")
return if (asyncResult) done(result as T) as Promise<SUB_RESULT> else DonePromise(done(result as T) as SUB_RESULT)
}
Promise.State.REJECTED -> return RejectedPromise(result as Throwable)
}
val promise = AsyncPromise<SUB_RESULT>()
addHandlers({
promise.catchError {
if (done is Obsolescent && done.isObsolete()) {
promise.setError(OBSOLETE_ERROR)
}
else {
val subResult = done(it)
if (asyncResult) {
(subResult as Promise<*>).notify(promise)
if (subResult is AsyncPromise<*> && subResult.state == Promise.State.PENDING) {
// if promise fulfilled separately from sub result
@suppress("UNCHECKED_CAST")
promise.notify(subResult as AsyncPromise<SUB_RESULT>)
}
}
else {
@suppress("UNCHECKED_CAST")
promise.setResult(subResult as SUB_RESULT)
}
}
}
},
{ promise.setError(it) }
)
return promise
}
override fun notify(child: AsyncPromise<T>): Promise<T> {
if (child == this) {
throw IllegalStateException("Child must no be equals to this")
}
when (state) {
Promise.State.PENDING -> {
}
Promise.State.FULFILLED -> {
@suppress("UNCHECKED_CAST")
child.setResult(result as T)
return this
}
Promise.State.REJECTED -> {
child.setError(result as Throwable)
return this
}
}
addHandlers({ child.catchError { child.setResult(it) } }, { child.setError(it) })
return this
}
private fun addHandlers(done: (T) -> Unit, rejected: (Throwable) -> Unit) {
this.done = setHandler(this.done, done)
this.rejected = setHandler(this.rejected, rejected)
}
public fun setResult(result: T) {
if (state != Promise.State.PENDING) {
return
}
state = Promise.State.FULFILLED
this.result = result
val done = this.done
clearHandlers()
if (done != null && !done.isObsolete()) {
done(result)
}
}
public fun setError(error: String): Boolean = setError(MessageError(error))
public fun setError(error: Throwable): Boolean {
if (state != Promise.State.PENDING) {
return false
}
state = Promise.State.REJECTED
result = error
val rejected = this.rejected
clearHandlers()
if (rejected != null) {
if (!rejected.isObsolete()) {
rejected(error)
}
}
else {
Promise.logError(LOG, error)
}
return true
}
private fun clearHandlers() {
done = null
rejected = null
}
override fun processed(processed: (T) -> Unit): Promise<T> {
done(processed)
rejected { processed(null) }
return this
}
}
fun <T> ((T) -> Unit).isObsolete() = this is Obsolescent && this.isObsolete()
public inline fun AsyncPromise<out Any?>.catchError(task: () -> Unit) {
try {
task()
}
catch (e: Throwable) {
setError(e)
}
} | apache-2.0 | 7d51e41c81a90f204cc3abb4f0997c11 | 25.256809 | 122 | 0.601008 | 4.134191 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/event/EventDetailsViewModel.kt | 1 | 15326 | package org.fossasia.openevent.general.event
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.PagedList
import androidx.paging.RxPagedListBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import org.fossasia.openevent.general.BuildConfig.MAPBOX_KEY
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.auth.User
import org.fossasia.openevent.general.auth.UserId
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.connectivity.MutableConnectionLiveData
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.event.paging.SimilarEventsDataSourceFactory
import org.fossasia.openevent.general.favorite.FavoriteEvent
import org.fossasia.openevent.general.feedback.Feedback
import org.fossasia.openevent.general.feedback.FeedbackService
import org.fossasia.openevent.general.order.Order
import org.fossasia.openevent.general.order.OrderService
import org.fossasia.openevent.general.sessions.Session
import org.fossasia.openevent.general.sessions.SessionService
import org.fossasia.openevent.general.social.SocialLinksService
import org.fossasia.openevent.general.social.SocialLink
import org.fossasia.openevent.general.speakers.Speaker
import org.fossasia.openevent.general.speakers.SpeakerService
import org.fossasia.openevent.general.sponsor.Sponsor
import org.fossasia.openevent.general.sponsor.SponsorService
import org.fossasia.openevent.general.ticket.TicketPriceRange
import org.fossasia.openevent.general.ticket.TicketService
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
import java.lang.StringBuilder
class EventDetailsViewModel(
private val eventService: EventService,
private val ticketService: TicketService,
private val authHolder: AuthHolder,
private val speakerService: SpeakerService,
private val sponsorService: SponsorService,
private val sessionService: SessionService,
private val socialLinksService: SocialLinksService,
private val feedbackService: FeedbackService,
private val resource: Resource,
private val orderService: OrderService,
private val mutableConnectionLiveData: MutableConnectionLiveData,
private val config: PagedList.Config
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val connection: LiveData<Boolean> = mutableConnectionLiveData
private val mutableProgress = MutableLiveData<Boolean>()
val progress: LiveData<Boolean> = mutableProgress
private val mutableUser = MutableLiveData<User>()
val user: LiveData<User> = mutableUser
private val mutablePopMessage = SingleLiveEvent<String>()
val popMessage: LiveData<String> = mutablePopMessage
private val mutableEvent = MutableLiveData<Event>()
val event: LiveData<Event> = mutableEvent
private val mutableEventFeedback = MutableLiveData<List<Feedback>>()
val eventFeedback: LiveData<List<Feedback>> = mutableEventFeedback
private val mutableFeedbackProgress = MutableLiveData<Boolean>()
val feedbackProgress: LiveData<Boolean> = mutableFeedbackProgress
private val mutableSubmittedFeedback = MutableLiveData<Feedback>()
val submittedFeedback: LiveData<Feedback> = mutableSubmittedFeedback
private val mutableEventSessions = MutableLiveData<List<Session>>()
val eventSessions: LiveData<List<Session>> = mutableEventSessions
private val mutableEventSpeakers = MutableLiveData<List<Speaker>>()
val eventSpeakers: LiveData<List<Speaker>> = mutableEventSpeakers
private val mutableEventSponsors = MutableLiveData<List<Sponsor>>()
val eventSponsors: LiveData<List<Sponsor>> = mutableEventSponsors
private val mutableSocialLinks = MutableLiveData<List<SocialLink>>()
val socialLinks: LiveData<List<SocialLink>> = mutableSocialLinks
private val mutableSimilarEvents = MutableLiveData<PagedList<Event>>()
val similarEvents: LiveData<PagedList<Event>> = mutableSimilarEvents
private val mutableSimilarEventsProgress = MediatorLiveData<Boolean>()
val similarEventsProgress: MediatorLiveData<Boolean> = mutableSimilarEventsProgress
private val mutableOrders = MutableLiveData<List<Order>>()
val orders: LiveData<List<Order>> = mutableOrders
private val mutablePriceRange = MutableLiveData<String>()
val priceRange: LiveData<String> = mutablePriceRange
fun isLoggedIn() = authHolder.isLoggedIn()
fun getId() = authHolder.getId()
fun fetchEventFeedback(id: Long) {
if (id == -1L) return
compositeDisposable += feedbackService.getEventFeedback(id)
.withDefaultSchedulers()
.doOnSubscribe {
mutableFeedbackProgress.value = true
}.doFinally {
mutableFeedbackProgress.value = false
}
.subscribe({
mutableEventFeedback.value = it
}, {
Timber.e(it, "Error fetching events feedback")
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_section_message,
resource.getString(R.string.feedback))
})
}
fun submitFeedback(comment: String, rating: Float?, eventId: Long) {
val feedback = Feedback(rating = rating.toString(), comment = comment,
event = EventId(eventId), user = UserId(getId()))
compositeDisposable += feedbackService.submitFeedback(feedback)
.withDefaultSchedulers()
.subscribe({
mutablePopMessage.value = resource.getString(R.string.feedback_submitted)
mutableSubmittedFeedback.value = it
}, {
mutablePopMessage.value = resource.getString(R.string.error_submitting_feedback)
})
}
fun fetchEventSpeakers(id: Long) {
if (id == -1L) return
val query = """[{
| 'and':[{
| 'name':'is-featured',
| 'op':'eq',
| 'val':'true'
| }]
|}]""".trimMargin().replace("'", "\"")
compositeDisposable += speakerService.fetchSpeakersForEvent(id, query)
.withDefaultSchedulers()
.subscribe({
mutableEventSpeakers.value = it
}, {
Timber.e(it, "Error fetching speaker for event id %d", id)
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_section_message,
resource.getString(R.string.speakers))
})
}
fun fetchSocialLink(id: Long) {
if (id == -1L) return
compositeDisposable += socialLinksService.getSocialLinks(id)
.withDefaultSchedulers()
.subscribe({
mutableSocialLinks.value = it
}, {
Timber.e(it, "Error fetching social link for event id $id")
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_section_message,
resource.getString(R.string.social_links))
})
}
fun fetchSimilarEvents(eventId: Long, topicId: Long, location: String?) {
if (eventId == -1L) return
val sourceFactory = SimilarEventsDataSourceFactory(
compositeDisposable,
topicId,
location,
eventId,
mutableSimilarEventsProgress,
eventService
)
val similarEventPagedList = RxPagedListBuilder(sourceFactory, config)
.setFetchScheduler(Schedulers.io())
.buildObservable()
.cache()
compositeDisposable += similarEventPagedList
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.distinctUntilChanged()
.doOnSubscribe {
mutableSimilarEventsProgress.value = true
}.subscribe({ events ->
val currentPagedSimilarEvents = mutableSimilarEvents.value
if (currentPagedSimilarEvents == null) {
mutableSimilarEvents.value = events
} else {
currentPagedSimilarEvents.addAll(events)
mutableSimilarEvents.value = currentPagedSimilarEvents
}
}, {
Timber.e(it, "Error fetching similar events")
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_section_message,
resource.getString(R.string.similar_events))
})
}
fun fetchEventSponsors(id: Long) {
if (id == -1L) return
compositeDisposable += sponsorService.fetchSponsorsWithEvent(id)
.withDefaultSchedulers()
.subscribe({
mutableEventSponsors.value = it
}, {
Timber.e(it, "Error fetching sponsor for event id %d", id)
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_section_message,
resource.getString(R.string.sponsors))
})
}
fun loadEvent(id: Long) {
if (id == -1L) {
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_message)
return
}
compositeDisposable += eventService.getEvent(id)
.withDefaultSchedulers()
.distinctUntilChanged()
.doOnSubscribe {
mutableProgress.value = true
}.subscribe({
mutableProgress.value = false
mutableEvent.value = it
}, {
mutableProgress.value = false
Timber.e(it, "Error fetching event %d", id)
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_message)
})
}
fun loadEventByIdentifier(identifier: String) {
if (identifier.isEmpty()) {
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_message)
return
}
compositeDisposable += eventService.getEventByIdentifier(identifier)
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableEvent.value = it
}, {
Timber.e(it, "Error fetching event")
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_message)
})
}
fun fetchEventSessions(id: Long) {
if (id == -1L) return
compositeDisposable += sessionService.fetchSessionForEvent(id)
.withDefaultSchedulers()
.subscribe({
mutableEventSessions.value = it
}, {
mutablePopMessage.value = resource.getString(R.string.error_fetching_event_section_message,
resource.getString(R.string.sessions))
Timber.e(it, "Error fetching events sessions")
})
}
fun loadOrders() {
if (!isLoggedIn())
return
compositeDisposable += orderService.getOrdersOfUser(getId())
.withDefaultSchedulers()
.subscribe({
mutableOrders.value = it
}, {
Timber.e(it, "Error fetching orders")
})
}
fun syncTickets(event: Event) {
compositeDisposable += ticketService.syncTickets(event.id)
.withDefaultSchedulers()
.subscribe({
if (!it.isNullOrEmpty())
loadPriceRange(event)
}, {
Timber.e(it, "Error fetching tickets")
})
}
private fun loadPriceRange(event: Event) {
compositeDisposable += ticketService.getTicketPriceRange(event.id)
.withDefaultSchedulers()
.subscribe({
setRange(it, event.paymentCurrency.toString())
}, {
Timber.e(it, "Error fetching ticket price range")
})
}
private fun setRange(priceRange: TicketPriceRange, paymentCurrency: String) {
val maxPrice = priceRange.maxValue
val minPrice = priceRange.minValue
val range = StringBuilder()
if (maxPrice == minPrice) {
if (maxPrice == 0f)
range.append(resource.getString(R.string.free))
else {
range.append(paymentCurrency)
range.append(" ")
range.append("%.2f".format(minPrice))
}
} else {
if (minPrice == 0f)
range.append(resource.getString(R.string.free))
else {
range.append(paymentCurrency)
range.append(" ")
range.append("%.2f".format(minPrice))
}
range.append(" - ")
range.append(paymentCurrency)
range.append(" ")
range.append("%.2f".format(maxPrice))
}
mutablePriceRange.value = range.toString()
}
fun loadMap(event: Event): String {
// location handling
val BASE_URL = "https://api.mapbox.com/v4/mapbox.emerald/pin-l-marker+673ab7"
val LOCATION = "(${event.longitude},${event.latitude})/${event.longitude},${event.latitude}"
return "$BASE_URL$LOCATION,15/900x500.png?access_token=$MAPBOX_KEY"
}
fun setFavorite(event: Event, favorite: Boolean) {
if (favorite) {
addFavorite(event)
} else {
removeFavorite(event)
}
}
private fun addFavorite(event: Event) {
val favoriteEvent = FavoriteEvent(authHolder.getId(), EventId(event.id))
compositeDisposable += eventService.addFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutablePopMessage.value = resource.getString(R.string.add_event_to_shortlist_message)
}, {
mutablePopMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on adding like for event ID ${event.id}")
})
}
private fun removeFavorite(event: Event) {
val favoriteEventId = event.favoriteEventId ?: return
val favoriteEvent = FavoriteEvent(favoriteEventId, EventId(event.id))
compositeDisposable += eventService.removeFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutablePopMessage.value = resource.getString(R.string.remove_event_from_shortlist_message)
}, {
mutablePopMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on removing like for event ID ${event.id}")
})
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| apache-2.0 | 6a7272d950499bfdddb4a33476122b06 | 40.088472 | 107 | 0.640611 | 5.001958 | false | false | false | false |
Austin72/Charlatano | src/main/kotlin/com/charlatano/utils/extensions/PointExtensions.kt | 1 | 1258 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.utils.extensions
import com.charlatano.utils.natives.CUser32
import com.sun.jna.platform.win32.WinDef
import java.lang.Math.sqrt
fun WinDef.POINT.set(x: Int, y: Int) = apply {
this.x = x
this.y = y
}
fun WinDef.POINT.refresh() = apply { CUser32.GetCursorPos(this) }
fun WinDef.POINT.distance(b: WinDef.POINT): Double {
val px = (b.x - this.x).toDouble()
val py = (b.y - this.y).toDouble()
return sqrt(px * px + py * py)
} | agpl-3.0 | 83d808a7f7d6ac02b94881ce039e7691 | 33.972222 | 78 | 0.72496 | 3.409214 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerMoveListener.kt | 1 | 2302 | /*
* Copyright 2016 Ross 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.characters.bukkit.listener
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.Location
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerMoveEvent
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType.BLINDNESS
/**
* Player move listener for preventing players from moving about with a dead character.
*/
class PlayerMoveListener(private val plugin: RPKCharactersBukkit): Listener {
@EventHandler
fun onPlayerMove(event: PlayerMoveEvent) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(event.player)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null && character.isDead) {
if (event.from.blockX != event.to?.blockX || event.from.blockZ != event.to?.blockZ) {
event.player.teleport(Location(event.from.world, event.from.blockX + 0.5, event.from.blockY + 0.5, event.from.blockZ.toDouble(), event.from.yaw, event.from.pitch))
event.player.sendMessage(plugin.messages["dead-character"])
event.player.addPotionEffect(PotionEffect(BLINDNESS, 60, 1))
}
}
}
}
}
| apache-2.0 | 0cc154c4c780272a56bf119de812924d | 44.137255 | 183 | 0.734579 | 4.576541 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/fastscroll/RecyclerViewFastScroller.kt | 1 | 16729 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.ui.widget.fastscroll
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.InsetDrawable
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.ColorInt
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import com.google.android.material.appbar.AppBarLayout
import jp.hazuki.yuzubrowser.core.utility.extensions.convertDpToPx
import jp.hazuki.yuzubrowser.ui.R
import jp.hazuki.yuzubrowser.ui.extensions.getColorFromThemeRes
class RecyclerViewFastScroller @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
private val bar = View(context)
private val handle = View(context)
private var hiddenTranslationX: Int = 0
private val minScrollHandleHeight: Int
private var mOnTouchListener: OnTouchListener? = null
internal var appBarLayoutOffset: Int = 0
internal var recyclerView: androidx.recyclerview.widget.RecyclerView? = null
internal var coordinatorLayout: CoordinatorLayout? = null
internal var appBarLayout: AppBarLayout? = null
internal var animator: AnimatorSet? = null
internal var animatingIn: Boolean = false
/**
* @property hideDelay the delay in millis to hide the scrollbar
*/
var hideDelay: Long = 0
private var hidingEnabled: Boolean = false
private var barInset: Int = 0
private var hideOverride: Boolean = false
private var adapter: androidx.recyclerview.widget.RecyclerView.Adapter<*>? = null
private val adapterObserver = object : androidx.recyclerview.widget.RecyclerView.AdapterDataObserver() {
override fun onChanged() {
requestLayout()
}
}
var isShowLeft: Boolean = false
@SuppressLint("RtlHardcoded")
set(showLeft) {
if (this.isShowLeft != showLeft) {
field = showLeft
updateBarColorAndInset()
updateHandleColorsAndInset()
hiddenTranslationX *= -1
val params = layoutParams as LayoutParams
if (showLeft) {
params.gravity = Gravity.LEFT
} else {
params.gravity = Gravity.RIGHT
}
}
}
@ColorInt
var handlePressedColor = 0
set(@ColorInt colorPressed) {
field = colorPressed
updateHandleColorsAndInset()
}
@ColorInt
var handleNormalColor = 0
set(@ColorInt colorNormal) {
field = colorNormal
updateHandleColorsAndInset()
}
/**
* @property scrollBarColor Scroll bar color. Alpha will be set to ~22% to match stock scrollbar.
*/
@ColorInt
var scrollBarColor = 0
set(@ColorInt scrollBarColor) {
field = scrollBarColor
updateBarColorAndInset()
}
/**
* @property touchTargetWidth In pixels, less than or equal to 48dp
*/
var touchTargetWidth = 0
set(touchTargetWidth) {
field = touchTargetWidth
val eightDp = context.convertDpToPx(8)
barInset = this.touchTargetWidth - eightDp
val fortyEightDp = context.convertDpToPx(48)
if (this.touchTargetWidth > fortyEightDp) {
throw RuntimeException("Touch target width cannot be larger than 48dp!")
}
bar.layoutParams = LayoutParams(touchTargetWidth, ViewGroup.LayoutParams.MATCH_PARENT, GravityCompat.END)
handle.layoutParams = LayoutParams(touchTargetWidth, ViewGroup.LayoutParams.MATCH_PARENT, GravityCompat.END)
updateHandleColorsAndInset()
updateBarColorAndInset()
}
/**
* @property isHidingEnabled whether hiding is enabled
*/
var isHidingEnabled: Boolean
get() = hidingEnabled
set(hidingEnabled) {
this.hidingEnabled = hidingEnabled
if (hidingEnabled) {
postAutoHide()
}
}
var isFixed: Boolean = false
private val mHide: Runnable = Runnable {
if (!handle.isPressed) {
animator?.run {
if (isStarted) {
cancel()
}
}
animator = AnimatorSet().apply {
val animator2 = ObjectAnimator.ofFloat(this@RecyclerViewFastScroller, View.TRANSLATION_X, hiddenTranslationX.toFloat())
animator2.interpolator = FastOutLinearInInterpolator()
animator2.duration = 150
handle.isEnabled = false
play(animator2)
start()
}
}
}
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.WebViewFastScroller, defStyleAttr, defStyleRes)
this.scrollBarColor = a.getColor(
R.styleable.WebViewFastScroller_fs_barColor,
context.getColorFromThemeRes(R.attr.colorControlNormal))
this.handleNormalColor = a.getColor(
R.styleable.WebViewFastScroller_fs_handleNormalColor,
context.getColorFromThemeRes(R.attr.colorControlNormal))
this.handlePressedColor = a.getColor(
R.styleable.WebViewFastScroller_fs_handlePressedColor,
context.getColorFromThemeRes(R.attr.colorAccent))
this.touchTargetWidth = a.getDimensionPixelSize(
R.styleable.WebViewFastScroller_fs_touchTargetWidth,
context.convertDpToPx(24))
hideDelay = a.getInt(R.styleable.WebViewFastScroller_fs_hideDelay,
DEFAULT_AUTO_HIDE_DELAY).toLong()
hidingEnabled = a.getBoolean(R.styleable.WebViewFastScroller_fs_hidingEnabled, true)
a.recycle()
val fortyEightDp = context.convertDpToPx(48)
layoutParams = ViewGroup.LayoutParams(fortyEightDp, ViewGroup.LayoutParams.MATCH_PARENT)
addView(bar)
addView(handle)
this.touchTargetWidth = this.touchTargetWidth
minScrollHandleHeight = fortyEightDp
val eightDp = getContext().convertDpToPx(8)
hiddenTranslationX = (if (isShowLeft) -1 else 1) * eightDp
handle.setOnTouchListener(object : OnTouchListener {
private var mInitialBarHeight: Float = 0.toFloat()
private var mLastPressedYAdjustedToInitial: Float = 0.toFloat()
override fun onTouch(v: View, ev: MotionEvent): Boolean {
val recyclerView = recyclerView ?: return true
val event = MotionEvent.obtain(ev)
val action = event.actionMasked
event.offsetLocation(0f, (-appBarLayoutOffset).toFloat())
mOnTouchListener?.onTouch(v, event)
when (action) {
MotionEvent.ACTION_DOWN -> {
handle.isPressed = true
recyclerView.stopScroll()
var nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE
nestedScrollAxis = nestedScrollAxis or ViewCompat.SCROLL_AXIS_VERTICAL
recyclerView.startNestedScroll(nestedScrollAxis)
mInitialBarHeight = bar.height.toFloat()
mLastPressedYAdjustedToInitial = event.y + handle.y + bar.y
}
MotionEvent.ACTION_MOVE -> {
val newHandlePressedY = event.y + handle.y
val barHeight = bar.height
val newHandlePressedYAdjustedToInitial = newHandlePressedY + (mInitialBarHeight - barHeight) + bar.y
val deltaPressedYFromLastAdjustedToInitial = newHandlePressedYAdjustedToInitial - mLastPressedYAdjustedToInitial
val dY = (deltaPressedYFromLastAdjustedToInitial / mInitialBarHeight *
(recyclerView.computeVerticalScrollRange() + if (appBarLayout == null) 0 else appBarLayout!!.totalScrollRange).toFloat()
* computeDeltaScale(event)).toInt()
val coordinator = coordinatorLayout
val appBar = appBarLayout
if (!isFixed && coordinator != null && appBar != null) {
val params = appBar.layoutParams as CoordinatorLayout.LayoutParams
val behavior = params.behavior as AppBarLayout.Behavior?
behavior?.onNestedPreScroll(coordinator, appBar,
this@RecyclerViewFastScroller, 0, dY, IntArray(2), ViewCompat.TYPE_TOUCH)
}
updateRvScroll(dY)
mLastPressedYAdjustedToInitial = newHandlePressedYAdjustedToInitial
}
MotionEvent.ACTION_UP -> {
mLastPressedYAdjustedToInitial = -1f
recyclerView.stopNestedScroll()
handle.isPressed = false
postAutoHide()
}
}
return true
}
})
translationX = hiddenTranslationX.toFloat()
}
private fun computeDeltaScale(e: MotionEvent): Float {
val width = recyclerView!!.width
val scrollbarX = if (isShowLeft) x else x + getWidth()
var scale = Math.abs(width - scrollbarX + recyclerView!!.x - e.rawX) / width
if (scale < 0.1f) {
scale = 0.1f
} else if (scale > 0.9f) {
scale = 1.0f
}
return scale
}
private fun updateHandleColorsAndInset() {
val drawable = StateListDrawable()
if (!isShowLeft) {
drawable.addState(View.PRESSED_ENABLED_STATE_SET,
InsetDrawable(ColorDrawable(this.handlePressedColor), barInset, 0, 0, 0))
drawable.addState(View.EMPTY_STATE_SET,
InsetDrawable(ColorDrawable(this.handleNormalColor), barInset, 0, 0, 0))
} else {
drawable.addState(View.PRESSED_ENABLED_STATE_SET,
InsetDrawable(ColorDrawable(this.handlePressedColor), 0, 0, barInset, 0))
drawable.addState(View.EMPTY_STATE_SET,
InsetDrawable(ColorDrawable(this.handleNormalColor), 0, 0, barInset, 0))
}
handle.background = drawable
}
private fun updateBarColorAndInset() {
val drawable = if (!isShowLeft) {
InsetDrawable(ColorDrawable(this.scrollBarColor), barInset, 0, 0, 0)
} else {
InsetDrawable(ColorDrawable(this.scrollBarColor), 0, 0, barInset, 0)
}
drawable.alpha = 22
bar.background = drawable
}
fun attachRecyclerView(recyclerView: androidx.recyclerview.widget.RecyclerView) {
this.recyclerView = recyclerView
recyclerView.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) {
show(true)
}
})
recyclerView.adapter?.let {
attachAdapter(it)
}
}
fun attachAdapter(adapter: androidx.recyclerview.widget.RecyclerView.Adapter<*>?) {
if (this.adapter === adapter) return
this.adapter?.unregisterAdapterDataObserver(adapterObserver)
adapter?.registerAdapterDataObserver(adapterObserver)
this.adapter = adapter
}
fun attachAppBarLayout(coordinatorLayout: CoordinatorLayout, appBarLayout: AppBarLayout) {
this.coordinatorLayout = coordinatorLayout
this.appBarLayout = appBarLayout
appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
show(true)
val layoutParams = layoutParams as ViewGroup.MarginLayoutParams
appBarLayoutOffset = -verticalOffset
setLayoutParams(layoutParams)
})
}
fun setOnHandleTouchListener(listener: OnTouchListener) {
mOnTouchListener = listener
}
/**
* Show the fast scroller and hide after delay
*
* @param animate whether to animate showing the scroller
*/
fun show(animate: Boolean) {
requestLayout()
post(Runnable {
if (hideOverride) {
return@Runnable
}
handle.isEnabled = true
if (animate) {
if (!animatingIn && translationX != 0f) {
animator?.run {
if (isStarted) {
cancel()
}
}
animator = AnimatorSet().apply {
val animator = ObjectAnimator.ofFloat(this@RecyclerViewFastScroller, View.TRANSLATION_X, 0f)
animator.interpolator = LinearOutSlowInInterpolator()
animator.duration = 100
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
animatingIn = false
}
})
animatingIn = true
play(animator)
start()
}
}
} else {
translationX = 0f
}
postAutoHide()
})
}
internal fun postAutoHide() {
val recyclerView = recyclerView
if (recyclerView != null && hidingEnabled) {
recyclerView.removeCallbacks(mHide)
recyclerView.postDelayed(mHide, hideDelay)
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
val recyclerView = recyclerView ?: return
val appBarScrollRange = appBarLayout?.totalScrollRange ?: 0
val scrollOffset = recyclerView.computeVerticalScrollOffset() + appBarLayoutOffset
val verticalScrollRange = recyclerView.computeVerticalScrollRange() + appBarScrollRange
val barHeight = bar.height
val ratio = scrollOffset.toFloat() / (verticalScrollRange - barHeight)
var calculatedHandleHeight = (barHeight.toFloat() / verticalScrollRange * barHeight).toInt()
if (calculatedHandleHeight < minScrollHandleHeight) {
calculatedHandleHeight = minScrollHandleHeight
}
if (calculatedHandleHeight >= barHeight) {
translationX = hiddenTranslationX.toFloat()
hideOverride = true
return
}
hideOverride = false
val y = ratio * (barHeight - calculatedHandleHeight) + appBarLayoutOffset - appBarScrollRange
handle.layout(handle.left, y.toInt(), handle.right, y.toInt() + calculatedHandleHeight)
}
internal fun updateRvScroll(dY: Int) {
recyclerView?.run {
try {
scrollBy(0, dY)
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
companion object {
private const val DEFAULT_AUTO_HIDE_DELAY = 1500
}
}
| apache-2.0 | 621441a044151ce2def1f38479294741 | 36.258352 | 194 | 0.612649 | 5.278952 | false | false | false | false |
holgerbrandl/kscript | src/main/kotlin/kscript/app/cache/Cache.kt | 1 | 3969 | package kscript.app.cache
import kscript.app.creator.JarArtifact
import kscript.app.model.Content
import kscript.app.model.ScriptType
import kscript.app.shell.*
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.io.FileUtils
import java.net.URI
class Cache(private val cacheBasePath: OsPath) {
init {
cacheBasePath.createDirectories()
}
fun getOrCreateIdeaProject(digest: String, creator: (OsPath) -> OsPath): OsPath {
val path = cacheBasePath.resolve("idea_$digest")
return if (path.exists()) {
path
} else {
path.createDirectories()
creator(path)
}
}
fun getOrCreatePackage(digest: String, scriptName: String, creator: (OsPath, OsPath) -> OsPath): OsPath {
val path = cacheBasePath.resolve("package_$digest")
val cachedPackageFile = path.resolve("build/libs/$scriptName")
return if (cachedPackageFile.exists()) {
cachedPackageFile
} else {
path.createDirectories()
creator(path, cachedPackageFile)
}
}
fun getOrCreateJar(digest: String, creator: (OsPath) -> JarArtifact): JarArtifact {
val directory = cacheBasePath.resolve("jar_$digest")
val cachedJarArtifact = directory.resolve("jarArtifact.descriptor")
return if (cachedJarArtifact.exists()) {
val jarArtifactLines = cachedJarArtifact.readText().lines()
JarArtifact(OsPath.createOrThrow(cacheBasePath.nativeType, jarArtifactLines[0]), jarArtifactLines[1])
} else {
directory.createDirectories()
val jarArtifact = creator(directory)
cachedJarArtifact.writeText("${jarArtifact.path}\n${jarArtifact.execClassName}")
jarArtifact
}
}
fun getOrCreateUriItem(uri: URI, creator: (URI, OsPath) -> Content): Content {
val digest = DigestUtils.md5Hex(uri.toString())
val directory = cacheBasePath.resolve("uri_$digest")
val descriptorFile = directory.resolve("uri.descriptor")
val contentFile = directory.resolve("uri.content")
if (descriptorFile.exists() && contentFile.exists()) {
//Cache hit
val descriptor = descriptorFile.readText().lines()
val scriptType = ScriptType.valueOf(descriptor[0])
val fileName = descriptor[1]
val cachedUri = URI.create(descriptor[2])
val contextUri = URI.create(descriptor[3])
val content = contentFile.readText()
return Content(content, scriptType, fileName, cachedUri, contextUri, contentFile)
}
//Cache miss
val content = creator(uri, contentFile)
directory.createDirectories()
descriptorFile.writeText("${content.scriptType}\n${content.fileName}\n${content.uri}\n${content.contextUri}")
contentFile.writeText(content.text)
return content
}
fun getOrCreateDependencies(digest: String, creator: () -> Set<OsPath>): Set<OsPath> {
val directory = cacheBasePath.resolve("dependencies_$digest")
val contentFile = directory.resolve("dependencies.content")
if (contentFile.exists()) {
val dependencies =
contentFile.readText()
.lines()
.filter { it.isNotEmpty() }
.map { OsPath.createOrThrow(cacheBasePath.nativeType, it) }
.toSet()
//Recheck cached paths - if there are missing artifacts skip the cached values
if (dependencies.all { it.exists() }) {
return dependencies
}
}
val dependencies = creator()
directory.createDirectories()
contentFile.writeText(dependencies.joinToString("\n") { it.toString() })
return dependencies
}
fun clear() {
FileUtils.cleanDirectory(cacheBasePath.toNativeFile())
}
}
| mit | 90b40f17b2da21971578fd5762c4643f | 34.756757 | 117 | 0.629126 | 4.669412 | false | false | false | false |
rekendahl/kotlin_simple_language_plugin | src/main/kotlin/com/simpleplugin/SimpleSyntaxHighlighter.kt | 1 | 1926 | package com.simpleplugin
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey as Key
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.TokenType
import com.simpleplugin.psi.SimpleTypes
class SimpleSyntaxHighlighter() : SyntaxHighlighterBase() {
companion object {
val SEPARATOR = Key.createTextAttributesKey("SIMPLE_SEPARATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN)
val KEY = Key.createTextAttributesKey("SIMPLE_KEY", DefaultLanguageHighlighterColors.KEYWORD)
val VALUE = Key.createTextAttributesKey("SIMPLE_VALUE", DefaultLanguageHighlighterColors.STRING)
val COMMENT = Key.createTextAttributesKey("SIMPLE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
val BAD_CHARACTER = Key.createTextAttributesKey("SIMPLE_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER)
val SEPARATOR_KEYS = arrayOf(SEPARATOR)
val KEY_KEYS = arrayOf(KEY)
val VALUE_KEYS = arrayOf(VALUE)
val COMMENT_KEYS = arrayOf(COMMENT)
val BAD_CHARACTER_KEYS = arrayOf(BAD_CHARACTER)
val EMPTY_KEYS = arrayOf<Key>()
}
override fun getHighlightingLexer(): Lexer { return SimpleLexerAdapter() }
override fun getTokenHighlights(tokentype: IElementType?): Array<TextAttributesKey> {
when(tokentype) {
SimpleTypes.SEPARATOR -> return SEPARATOR_KEYS
SimpleTypes.KEY -> return KEY_KEYS
SimpleTypes.VALUE -> return VALUE_KEYS
SimpleTypes.COMMENT -> return COMMENT_KEYS
TokenType.BAD_CHARACTER -> return BAD_CHARACTER_KEYS
else -> return EMPTY_KEYS
}
}
}
| apache-2.0 | 6178391da2e62c5eebe4cf8ecbb95eed | 42.772727 | 120 | 0.742991 | 5.041885 | false | false | false | false |
rfcx/rfcx-guardian-android | role-guardian/src/main/java/org/rfcx/guardian/guardian/api/http/GuardianCheckApi.kt | 1 | 1418 | package org.rfcx.guardian.guardian.api.http
import android.content.Context
import android.os.Handler
import android.os.StrictMode
import org.rfcx.guardian.guardian.RfcxGuardian
import org.rfcx.guardian.guardian.manager.getTokenID
import org.rfcx.guardian.utility.http.HttpGet
object GuardianCheckApi {
private lateinit var httpGet: HttpGet
fun exists(context: Context, guid: String, callback: GuardianCheckCallback) {
val token = context.getTokenID()
httpGet = HttpGet(context, RfcxGuardian.APP_ROLE)
httpGet.customHttpHeaders = listOf(arrayOf("Authorization", "Bearer ${token!!}"))
val url = ApiRest.baseUrl(context)
val getUrl = "${url}v2/guardians/${guid}"
val handler = Handler()
val runnable = Runnable {
val policy = StrictMode.ThreadPolicy.Builder()
.permitAll().build()
StrictMode.setThreadPolicy(policy)
val response = httpGet.getAsJson(getUrl, null).toString()
if (response.isNotEmpty()) {
callback.onGuardianCheckSuccess(null, response)
} else {
callback.onGuardianCheckFailed(null, "Unsuccessful")
}
}
handler.post(runnable)
}
}
interface GuardianCheckCallback {
fun onGuardianCheckSuccess(t: Throwable?, response: String?)
fun onGuardianCheckFailed(t: Throwable?, message: String?)
}
| apache-2.0 | a2766442bff7c8d72df6a9aa39b71e26 | 31.976744 | 89 | 0.672073 | 4.376543 | false | false | false | false |
myunusov/sofarc | sofarc-serv/src/main/kotlin/org/maxur/sofarc/rest/RestServiceConfig.kt | 1 | 1630 | @file:Suppress("unused")
package org.maxur.sofarc.rest
import io.swagger.annotations.*
import org.jvnet.hk2.annotations.Service
import org.maxur.sofarc.core.annotation.Value
import org.maxur.sofarc.core.rest.RestResourceConfig
import javax.inject.Inject
/**
* @author myunusov
* @version 1.0
* @since <pre>12.06.2017</pre>
*/
@Service
@SwaggerDefinition(
info = Info(
title = "SOFTARC REST API",
description = "This is a SoftArc Service REST API",
version = "V1.0",
// termsOfService = "http://theweatherapi.io/terms.html",
contact = Contact(
name = "Maxim Yunusov",
email = "[email protected]",
url = "https://github.com/myunusov"
),
license = License(
name = "Apache 2.0",
url = "http://www.apache.org/licenses/LICENSE-2.0"
)
),
consumes = arrayOf("application/json", "application/xml"),
produces = arrayOf("application/json", "application/xml"),
schemes = arrayOf(SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS),
tags = arrayOf(
Tag(name = "Private", description = "Tag used to denote operations as private")
)
// externalDocs = ExternalDocs(value = "Meteorology", url = "http://theweatherapi.io/meteorology.html")
)
class RestServiceConfig @Inject constructor(
@Value(key = "name") name: String
) : RestResourceConfig(name, RestServiceConfig::class.java.getPackage().name) | apache-2.0 | e5b60d1fd64ecc7731cbb0b534302822 | 36.068182 | 110 | 0.589571 | 4.126582 | false | true | false | false |
ratedali/EEESE-android | app/src/main/java/edu/uofk/eeese/eeese/data/backend/ApiWrapper.kt | 1 | 2359 | /*
* Copyright 2017 Ali Salah Alddin
*
* 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 edu.uofk.eeese.eeese.data.backend
import edu.uofk.eeese.eeese.data.Event
import edu.uofk.eeese.eeese.data.Project
import edu.uofk.eeese.eeese.data.ProjectCategory
import edu.uofk.eeese.eeese.data.backend.ServerContract.Events
import edu.uofk.eeese.eeese.data.backend.ServerContract.Projects
import io.reactivex.Observable
import io.reactivex.Single
class ApiWrapper(private val api: BackendApi) {
fun projects(): Single<List<Project>> = api.projects()
.flatMapObservable({ Observable.fromIterable(it) })
.map({ Projects.project(it) })
.toList()
fun project(id: String): Single<Project> = api.project(id)
.map({ ServerContract.Projects.project(it) })
fun projects(category: ProjectCategory): Single<List<Project>> =
api.projects(Projects.category(category))
.flatMapObservable({ Observable.fromIterable(it) })
.map({ Projects.project(it) })
.toList()
fun event(id: String): Single<Event> = api.event(id)
.map({ Events.event(it) })
fun events(): Single<List<Event>> = api.events()
.flatMapObservable({ Observable.fromIterable(it) })
.map({ Events.event(it) })
.toList()
}
| mit | 4d077ef5c93cc7dd729dd677def17ec1 | 48.145833 | 463 | 0.711742 | 4.376623 | false | false | false | false |
googlecodelabs/android-compose-codelabs | TestingCodelab/app/src/main/java/com/example/compose/rally/ui/components/RallyAnimatedCircle.kt | 1 | 3641 | /*
* 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
*
* 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.compose.rally.ui.components
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
private const val DividerLengthInDegrees = 1.8f
/**
* A donut chart that animates when loaded.
*/
@Composable
fun AnimatedCircle(
proportions: List<Float>,
colors: List<Color>,
modifier: Modifier = Modifier
) {
val currentState = remember {
MutableTransitionState(AnimatedCircleProgress.START)
.apply { targetState = AnimatedCircleProgress.END }
}
val stroke = with(LocalDensity.current) { Stroke(5.dp.toPx()) }
val transition = updateTransition(currentState)
val angleOffset by transition.animateFloat(
transitionSpec = {
tween(
delayMillis = 500,
durationMillis = 900,
easing = LinearOutSlowInEasing
)
}
) { progress ->
if (progress == AnimatedCircleProgress.START) {
0f
} else {
360f
}
}
val shift by transition.animateFloat(
transitionSpec = {
tween(
delayMillis = 500,
durationMillis = 900,
easing = CubicBezierEasing(0f, 0.75f, 0.35f, 0.85f)
)
}
) { progress ->
if (progress == AnimatedCircleProgress.START) {
0f
} else {
30f
}
}
Canvas(modifier) {
val innerRadius = (size.minDimension - stroke.width) / 2
val halfSize = size / 2.0f
val topLeft = Offset(
halfSize.width - innerRadius,
halfSize.height - innerRadius
)
val size = Size(innerRadius * 2, innerRadius * 2)
var startAngle = shift - 90f
proportions.forEachIndexed { index, proportion ->
val sweep = proportion * angleOffset
drawArc(
color = colors[index],
startAngle = startAngle + DividerLengthInDegrees / 2,
sweepAngle = sweep - DividerLengthInDegrees,
topLeft = topLeft,
size = size,
useCenter = false,
style = stroke
)
startAngle += sweep
}
}
}
private enum class AnimatedCircleProgress { START, END }
| apache-2.0 | ad92861d0f4019db66e86125716fd583 | 32.40367 | 75 | 0.652293 | 4.71022 | false | false | false | false |
systemallica/ValenBisi | app/src/main/kotlin/com/systemallica/valenbisi/clustering/ClusterPoint.kt | 1 | 842 | package com.systemallica.valenbisi.clustering
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.clustering.ClusterItem
import com.systemallica.valenbisi.BikeStation
class ClusterPoint(station: BikeStation) : ClusterItem {
private var position: LatLng = LatLng(station.lat, station.lng)
private var title: String = station.address
private val snippet: String = station.snippet!!
val icon: BitmapDescriptor = station.icon!!
var alpha: Float = station.alpha!!
var visibility: Boolean = station.visibility
override fun getPosition(): LatLng {
return this.position
}
override fun getTitle(): String {
return this.title
}
override fun getSnippet(): String {
return this.snippet
}
}
| gpl-3.0 | d012139827db4d7887e17f7889368d90 | 28.034483 | 67 | 0.728029 | 4.107317 | false | false | false | false |
shchurov/gitter-kotlin-client | app/src/main/kotlin/com/github/shchurov/gitterclient/data/network/api/implementation/retrofit/RetrofitInitializer.kt | 1 | 2098 | package com.github.shchurov.gitterclient.data.network.api.implementation.retrofit
import com.github.shchurov.gitterclient.data.preferences.Preferences
import com.squareup.okhttp.Interceptor
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.logging.HttpLoggingInterceptor
import retrofit.GsonConverterFactory
import retrofit.Retrofit
import retrofit.RxJavaCallAdapterFactory
object RetrofitInitializer {
private const val BASE_URL = "https://api.gitter.im/"
private const val KEY_AUTH_HEADER = "Authorization"
fun initGitterService(preferences: Preferences): GitterRetrofitService {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(createClient(preferences))
.build()
return retrofit.create(GitterRetrofitService::class.java)
}
private fun createClient(preferences: Preferences): OkHttpClient {
val okHttpClient = OkHttpClient()
setupAuth(okHttpClient, preferences)
setupLogging(okHttpClient)
return okHttpClient
}
private fun setupLogging(client: OkHttpClient) {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.interceptors().add(interceptor)
}
private fun setupAuth(client: OkHttpClient, preferences: Preferences) {
val interceptor = Interceptor { chain ->
val original = chain.request();
val token = preferences.getGitterAccessToken()
if (token != null) {
val modified = original.newBuilder()
.header(KEY_AUTH_HEADER, "Bearer $token")
.method(original.method(), original.body())
.build();
chain.proceed(modified)
} else {
chain.proceed(original);
}
}
client.interceptors().add(interceptor)
}
}
| apache-2.0 | c90035fc64b38761410d54240f0b258b | 36.464286 | 81 | 0.659676 | 5.365729 | false | false | false | false |
waicool20/SikuliCef | src/main/kotlin/com/waicool20/sikulicef/util/CefAppLoader.kt | 1 | 7297 | /*
* GPLv3 License
* Copyright (c) SikuliCef by waicool20
*
* 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
*
* 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.waicool20.sikulicef.util
import org.cef.CefApp
import org.cef.CefSettings
import org.cef.handler.CefAppHandlerAdapter
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.net.URI
import java.net.URLClassLoader
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
object CefAppLoader {
val CODE_SOURCE: String = javaClass.protectionDomain.codeSource.location.toURI().path
val CEF_DIR: Path = Paths.get(System.getProperty("user.home")).resolve(".cef")
val LIB_DIR: Path = if (CODE_SOURCE.endsWith(".jar")) CEF_DIR else Paths.get("src/resources")
private val MAC_FRAMEWORK_DIR: Path by lazy { LIB_DIR.resolve("jcef_app.app/Contents/Frameworks/Chromium Embedded Framework.framework/") }
private val MAC_HELPER: Path by lazy { LIB_DIR.resolve("jcef_app.app/Contents/Frameworks/jcef Helper.app/Contents/MacOS/jcef Helper") }
private val JVM: Path by lazy { Paths.get(System.getProperty("java.home")) }
private val FAKE_JVM: Path by lazy { CEF_DIR.resolve("fakejvm") }
private val FAKE_JVM_BIN: Path by lazy { FAKE_JVM.resolve("bin") }
private val BINARIES by lazy { listOf("icudtl.dat", "natives_blob.bin", "snapshot_blob.bin") }
private val logger = LoggerFactory.getLogger(javaClass)
init {
loadBinaries()
loadLibraries()
}
private fun loadBinaries() {
// Hack for icudtl.dat discovery on linux
if (OS.isLinux()) {
Files.createDirectories(FAKE_JVM_BIN)
unpack(JVM.resolve("bin/java"), FAKE_JVM_BIN.resolve("java"))
BINARIES.forEach { unpack(javaClass.classLoader.getResourceAsStream("java-cef-res/binaries/$it"), FAKE_JVM_BIN.resolve(it)) }
FAKE_JVM.resolve("lib").let {
if (Files.notExists(it)) {
val target = JVM.resolve("lib")
logger.debug("[LINK] $it to $target")
Files.createSymbolicLink(it, target)
}
}
if (System.getenv("fakeJvm").isNullOrEmpty()) {
val java = FAKE_JVM_BIN.resolve("java")
logger.debug("Not running under fake JVM")
logger.debug("Main class: ${SystemUtils.mainClassName}")
logger.debug("Fake JVM path: $java")
val cp = (ClassLoader.getSystemClassLoader() as URLClassLoader).urLs.map { it.toString().replace("file:", "") }.joinToString(":")
with(ProcessBuilder(java.toString(), "-cp", cp, SystemUtils.mainClassName)) {
inheritIO()
environment().put("fakeJvm", FAKE_JVM.toString())
logger.debug("Launching new instance with fake JVM")
start().waitFor()
System.exit(0)
}
}
logger.debug("Running under fake JVM")
}
}
private fun loadLibraries() {
if (CODE_SOURCE.endsWith(".jar")) {
val jarURI = URI.create("jar:file:$CODE_SOURCE")
val env = mapOf(
"create" to "false",
"encoding" to "UTF-8"
)
Files.createDirectories(LIB_DIR)
(FileSystems.newFileSystem(jarURI, env)).use { fs ->
Files.walk(fs.getPath("/java-cef-res"))
.filter { !it.startsWith("/java-cef-res/binaries/") }
.filter { it.nameCount > 1 }
.map { it to LIB_DIR.resolve((if (it.nameCount > 2) it.subpath(1, it.nameCount) else it.fileName).toString().replace(".jarpak", ".jar")) }
.forEach {
unpack(it.first, it.second)
if (OS.isUnix()) {
val perms = Files.getPosixFilePermissions(it.second).toMutableSet()
perms.addAll(listOf(PosixFilePermission.OWNER_EXECUTE))
Files.setPosixFilePermissions(it.second, perms)
}
}
}
}
Files.walk(LIB_DIR)
.filter { it.toString().endsWith(OS.libraryExtention) }
.peek { SystemUtils.loadLibrary(it) } // Add to library path first
.forEach {
logger.debug("Loading library: $it")
try {
// Try loading it through System if possible, otherwise ignore and let CefApp take care of it
System.load(it.toAbsolutePath().toString())
} catch (e: UnsatisfiedLinkError) {
// Ignore
}
}
Files.walk(LIB_DIR).filter { it.toString().endsWith(".jar") }.forEach {
logger.debug("Loading jar library $it")
SystemUtils.loadJarLibrary(it)
}
if (OS.isMac()) {
MAC_FRAMEWORK_DIR.resolve("Chromium Embedded Framework").let {
logger.debug("Loading library: $it")
System.load(it.toString())
}
}
}
private fun <T> unpack(source: T, target: Path) {
if (Files.notExists(target)) {
when (source) {
is Path -> {
logger.debug("[COPY] $source to $target")
Files.copy(source, target)
}
is InputStream -> {
logger.debug("[UNPACKED] $target")
Files.copy(source, target)
}
else -> throw IllegalArgumentException()
}
}
}
fun load(args: Array<String> = arrayOf<String>(), cefSettings: CefSettings = CefSettings()): CefApp {
val arguments = args.toMutableList()
if (OS.isMac()) {
arguments.removeIf { it.startsWith("--framework-dir-path") || it.startsWith("--browser-subprocess-path") }
arguments.add("--framework-dir-path=$MAC_FRAMEWORK_DIR")
arguments.add("--browser-subprocess-path=$MAC_HELPER")
}
logger.debug("Using arguments: $arguments")
CefApp.addAppHandler(object : CefAppHandlerAdapter(arguments.toTypedArray()) {
override fun stateHasChanged(state: CefApp.CefAppState) {
logger.debug("CefApp state: $state")
if (state == CefApp.CefAppState.TERMINATED) System.exit(0)
}
})
return CefApp.getInstance(arguments.toTypedArray(), cefSettings)
}
}
| gpl-3.0 | 26a8d0f1937987123e4ab79e7db9e23a | 42.434524 | 162 | 0.572564 | 4.43048 | false | false | false | false |
GoogleCloudPlatform/kotlin-samples | getting-started/android-with-appengine/frontend/emojify/src/main/java/com/google/cloud/kotlin/emojify/ImageActivity.kt | 1 | 9246 | /*
* Copyright 2018 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.google.cloud.kotlin.emojify
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.util.NoSuchPropertyException
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.signature.ObjectKey
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.AlbumFile
import com.yanzhenjie.album.api.widget.Widget
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageMetadata
import com.google.firebase.storage.StorageReference
import com.yanzhenjie.album.widget.divider.Api21ItemDivider
import kotlinx.android.synthetic.main.activity_list_content.imageView
import kotlinx.android.synthetic.main.activity_list_content.recyclerView
import kotlinx.android.synthetic.main.activity_list_content.tvMessage
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.launch
import kotlinx.android.synthetic.main.toolbar.toolbar
import java.io.File
import java.util.ArrayList
import java.util.Properties
class ImageActivity : AppCompatActivity() {
private lateinit var backendUrl: String
private lateinit var adapter: Adapter
private val albumFiles: MutableList<AlbumFile> = mutableListOf()
private val job = Job()
private var emjojifiedUrl: String = ""
private var imageId: String = ""
private val storageRef: StorageReference = FirebaseStorage.getInstance().reference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_album)
setSupportActionBar(toolbar)
recyclerView.apply {
layoutManager = GridLayoutManager(this@ImageActivity, 3)
adapter = Adapter { _ -> previewImage(0) }
val divider = Api21ItemDivider(Color.TRANSPARENT, 10, 10)
addItemDecoration(divider)
}
val properties = Properties()
properties.load(assets.open("application.properties"))
val projectId = properties["cloud.project.id"] ?: throw NoSuchPropertyException("property 'cloud.project.id' doesn't exist in application.properties!")
backendUrl = "https://$projectId.appspot.com"
show("First, select picture to emojify!")
selectImage()
}
private fun show(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
private fun updateUI(fct: () -> Unit) = this.runOnUiThread(java.lang.Runnable(fct))
private fun callEmojifyBackend() {
val queue = Volley.newRequestQueue(this)
val url = "${this.backendUrl}/emojify?objectName=$imageId"
updateUI { show("Image uploaded to Storage!") }
val request = JsonObjectRequest(Request.Method.GET, url, null,
Response.Listener { response ->
val statusCode = response["statusCode"]
if (statusCode != "OK") {
updateUI {
show("Oops!")
tvMessage.text = response["errorMessage"].toString()
}
Log.i("backend response", "${response["statusCode"]}, ${response["errorCode"]}")
} else {
updateUI {
show("Yay!")
tvMessage.text = getString(R.string.waiting_over)
}
emjojifiedUrl = response["emojifiedUrl"].toString()
downloadAndShowImage()
}
deleteSourceImage()
},
Response.ErrorListener { err ->
updateUI {
show("Error calling backend!")
tvMessage.text = getString(R.string.backend_error)
}
Log.e("backend", err?.message)
deleteSourceImage()
})
request.retryPolicy = DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
queue.add(request)
}
private fun deleteSourceImage() = storageRef.child(imageId).delete()
.addOnSuccessListener { Log.i("deleted", "Source image successfully deleted!") }
.addOnFailureListener { err -> Log.e("delete", err.message) }
private fun uploadImage(path: String) {
val file = Uri.fromFile(File(path))
imageId = "${System.currentTimeMillis()}.jpg"
val imgRef = storageRef.child(imageId)
updateUI {
imageView.visibility = View.GONE
tvMessage!!.text = getString(R.string.waiting_msg_1)
}
imgRef.putFile(file, StorageMetadata.Builder().setContentType("image/jpg").build())
.addOnSuccessListener { _ ->
updateUI { tvMessage.text = getString(R.string.waiting_msg_2) }
callEmojifyBackend()
}
.addOnFailureListener { err ->
updateUI {
show("Cloud Storage error!")
tvMessage.text = getString(R.string.storage_error)
}
Log.e("storage", err.message)
}
}
private fun downloadAndShowImage() {
val url = emjojifiedUrl
updateUI {
Glide.with(this)
.load(url)
.apply(RequestOptions().signature(ObjectKey(System.currentTimeMillis())))
.apply(RequestOptions()
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.dontTransform()
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.skipMemoryCache(true))
.into(imageView)
}
imageView.visibility = View.VISIBLE
}
private fun load(path: String) =
launch(CommonPool + job) {
uploadImage(path)
}
private fun selectImage() {
Album.image(this)
.singleChoice()
.camera(true)
.columnCount(2)
.widget(
Widget.newDarkBuilder(this)
.title(toolbar!!.title.toString())
.build()
)
.onResult { result ->
albumFiles.clear()
albumFiles.addAll(result)
tvMessage.visibility = View.VISIBLE
if (result.size > 0) load(result[0].path)
}
.onCancel {
finish()
}
.start()
}
private fun previewImage(position: Int) {
if (albumFiles.isEmpty()) Toast.makeText(this, R.string.no_selected, Toast.LENGTH_LONG).show()
else {
Album.galleryAlbum(this)
.checkable(false)
.checkedList(albumFiles as ArrayList<AlbumFile>)
.currentPosition(position)
.widget(
Widget.newDarkBuilder(this)
.title(toolbar!!.title.toString())
.build()
)
.onResult { result ->
albumFiles.clear()
albumFiles.addAll(result)
adapter.submitList(albumFiles)
tvMessage.visibility = if (result.size > 0) View.VISIBLE else View.GONE
}
.start()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_album_image, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
android.R.id.home -> this.onBackPressed()
R.id.menu_eye -> previewImage(0)
}
return true
}
override fun onBackPressed() = selectImage()
} | apache-2.0 | 577bff9ae3549726ad0a9b98e3b09082 | 38.016878 | 159 | 0.600692 | 4.879156 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/parallax/ParallaxEmbed.kt | 1 | 1170 | package net.perfectdreams.loritta.cinnamon.discord.utils.parallax
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ParallaxEmbed(
val title: String? = null,
val description: String? = null,
val url: String? = null,
val image: ParallaxImage? = null,
val thumbnail: ParallaxThumbnail? = null,
val author: ParallaxAuthor? = null,
val footer: ParallaxFooter? = null,
val fields: List<ParallaxField> = listOf(),
val color: Int? = null,
) {
@Serializable
data class ParallaxImage(
val url: String
)
@Serializable
data class ParallaxThumbnail(
val url: String
)
@Serializable
data class ParallaxAuthor(
val name: String,
val url: String? = null,
@SerialName("icon_url")
val iconUrl: String? = null
)
@Serializable
data class ParallaxFooter(
val text: String,
@SerialName("icon_url")
val iconUrl: String? = null
)
@Serializable
data class ParallaxField(
val name: String,
val value: String,
val inline: Boolean = false
)
} | agpl-3.0 | 487da6f54b2beb4a7173b8d586e3edd8 | 22.897959 | 65 | 0.638462 | 4.178571 | false | false | false | false |
jitsi/jibri | src/main/kotlin/org/jitsi/jibri/service/JibriServiceStateMachine.kt | 1 | 4716 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.jibri.service
import com.tinder.StateMachine
import org.jitsi.jibri.status.ComponentState
import org.jitsi.jibri.util.NotifyingStateMachine
sealed class JibriServiceEvent {
class SubComponentStartingUp(val componentId: String, val subState: ComponentState.StartingUp) : JibriServiceEvent()
class SubComponentRunning(val componentId: String, val subState: ComponentState.Running) : JibriServiceEvent()
class SubComponentError(val componentId: String, val subState: ComponentState.Error) : JibriServiceEvent()
class SubComponentFinished(val componentId: String, val subState: ComponentState.Finished) : JibriServiceEvent()
}
fun ComponentState.toJibriServiceEvent(componentId: String): JibriServiceEvent {
return when (this) {
is ComponentState.StartingUp -> JibriServiceEvent.SubComponentStartingUp(componentId, this)
is ComponentState.Running -> JibriServiceEvent.SubComponentRunning(componentId, this)
is ComponentState.Error -> JibriServiceEvent.SubComponentError(componentId, this)
is ComponentState.Finished -> JibriServiceEvent.SubComponentFinished(componentId, this)
}
}
sealed class JibriServiceSideEffect
/**
* A state machine for the services to use to handle status updates from their subcomponents. Subcomponents should
* be registered via [JibriServiceStateMachine.registerSubComponent] such that the [JibriService]'s overall state
* can be computed as a function of the subcomponents' states.
*/
class JibriServiceStateMachine : NotifyingStateMachine() {
private val stateMachine = StateMachine.create<ComponentState, JibriServiceEvent, JibriServiceSideEffect> {
initialState(ComponentState.StartingUp)
state<ComponentState.StartingUp> {
on<JibriServiceEvent.SubComponentError> {
subComponentStates[it.componentId] = it.subState
transitionTo(ComponentState.Error(it.subState.error))
}
on<JibriServiceEvent.SubComponentFinished> {
subComponentStates[it.componentId] = it.subState
transitionTo(ComponentState.Finished)
}
on<JibriServiceEvent.SubComponentRunning> {
subComponentStates[it.componentId] = it.subState
if (subComponentStates.values.all { it is ComponentState.Running }) {
transitionTo(ComponentState.Running)
} else {
dontTransition()
}
}
on<JibriServiceEvent.SubComponentStartingUp> {
dontTransition()
}
}
state<ComponentState.Running> {
on<JibriServiceEvent.SubComponentError> {
subComponentStates[it.componentId] = it.subState
transitionTo(ComponentState.Error(it.subState.error))
}
on<JibriServiceEvent.SubComponentFinished> {
subComponentStates[it.componentId] = it.subState
transitionTo(ComponentState.Finished)
}
}
state<ComponentState.Error> {
on(any<JibriServiceEvent>()) {
dontTransition()
}
}
state<ComponentState.Finished> {
on(any<JibriServiceEvent>()) {
dontTransition()
}
}
onTransition {
val validTransition = it as? StateMachine.Transition.Valid ?: run {
throw Exception("Invalid state transition: $it")
}
if (validTransition.fromState::class != validTransition.toState::class) {
notify(validTransition.fromState, validTransition.toState)
}
}
}
private val subComponentStates = mutableMapOf<String, ComponentState>()
fun registerSubComponent(componentKey: String) {
// TODO: we'll assume everything starts in 'starting up' ?
subComponentStates[componentKey] = ComponentState.StartingUp
}
fun transition(event: JibriServiceEvent): StateMachine.Transition<*, *, *> = stateMachine.transition(event)
}
| apache-2.0 | 5fbb14638d70cea88b3b11753211c755 | 40.734513 | 120 | 0.678541 | 4.897196 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/utils/Fstrim.kt | 1 | 2413 | package com.androidvip.hebf.utils
import android.content.Context
import android.util.Log
import com.androidvip.hebf.services.FstrimWork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.util.*
//todo api 29
object Fstrim {
suspend fun fstrimLog(mode: String, context: Context) = withContext(Dispatchers.Default) {
val logFile = K.HEBF.getFstrimLog(context)
val prefs = Prefs(context)
val commands = ArrayList<String>()
if (prefs.getBoolean(K.PREF.FSTRIM_SYSTEM, true)) {
commands.add("busybox fstrim -v /system")
}
if (prefs.getBoolean(K.PREF.FSTRIM_DATA, true)) {
commands.add("busybox fstrim -v /data")
}
if (prefs.getBoolean(K.PREF.FSTRIM_CACHE, true)) {
commands.add("busybox fstrim -v /cache")
}
Log.d("testVerify", "commands added")
try {
val log = "Fstrim ($mode): ${Utils.dateMillisToString(System.currentTimeMillis(), "HH:mm:ss")}\n\n"
if (logFile.exists() || logFile.isFile) {
writeFile(logFile, mode, log, false)
} else {
if (logFile.createNewFile()) {
writeFile(logFile, mode, log, true)
} else {
Utils.runCommand("touch $logFile", "")
writeFile(logFile, mode, log, true)
}
}
commands.forEach { command ->
RootUtils.executeWithOutput(command) { line ->
writeFile(logFile, mode, "$line\n", true)
}
}
} catch (e: Exception) {
Logger.logError("Error while running fstrim: ${e.message}", context)
}
}
fun toggleService(start: Boolean, context: Context?) {
if (context == null) return
if (start) {
FstrimWork.scheduleJobPeriodic(context)
} else {
FstrimWork.cancelJob(context)
}
}
@Throws(Exception::class)
private fun writeFile(logFile: File, mode: String, log: String?, append: Boolean) {
val outputStream = FileOutputStream(logFile, append)
OutputStreamWriter(outputStream).apply {
append(log)
close()
}
outputStream.close()
}
}
| apache-2.0 | 66742415f24da9cc63b8d4a3e1bdbaed | 31.173333 | 111 | 0.578119 | 4.285968 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/report/protocol.kt | 1 | 6034 | package at.cpickl.gadsu.report
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.Gender
import at.cpickl.gadsu.image.MyImage
import at.cpickl.gadsu.report.multiprotocol.ReportMetaData
import at.cpickl.gadsu.service.formatTimeWithoutSeconds
import com.github.christophpickl.kpotpourri.common.string.nullIfEmpty
import com.google.common.annotations.VisibleForTesting
import org.joda.time.DateTime
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.util.Date
import javax.inject.Inject
fun MyImage.toReportRepresentation(): InputStream? {
val bytes = toSaveRepresentation() ?: return null //throw GadsuException("Can not transform a non-saveable image to report representation (are you trying to use a default pic for reports?!)")
return ByteArrayInputStream(bytes)
}
data class ProtocolReportData(
override val author: String,
override val printDate: DateTime,
val client: ClientReportData,
override val rows: List<TreatmentReportData>
) : ReportWithRows, ReportMetaData {
companion object {} // needed for extension
}
class ClientReportData(
val anonymizedName: String,
val picture: InputStream?,
val gender: Gender,
since: DateTime?,
birthday: DateTime?,
val birthPlace: String?,
val livePlace: String?,
val relationship: String?,
val children: String?,
val job: String?,
val hobbies: String?,
val textsNotes: String?,
val textsImpression: String?,
val textsMedical: String?,
val textsComplaints: String?,
val textsPersonal: String?,
val textsObjective: String?,
val textMainObjective: String?,
val textSymptoms: String?,
val textFiveElements: String?,
val textSyndrom: String?,
val tcmProps: String?,
val tcmNotes: String?
) {
companion object {} // needed for extension
val since: Date?
val birthday: Date?
init {
this.since = since?.toDate()
this.birthday = birthday?.toDate()
}
}
/**
* Used by Jasper to render fields in repeating detail band.
*/
@Suppress("unused")
class TreatmentReportData(
val id: String, // only used for DB insert, not for actual report (UI)
val number: Int,
date: DateTime,
duration: Int,
val aboutDiscomfort: String?,
val aboutDiagnosis: String?,
val aboutContent: String?,
val aboutFeedback: String?,
val aboutHomework: String?,
val aboutUpcoming: String?,
val note: String?,
val dynTreatments: String?,
val treatedMeridians: String?
) {
companion object {} // needed for extension
val date: Date
val time: String
val duration: Int
init {
this.date = date.toDate()
this.time = date.formatTimeWithoutSeconds()
this.duration = fakeDurationForProtocolFeedback(duration)
}
private fun fakeDurationForProtocolFeedback(duration: Int): Int {
when {
duration >= 90 -> return 70
duration >= 70 -> return 60
else -> return duration
}
}
}
interface ProtocolGenerator : GenericReportGenerator<ProtocolReportData> {
// all via super-interface
}
class JasperProtocolGenerator @Inject constructor(
engine: JasperEngine
) : BaseReportGenerator<ProtocolReportData>(TEMPLATE_CLASSPATH, engine), ProtocolGenerator {
companion object {
private val TEMPLATE_CLASSPATH = "/gadsu/reports/protocol.jrxml"
}
override fun buildParameters(report: ProtocolReportData) = arrayOf(
Pair("countTreatments", report.rows.size), // MINOR @REPORT - counting row items is most likely possible to do in jasper itself
Pair("client_picture", report.client.picture),
Pair("client_name", report.client.anonymizedName),
Pair("client_since", report.client.since),
Pair("client_salutation", buildSalutation(report.client.gender)),
Pair("client_birthday", report.client.birthday),
Pair("client_birthplace", report.client.birthPlace?.nullIfEmpty()),
Pair("client_liveplace", report.client.livePlace?.nullIfEmpty()),
Pair("client_relationship", report.client.relationship?.nullIfEmpty()),
Pair("client_children", report.client.children?.nullIfEmpty()),
Pair("client_job", report.client.job?.nullIfEmpty()),
Pair("client_hobbys", report.client.hobbies?.nullIfEmpty()),
Pair("texts_notes", report.client.textsNotes?.nullIfEmpty()),
Pair("texts_impression", report.client.textsImpression?.nullIfEmpty()),
Pair("texts_medical", report.client.textsMedical?.nullIfEmpty()),
Pair("texts_complaints", report.client.textsComplaints?.nullIfEmpty()),
Pair("texts_personal", report.client.textsPersonal?.nullIfEmpty()),
Pair("texts_objective", report.client.textsObjective?.nullIfEmpty()),
Pair("client_mainObjective", report.client.textMainObjective?.nullIfEmpty()),
Pair("client_symptoms", report.client.textSymptoms?.nullIfEmpty()),
Pair("client_fiveElements", report.client.textFiveElements?.nullIfEmpty()),
Pair("client_syndrom", report.client.textSyndrom?.nullIfEmpty()),
// Pair("author", report.author),
// Pair("printDate", report.printDate.formatDate()),
Pair("tcm_properties", report.client.tcmProps),
Pair("tcm_notes", report.client.tcmNotes)
)
private fun buildSalutation(gender: Gender): String {
val salut = if (gender == Gender.MALE) "Klient" else if (gender == Gender.FEMALE) "Klientin" else "KlientIn"
return "$salut seit:"
}
}
@VisibleForTesting
val Client.anonymizedName: String get() {
if (lastName.isEmpty()) {
return firstName
}
return firstName + " " + lastName.substring(0, 1) + "."
}
| apache-2.0 | fa25e5492eeaf8fdad1eca3f380b213b | 33.284091 | 195 | 0.660259 | 4.414045 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/inspection/TFNoInterpolationsAllowedInspection.kt | 1 | 5770 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.plugins.hcl.terraform.config.inspection
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.PsiElementPattern
import com.intellij.psi.InjectedLanguagePlaces
import com.intellij.psi.PsiElementVisitor
import com.intellij.util.ProcessingContext
import org.intellij.plugins.hcl.psi.*
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns.ModuleRootBlock
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns.ResourceRootBlock
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns.TerraformRootBlock
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns.VariableRootBlock
import org.intellij.plugins.hil.ILLanguageInjector
import java.util.*
class TFNoInterpolationsAllowedInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val file = holder.file
if (!TerraformPatterns.TerraformConfigFile.accepts(file)) {
return super.buildVisitor(holder, isOnTheFly)
}
return MyEV(holder)
}
companion object {
val StringLiteralAnywhereInVariable: PsiElementPattern.Capture<HCLStringLiteral> =
psiElement(HCLStringLiteral::class.java)
.inside(true, VariableRootBlock)
val HeredocContentAnywhereInVariable: PsiElementPattern.Capture<HCLHeredocContent> =
psiElement(HCLHeredocContent::class.java)
.inside(true, VariableRootBlock)
val DependsOnPropertyOfResource: PsiElementPattern.Capture<HCLProperty> =
psiElement(HCLProperty::class.java)
.withSuperParent(1, HCLObject::class.java)
.withSuperParent(2, ResourceRootBlock)
.with(object : PatternCondition<HCLProperty?>("HCLProperty(depends_on)") {
override fun accepts(t: HCLProperty, context: ProcessingContext?): Boolean {
return t.name == "depends_on"
}
})
}
inner class MyEV(val holder: ProblemsHolder) : HCLElementVisitor() {
override fun visitBlock(block: HCLBlock) {
if (ModuleRootBlock.accepts(block)) {
checkModule(block)
} else if (TerraformRootBlock.accepts(block)) {
checkTerraform(block)
}
}
override fun visitStringLiteral(o: HCLStringLiteral) {
if (StringLiteralAnywhereInVariable.accepts(o)) {
checkForVariableInterpolations(o)
}
}
override fun visitHeredocContent(o: HCLHeredocContent) {
if (HeredocContentAnywhereInVariable.accepts(o)) {
checkForVariableInterpolations(o)
}
}
override fun visitProperty(o: HCLProperty) {
if (DependsOnPropertyOfResource.accepts(o)) {
checkDependsOnOfResource(o)
}
}
private fun checkModule(block: HCLBlock) {
// Ensure there's no interpolation in module 'source' string
val source = block.`object`?.findProperty("source")?.value
if (source != null) {
if (source is HCLStringLiteral) {
reportRanges(source, "module source")
} else {
holder.registerProblem(source, "Module source should be a double quoted string")
}
}
}
private fun checkTerraform(block: HCLBlock) {
// Ensure there's no interpolation in all string properties
(block.`object`?.propertyList ?: return)
.map { it.value }
.filterIsInstance<HCLStringLiteral>()
.forEach { reportRanges(it, "properties inside 'terraform' block") }
}
private fun checkForVariableInterpolations(o: HCLStringLiteral) {
reportRanges(o, "variables")
}
private fun checkForVariableInterpolations(o: HCLHeredocContent) {
val ranges = ArrayList<TextRange>()
ILLanguageInjector.getHCLHeredocContentInjections(o, getInjectedLanguagePlacesCollector(ranges))
for (range in ranges) {
holder.registerProblem(o, "Interpolations are not allowed in variables", ProblemHighlightType.ERROR, range)
}
}
private fun checkDependsOnOfResource(o: HCLProperty) {
val value = o.value as? HCLArray ?: return
val list = value.valueList
for (e in list) {
if (e is HCLStringLiteral) {
reportRanges(e, "depends_on")
}
}
}
private fun reportRanges(e: HCLStringLiteral, where: String) {
val ranges = ArrayList<TextRange>()
ILLanguageInjector.getStringLiteralInjections(e, getInjectedLanguagePlacesCollector(ranges))
for (range in ranges) {
holder.registerProblem(e, "Interpolations are not allowed in $where", ProblemHighlightType.ERROR, range)
}
}
private fun getInjectedLanguagePlacesCollector(ranges: ArrayList<TextRange>) =
InjectedLanguagePlaces { _, rangeInsideHost, _, _ -> ranges.add(rangeInsideHost) }
}
}
| apache-2.0 | 94cdd37e6a78eecec9dd01d73351e2b5 | 38.251701 | 115 | 0.72201 | 4.479814 | false | false | false | false |
jean79/yested_fw | src/jsMain/kotlin/net/yested/core/utils/htmlutils.kt | 1 | 1636 | package net.yested.core.utils
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.Node
import kotlin.browser.document
import kotlin.browser.window
import kotlin.dom.appendText
fun Node.removeAllChildElements() {
while (this.firstChild != null) {
this.removeChild(this.firstChild!!)
}
}
fun HTMLElement.removeChildByName(childElementName:String) {
val elements = this.getElementsByTagName(childElementName)
(0..elements.length-1).forEach {
this.removeChild(elements.item(it)!!)
}
}
fun Node.setChild(child: Node) {
removeAllChildElements()
appendChild(child)
}
fun HTMLElement.setContent(content: String) {
removeAllChildElements()
appendText(content)
}
fun HTMLElement.whenAddedToDom(run: () -> Unit) {
repeatWithDelayUntil (
check = { isIncludedInDOM(this) },
millisecondInterval = 100,
run = run
)
}
fun isIncludedInDOM(node:Node):Boolean {
/*var style = window.getComputedStyle(node);
return style.display != "none" && style.display != ""*/
return (node as HTMLElement).offsetParent != null
}
fun repeatWithDelayUntil(check:()->Boolean, millisecondInterval:Int, run:()->Unit) {
if (check()) {
run()
} else {
window.setTimeout({repeatWithDelayUntil(check, millisecondInterval, run)}, millisecondInterval)
}
}
/** Creates a Div that is not attached to any parent HTMLElement yet. */
fun Div(init:(HTMLDivElement.()->Unit)? = null): HTMLDivElement {
val element: HTMLDivElement = document.createElement("div").asDynamic()
init?.let { element.init() }
return element
}
| mit | 83d34406f8f5c9708202456a2e5bccb3 | 26.266667 | 102 | 0.699878 | 3.904535 | false | false | false | false |
vmmaldonadoz/android-reddit-example | Reddit/app/src/main/java/com/thirdmono/reddit/presentation/list/presenter/ListPresenter.kt | 1 | 4054 | package com.thirdmono.reddit.presentation.list.presenter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.thirdmono.reddit.data.api.RedditsService
import com.thirdmono.reddit.data.entity.Listing
import com.thirdmono.reddit.data.entity.Reddit
import com.thirdmono.reddit.data.entity.Thing
import com.thirdmono.reddit.doIfBothAreNotNull
import com.thirdmono.reddit.domain.utils.Constants
import com.thirdmono.reddit.domain.utils.Utils
import com.thirdmono.reddit.presentation.BaseView
import com.thirdmono.reddit.presentation.details.DetailsActivity
import com.thirdmono.reddit.presentation.list.ListContract
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class ListPresenter @Inject
constructor(private val redditsService: RedditsService) : ListContract.Presenter {
private var view: ListContract.View? = null
private var connectionBroadcastReceiver: BroadcastReceiver? = null
private var nextPage: String? = null
override fun resume() {
doIfBothAreNotNull(view, connectionBroadcastReceiver) { view, broadcastReceiver ->
view.registerConnectionBroadcastReceiver(broadcastReceiver)
}
}
override fun pause() {
doIfBothAreNotNull(view, connectionBroadcastReceiver) { view, broadcastReceiver ->
view.unRegisterConnectionBroadcastReceiver(broadcastReceiver)
}
}
override fun destroy() {
connectionBroadcastReceiver = null
nextPage = null
}
override fun setView(view: BaseView) {
this.view = view as ListContract.View
}
override fun onItemClicked(context: Context, thing: Thing) {
// Launch Activity
val intent = Intent(context, DetailsActivity::class.java)
intent.putExtra(Constants.REDDIT_SELECTED_KEY, Utils.toString(thing))
this.view?.startActivity(intent)
}
override fun getReddits() {
redditsService.getPaginatedReddits().enqueue(object : Callback<Reddit> {
override fun onResponse(call: Call<Reddit>, response: Response<Reddit>) {
Timber.d("Got some feed back!")
if (response.isSuccessful) {
val entries = getListOfApplications(response.body())
if (entries.isEmpty()) {
view?.showEmptyResponseMessage()
Timber.i("Empty response from API.")
} else {
view?.updateListOfReddits(entries)
Timber.i("Apps data was loaded from API.")
}
}
}
override fun onFailure(call: Call<Reddit>, t: Throwable) {
Timber.e(t, "Failed to get feed!")
view?.showErrorDuringRequestMessage()
}
})
}
private fun getListOfApplications(feedWrapper: Reddit?): List<Thing> {
var listing: Listing? = null
var things: List<Thing> = ArrayList()
if (feedWrapper != null) {
listing = feedWrapper.listing
}
if (listing != null) {
if (listing.things != null && !listing.things.isEmpty()) {
Timber.i("getListOfApplications(): size: %s", listing.things.size)
things = listing.things
} else {
Timber.w("getListOfApplications(): Empty entries.")
}
} else {
Timber.w("getListOfApplications(): Empty listing!")
}
return things
}
override fun setupConnectionBroadcastReceiver() {
connectionBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (Utils.hasNetwork(context)) {
view?.hideNoConnectionMessage()
} else {
view?.showNoConnectionMessage()
}
}
}
}
}
| apache-2.0 | 4856388bac95ceebffd5d9c51f1f0883 | 34.876106 | 90 | 0.634682 | 4.843489 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | settings/src/main/kotlin/voice/settings/views/TimeSettingDialog.kt | 1 | 1800 | package voice.settings.views
import androidx.annotation.PluralsRes
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Slider
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import voice.settings.R
import kotlin.math.roundToInt
@Composable
fun TimeSettingDialog(
title: String,
currentSeconds: Int,
@PluralsRes textPluralRes: Int,
minSeconds: Int,
maxSeconds: Int,
onSecondsConfirmed: (Int) -> Unit,
onDismiss: () -> Unit
) {
val sliderValue = remember { mutableStateOf(currentSeconds.toFloat()) }
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(text = title)
},
text = {
Column {
Text(
LocalContext.current.resources.getQuantityString(
textPluralRes,
sliderValue.value.roundToInt(),
sliderValue.value.roundToInt()
)
)
}
Slider(
valueRange = minSeconds.toFloat()..maxSeconds.toFloat(),
value = sliderValue.value,
onValueChange = {
sliderValue.value = it
}
)
},
confirmButton = {
TextButton(
onClick = {
onSecondsConfirmed(sliderValue.value.roundToInt())
onDismiss()
}
) {
Text(stringResource(R.string.dialog_confirm))
}
},
dismissButton = {
TextButton(
onClick = {
onDismiss()
}
) {
Text(stringResource(R.string.dialog_cancel))
}
}
)
}
| lgpl-3.0 | 731ba61ef2220e1ef7a13bf8961ce466 | 24.352113 | 73 | 0.655 | 4.5 | false | false | false | false |
Commit451/YouTubeExtractor | youtubeextractor/src/main/java/com/commit451/youtubeextractor/PlayerConfig.kt | 1 | 426 | package com.commit451.youtubeextractor
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class PlayerConfig(
@Json(name = "args")
var args: PlayerArgs? = null,
@Json(name = "assets")
var assets: Assets? = null
) {
@JsonClass(generateAdapter = true)
data class Assets(
@Json(name = "js")
var js: String? = null
)
}
| apache-2.0 | 8c9a4037bf599aae78cdebc8b223d090 | 22.666667 | 38 | 0.664319 | 3.641026 | false | true | false | false |
westoncb/HNDesktop | src/main/java/Item.kt | 1 | 1007 | import com.google.gson.JsonObject
import org.ocpsoft.prettytime.PrettyTime
import java.util.*
val prettyTime = PrettyTime()
open class Item(itemNode: JsonObject) {
val id = itemNode.get("id").asInt
val type = itemNode.get("type").asString
val text = itemNode.get("text")?.asString
val dead = itemNode.get("dead")?.asBoolean
val title = itemNode.get("title")?.asString
val points = itemNode.get("score")?.asInt
// Note: the results PrettyTime is giving do not match actual HN... not sure
// where the problem is
val time = prettyTime.format(Date(itemNode.get("time").asLong * 1000))
val kids = itemNode.get("kids")?.asJsonArray
val numKids = kids?.size()
val user = itemNode.get("by")?.asString
val url = itemNode.get("url")?.asString
val totalComments = itemNode.get("descendants")?.asInt
override fun toString(): String {
return "ID: " + id + ", Type: " + type + ", Title: " + title + ", dead: " + dead + ", kids: " + numKids
}
} | mit | a97e5f771d2b2091e0334e4f7f64f687 | 35 | 111 | 0.652433 | 3.648551 | false | false | false | false |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/queue/data/BuildQueueDataManagerImpl.kt | 1 | 3264 | /*
* Copyright 2019 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.queue.data
import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener
import com.github.vase4kin.teamcityapp.api.Repository
import com.github.vase4kin.teamcityapp.buildlist.data.BuildListDataManagerImpl
import com.github.vase4kin.teamcityapp.overview.data.BuildDetails
import com.github.vase4kin.teamcityapp.runningbuilds.data.RunningBuildsDataManager
import com.github.vase4kin.teamcityapp.storage.SharedUserStorage
import io.reactivex.Observable
/**
* Data manager to handle build queue server operations
*/
class BuildQueueDataManagerImpl(
repository: Repository,
private val storage: SharedUserStorage
) : BuildListDataManagerImpl(repository, storage), RunningBuildsDataManager {
/**
* {@inheritDoc}
*/
override fun load(loadingListener: OnLoadingListener<List<BuildDetails>>, update: Boolean) {
val runningBuilds = getBuildDetailsObservable(repository.listQueueBuilds(null, null, update))
.toSortedList { buildDetails, buildDetails2 ->
buildDetails.buildTypeId.compareTo(buildDetails2.buildTypeId, ignoreCase = true)
}
loadBuildDetailsList(runningBuilds, loadingListener)
}
/**
* {@inheritDoc}
*/
override fun loadFavorites(loadingListener: OnLoadingListener<List<BuildDetails>>, update: Boolean) {
val runningBuildsByBuildTypeIds = Observable.fromIterable(storage.favoriteBuildTypeIds)
.flatMap { buildTypeId ->
val locator = buildTypeIdLocator(buildTypeId)
getBuildDetailsObservable(repository.listQueueBuilds(locator, null, update))
}.toSortedList { buildDetails, buildDetails2 ->
buildDetails.buildTypeId.compareTo(buildDetails2.buildTypeId, ignoreCase = true)
}
loadBuildDetailsList(runningBuildsByBuildTypeIds, loadingListener)
}
/**
* {@inheritDoc}
*/
override fun loadCount(loadingListener: OnLoadingListener<Int>) {
loadCount(repository.listQueueBuilds(null, "count", false).map { it.count }, loadingListener)
}
/**
* {@inheritDoc}
*/
override fun loadFavoritesCount(loadingListener: OnLoadingListener<Int>) {
val runningBuildsByBuildTypeIds = Observable.fromIterable(storage.favoriteBuildTypeIds)
.flatMapSingle { buildTypeId ->
val locator = buildTypeIdLocator(buildTypeId)
repository.listQueueBuilds(locator, "count", false)
.map { it.count }
}.toList().map { it.sum() }
loadCount(runningBuildsByBuildTypeIds, loadingListener)
}
}
| apache-2.0 | b1772bf91ba372566ad44817b3d443b9 | 40.316456 | 105 | 0.717831 | 4.58427 | false | false | false | false |
HendraAnggrian/kota | kota-appcompat-v7/src/layouts/WidgetsV7.kt | 1 | 5474 | @file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.app.Dialog
import android.content.Context
import android.support.v4.app.Fragment
import android.support.v7.widget.*
import android.support.v7.widget.LinearLayoutCompat.HORIZONTAL
import android.support.v7.widget.LinearLayoutCompat.VERTICAL
//region Layouts
inline fun Context.supportActionMenuView(init: (@KotaDsl _ActionMenuViewV7).() -> Unit): ActionMenuView = _ActionMenuViewV7(this).apply(init)
inline fun android.app.Fragment.supportActionMenuView(init: (@KotaDsl _ActionMenuViewV7).() -> Unit): ActionMenuView = _ActionMenuViewV7(activity).apply(init)
inline fun Fragment.supportActionMenuView(init: (@KotaDsl _ActionMenuViewV7).() -> Unit): ActionMenuView = _ActionMenuViewV7(context!!).apply(init)
inline fun Dialog.supportActionMenuView(init: (@KotaDsl _ActionMenuViewV7).() -> Unit): ActionMenuView = _ActionMenuViewV7(context).apply(init)
inline fun ViewRoot.supportActionMenuView(init: (@KotaDsl _ActionMenuViewV7).() -> Unit): ActionMenuView = _ActionMenuViewV7(getContext()).apply(init).add()
inline fun Context.verticalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(this, VERTICAL).apply(init)
inline fun android.app.Fragment.verticalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(activity, VERTICAL).apply(init)
inline fun Fragment.verticalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(context!!, VERTICAL).apply(init)
inline fun Dialog.verticalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(context, VERTICAL).apply(init)
inline fun ViewRoot.verticalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(getContext(), VERTICAL).apply(init).add()
inline fun Context.horizontalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(this, HORIZONTAL).apply(init)
inline fun android.app.Fragment.horizontalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(activity, HORIZONTAL).apply(init)
inline fun Fragment.horizontalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(context!!, HORIZONTAL).apply(init)
inline fun Dialog.horizontalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(context, HORIZONTAL).apply(init)
inline fun ViewRoot.horizontalLayoutCompat(init: (@KotaDsl _LinearLayoutCompat).() -> Unit): LinearLayoutCompat = _LinearLayoutCompat(getContext(), HORIZONTAL).apply(init).add()
inline fun Context.supportToolbar(init: (@KotaDsl _ToolbarV7).() -> Unit): Toolbar = _ToolbarV7(this).apply(init)
inline fun android.app.Fragment.supportToolbar(init: (@KotaDsl _ToolbarV7).() -> Unit): Toolbar = _ToolbarV7(activity).apply(init)
inline fun Fragment.supportToolbar(init: (@KotaDsl _ToolbarV7).() -> Unit): Toolbar = _ToolbarV7(context!!).apply(init)
inline fun Dialog.supportToolbar(init: (@KotaDsl _ToolbarV7).() -> Unit): Toolbar = _ToolbarV7(context).apply(init)
inline fun ViewRoot.supportToolbar(init: (@KotaDsl _ToolbarV7).() -> Unit): Toolbar = _ToolbarV7(getContext()).apply(init).add()
//endregion
//region Views
inline fun Context.contentFrameLayout(init: (@KotaDsl ContentFrameLayout).() -> Unit): ContentFrameLayout = ContentFrameLayout(this).apply(init)
inline fun android.app.Fragment.contentFrameLayout(init: (@KotaDsl ContentFrameLayout).() -> Unit): ContentFrameLayout = ContentFrameLayout(activity).apply(init)
inline fun Fragment.contentFrameLayout(init: (@KotaDsl ContentFrameLayout).() -> Unit): ContentFrameLayout = ContentFrameLayout(context).apply(init)
inline fun Dialog.contentFrameLayout(init: (@KotaDsl ContentFrameLayout).() -> Unit): ContentFrameLayout = ContentFrameLayout(context).apply(init)
inline fun ViewRoot.contentFrameLayout(init: (@KotaDsl ContentFrameLayout).() -> Unit): ContentFrameLayout = ContentFrameLayout(getContext()).apply(init).add()
inline fun Context.supportSearchView(init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(this).apply(init)
inline fun android.app.Fragment.supportSearchView(init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(activity).apply(init)
inline fun Fragment.supportSearchView(init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(context).apply(init)
inline fun Dialog.supportSearchView(init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(context).apply(init)
inline fun ViewRoot.supportSearchView(init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(getContext()).apply(init).add()
inline fun Context.switchCompat(init: (@KotaDsl SwitchCompat).() -> Unit): SwitchCompat = SwitchCompat(this).apply(init)
inline fun android.app.Fragment.switchCompat(init: (@KotaDsl SwitchCompat).() -> Unit): SwitchCompat = SwitchCompat(activity).apply(init)
inline fun Fragment.switchCompat(init: (@KotaDsl SwitchCompat).() -> Unit): SwitchCompat = SwitchCompat(context).apply(init)
inline fun Dialog.switchCompat(init: (@KotaDsl SwitchCompat).() -> Unit): SwitchCompat = SwitchCompat(context).apply(init)
inline fun ViewRoot.switchCompat(init: (@KotaDsl SwitchCompat).() -> Unit): SwitchCompat = SwitchCompat(getContext()).apply(init).add()
//endregion | apache-2.0 | a58617c02a69b5e2d17d74872d19a089 | 93.396552 | 179 | 0.779686 | 4.191424 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/lang/core/resolve/RsTypeAwareResolveTest.kt | 1 | 11767 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import junit.framework.AssertionFailedError
class RsTypeAwareResolveTest : RsResolveTestBase() {
fun testSelfMethodCallExpr() = checkByCode("""
struct S;
impl S {
fn bar(self) { }
//X
fn foo(self) { self.bar() }
//^
}
""")
fun `test trait impl method`() = checkByCode("""
trait T { fn foo(&self); }
struct S;
impl T for S { fn foo(&self) {} }
//X
fn foo(s: S) {
s.foo()
} //^
""")
fun `test trait impl for various types`() {
for (type in listOf("bool", "char", "&str", "u32", "f32", "f64", "()", "(i32)", "(i16,)", "(u32, u16)",
"[u8; 1]", "&[u16]", "*const u8", "*const i8", "fn(u32) -> u8", "!")) {
checkByCode("""
trait T { fn foo(&self) {} }
impl T for $type {
fn foo(&self) {}
} //X
fn test(s: $type) {
s.foo()
} //^
""")
}
}
fun `test trait default method`() = checkByCode("""
trait T { fn foo(&self) {} }
//X
struct S;
impl T for S { }
fn foo(s: S) {
s.foo()
} //^
""")
fun `test trait overridden default method`() = checkByCode("""
trait T { fn foo(&self) {} }
struct S;
impl T for S { fn foo(&self) {} }
//X
fn foo(s: S) {
s.foo()
} //^
""")
fun testMethodReference() = checkByCode("""
//- main.rs
mod x;
use self::x::Stdin;
fn main() {
Stdin::read_line;
//^
}
//- x.rs
pub struct Stdin { }
impl Stdin {
pub fn read_line(&self) { }
//X
}
""")
fun testMethodCallOnTraitObject() = stubOnlyResolve("""
//- main.rs
mod aux;
use aux::T;
fn call_virtually(obj: &T) { obj.virtual_function() }
//^ aux.rs
//- aux.rs
trait T {
fn virtual_function(&self) {}
}
""")
fun testMethodInherentVsTraitConflict() = checkByCode("""
struct Foo;
impl Foo {
fn bar(&self) {}
//X
}
trait Bar {
fn bar(&self);
}
impl Bar for Foo {
fn bar(&self) {}
}
fn main() {
let foo = Foo;
foo.bar();
//^
}
""")
fun testSelfFieldExpr() = checkByCode("""
struct S { x: f32 }
//X
impl S {
fn foo(&self) { self.x; }
//^
}
""")
fun testFieldExpr() = stubOnlyResolve("""
//- main.rs
mod aux;
use aux::S;
fn main() {
let s: S = S { x: 0. };
s.x;
//^ aux.rs
}
//- aux.rs
struct S { x: f32 }
""")
fun testTupleFieldExpr() = checkByCode("""
struct T;
impl T { fn foo(&self) {} }
//X
struct S(T);
impl S {
fn foo(&self) {
let s = S(92.0);
s.0.foo();
//^
}
}
""")
fun testTupleFieldExprOutOfBounds() = checkByCode("""
struct S(f64);
impl S {
fn foo(&self) {
let s: S = S(92.0);
s.92;
//^ unresolved
}
}
""")
fun testTupleFieldExprSuffix() = checkByCode("""
struct S(f64);
impl S {
fn foo(&self) {
let s: S = S(92.0);
s.0u32;
//^ unresolved
}
}
""")
fun testNestedFieldExpr() = checkByCode("""
struct Foo { bar: Bar }
struct Bar { baz: i32 }
//X
fn main() {
let foo = Foo { bar: Bar { baz: 92 } };
foo.bar.baz;
//^
}
""")
fun testLetDeclCallExpr() = checkByCode("""
struct S { x: f32 }
//X
fn bar() -> S {}
impl S {
fn foo(&self) {
let s = bar();
s.x;
//^
}
}
""")
fun testLetDeclMethodCallExpr() = checkByCode("""
struct S { x: f32 }
//X
impl S {
fn bar(&self) -> S {}
fn foo(&self) {
let s = self.bar();
s.x;
//^
}
}
""")
fun testLetDeclPatIdentExpr() = checkByCode("""
struct S { x: f32 }
//X
impl S {
fn foo(&self) {
let s = S { x: 0. };
s.x;
//^
}
}
""")
fun testLetDeclPatTupExpr() = checkByCode("""
struct S { x: f32 }
//X
impl S {
fn foo(&self) {
let (_, s) = ((), S { x: 0. });
s.x;
//^
}
}
""")
fun testLetDeclPatStructExpr() = checkByCode("""
struct S { x: f32 }
impl S {
fn foo(&self) {
let S { x: x } = S { x: 0. };
//X
x;
//^
}
}
""")
fun testLetDeclPatStructExprComplex() = checkByCode("""
struct S { x: f32 }
//X
struct X { s: S }
impl S {
fn foo(&self) {
let X { s: f } = X { s: S { x: 0. } };
f.x;
//^
}
}
""")
fun testAssociatedFnFromInherentImpl() = checkByCode("""
struct S;
impl S { fn test() { } }
//X
fn main() { S::test(); }
//^
""")
fun testAssociatedFunctionInherentVsTraitConflict() = checkByCode("""
struct Foo;
impl Foo {
fn bar() {}
//X
}
trait Bar {
fn bar();
}
impl Bar for Foo {
fn bar() {}
}
fn main() {
Foo::bar();
//^
}
""")
fun testHiddenInherentImpl() = checkByCode("""
struct S;
fn main() {
let s: S = S;
s.transmogrify();
//^
}
mod hidden {
use super::S;
impl S { pub fn transmogrify(self) -> S { S } }
//X
}
""")
fun testWrongInherentImpl() = checkByCode("""
struct S;
fn main() {
let s: S = S;
s.transmogrify();
//^ unresolved
}
mod hidden {
struct S;
impl S { pub fn transmogrify(self) -> S { S } }
}
""")
fun testNonInherentImpl1() = checkByCode("""
struct S;
mod m {
trait T { fn foo(); }
}
mod hidden {
use super::S;
use super::m::T;
impl T for S { fn foo() {} }
//X
}
fn main() {
use m::T;
let _ = S::foo();
//^
}
""")
fun testSelfImplementsTrait() = checkByCode("""
trait Foo {
fn foo(&self);
//X
fn bar(&self) { self.foo(); }
//^
}
""")
fun testSelfImplementsTraitFromBound() = checkByCode("""
trait Bar {
fn bar(&self);
//X
}
trait Foo : Bar {
fn foo(&self) { self.bar(); }
//^
}
""")
fun `test can't import methods`() = checkByCode("""
mod m {
pub enum E {}
impl E {
pub fn foo() {}
}
}
use self::m::E::foo;
//^ unresolved
""")
fun testMatchEnumTupleVariant() = checkByCode("""
enum E { V(S) }
struct S;
impl S { fn frobnicate(&self) {} }
//X
impl E {
fn foo(&self) {
match *self {
E::V(ref s) => s.frobnicate()
} //^
}
}
""")
fun testStatic() = checkByCode("""
struct S { field: i32 }
//X
const FOO: S = S { field: 92 };
fn main() {
FOO.field;
} //^
""")
fun `test string slice resolve`() = checkByCode("""
impl<T> &str {
fn foo(&self) {}
//X
}
fn main() {
"test".foo();
//^
}
""")
fun `test slice resolve`() = checkByCode("""
impl<T> [T] {
fn foo(&self) {}
//X
}
fn main() {
let x: &[i32];
x.foo();
//^
}
""")
fun `test slice resolve UFCS`() = expect<AssertionFailedError> {
checkByCode("""
impl<T> [T] {
fn foo(&self) {}
//X
}
fn main() {
let x: &[i32];
<[i32]>::foo(x);
//^
}
""")
}
fun `test array coercing to slice resolve`() = checkByCode("""
impl<T> [T] {
fn foo(&self) {}
//X
}
fn main() {
let x: [i32; 1];
x.foo();
//^
}
""")
// https://github.com/intellij-rust/intellij-rust/issues/1269
fun `test tuple field`() = checkByCode("""
struct Foo;
impl Foo {
fn foo(&self) { unimplemented!() }
//X
}
fn main() {
let t = (1, Foo());
t.1.foo();
//^
}
""")
fun `test array to slice`() = checkByCode("""
struct Foo;
impl Foo {
fn foo(&self) { unimplemented!() }
//X
}
fn foo<T>(xs: &[T]) -> T { unimplemented!() }
fn main() {
let x = foo(&[Foo(), Foo()]);
x.foo()
//^
}
""")
fun `test tuple paren cast 1`() = checkByCode("""
struct Foo;
impl Foo { fn foo(&self) {} }
//X
fn main() {
let foo = unimplemented!() as (Foo);
foo.foo();
} //^
""")
fun `test tuple paren cast 2`() = checkByCode("""
struct Foo;
impl Foo { fn foo(&self) {} }
fn main() {
let foo = unimplemented!() as (Foo,);
foo.foo();
} //^ unresolved
""")
// https://github.com/intellij-rust/intellij-rust/issues/1549
fun `test Self type in assoc function`() = checkByCode("""
struct Foo;
impl Foo {
fn new() -> Self { unimplemented!() }
fn bar(&self) {}
//X
}
fn main() {
let foo = Foo::new();
foo.bar();
//^
}
""")
fun `test incomplete dot expr`() = checkByCode("""
struct Foo;
impl Foo {
fn foo(&self) {}
//X
}
fn main() {
Foo.foo().
//^
}
""")
}
| mit | 9aae31b71b6744aebd6b1a97c211682c | 19.975045 | 111 | 0.342823 | 4.403817 | false | true | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/apps/processors/UpdateAppMetadataProcessor.kt | 1 | 946 | package com.openlattice.apps.processors
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
import com.openlattice.apps.App
import com.openlattice.edm.requests.MetadataUpdate
import java.util.*
import kotlin.collections.MutableMap.MutableEntry
data class UpdateAppMetadataProcessor(val update: MetadataUpdate) : AbstractRhizomeEntryProcessor<UUID, App?, Boolean>() {
override fun process(entry: MutableEntry<UUID, App?>): Boolean {
val app = entry.value ?: return false
if (update.title.isPresent) {
app.title = update.title.get()
}
if (update.description.isPresent) {
app.description = update.description.get()
}
if (update.name.isPresent) {
app.name = update.name.get()
}
if (update.url.isPresent) {
app.url = update.url.get()
}
entry.setValue(app)
return true
}
} | gpl-3.0 | d9b0bb036cb7332edd38a00caca092d2 | 29.548387 | 122 | 0.664905 | 4.359447 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/ChapterTypeAdapter.kt | 4 | 1924 | package eu.kanade.tachiyomi.data.backup.serializer
import com.github.salomonbrys.kotson.typeAdapter
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonToken
import eu.kanade.tachiyomi.data.database.models.ChapterImpl
/**
* JSON Serializer used to write / read [ChapterImpl] to / from json
*/
object ChapterTypeAdapter {
private const val URL = "u"
private const val READ = "r"
private const val BOOKMARK = "b"
private const val LAST_READ = "l"
fun build(): TypeAdapter<ChapterImpl> {
return typeAdapter {
write {
if (it.read || it.bookmark || it.last_page_read != 0) {
beginObject()
name(URL)
value(it.url)
if (it.read) {
name(READ)
value(1)
}
if (it.bookmark) {
name(BOOKMARK)
value(1)
}
if (it.last_page_read != 0) {
name(LAST_READ)
value(it.last_page_read)
}
endObject()
}
}
read {
val chapter = ChapterImpl()
beginObject()
while (hasNext()) {
if (peek() == JsonToken.NAME) {
val name = nextName()
when (name) {
URL -> chapter.url = nextString()
READ -> chapter.read = nextInt() == 1
BOOKMARK -> chapter.bookmark = nextInt() == 1
LAST_READ -> chapter.last_page_read = nextInt()
}
}
}
endObject()
chapter
}
}
}
} | apache-2.0 | 9124d900c80b2f0f35acad503c234861 | 30.557377 | 75 | 0.41736 | 5.242507 | false | false | false | false |
SimpleMobileTools/Simple-Draw | app/src/main/kotlin/com/simplemobiletools/draw/pro/activities/MainActivity.kt | 1 | 24100 | package com.simplemobiletools.draw.pro.activities
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.WindowManager
import android.webkit.MimeTypeMap
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.Toast
import androidx.print.PrintHelper
import com.simplemobiletools.commons.dialogs.ColorPickerDialog
import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.LICENSE_GLIDE
import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE
import com.simplemobiletools.commons.helpers.SAVE_DISCARD_PROMPT_INTERVAL
import com.simplemobiletools.commons.helpers.isQPlus
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.models.Release
import com.simplemobiletools.draw.pro.BuildConfig
import com.simplemobiletools.draw.pro.R
import com.simplemobiletools.draw.pro.dialogs.SaveImageDialog
import com.simplemobiletools.draw.pro.extensions.config
import com.simplemobiletools.draw.pro.helpers.EyeDropper
import com.simplemobiletools.draw.pro.helpers.JPG
import com.simplemobiletools.draw.pro.helpers.PNG
import com.simplemobiletools.draw.pro.helpers.SVG
import com.simplemobiletools.draw.pro.interfaces.CanvasListener
import com.simplemobiletools.draw.pro.models.Svg
import kotlinx.android.synthetic.main.activity_main.*
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.OutputStream
class MainActivity : SimpleActivity(), CanvasListener {
private val PICK_IMAGE_INTENT = 1
private val SAVE_IMAGE_INTENT = 2
private val FOLDER_NAME = "images"
private val FILE_NAME = "simple-draw.png"
private val BITMAP_PATH = "bitmap_path"
private val URI_TO_LOAD = "uri_to_load"
private lateinit var eyeDropper: EyeDropper
private var defaultPath = ""
private var defaultFilename = ""
private var defaultExtension = PNG
private var intentUri: Uri? = null
private var uriToLoad: Uri? = null
private var color = 0
private var brushSize = 0f
private var savedPathsHash = 0L
private var lastSavePromptTS = 0L
private var isEraserOn = false
private var isEyeDropperOn = false
private var isBucketFillOn = false
private var isImageCaptureIntent = false
private var isEditIntent = false
private var lastBitmapPath = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appLaunched(BuildConfig.APPLICATION_ID)
setupOptionsMenu()
refreshMenuItems()
eyeDropper = EyeDropper(my_canvas) { selectedColor ->
setColor(selectedColor)
}
my_canvas.mListener = this
stroke_width_bar.setOnSeekBarChangeListener(onStrokeWidthBarChangeListener)
setBackgroundColor(config.canvasBackgroundColor)
setColor(config.brushColor)
defaultPath = config.lastSaveFolder
defaultExtension = config.lastSaveExtension
brushSize = config.brushSize
updateBrushSize()
stroke_width_bar.progress = brushSize.toInt()
color_picker.setOnClickListener { pickColor() }
undo.setOnClickListener { my_canvas.undo() }
eraser.setOnClickListener { eraserClicked() }
eraser.setOnLongClickListener {
toast(R.string.eraser)
true
}
redo.setOnClickListener { my_canvas.redo() }
eye_dropper.setOnClickListener { eyeDropperClicked() }
eye_dropper.setOnLongClickListener {
toast(R.string.eyedropper)
true
}
bucket_fill.setOnClickListener { bucketFillClicked() }
bucket_fill.setOnLongClickListener {
toast(R.string.bucket_fill)
true
}
checkIntents()
if (!isImageCaptureIntent) {
checkWhatsNewDialog()
}
}
override fun onResume() {
super.onResume()
setupToolbar(main_toolbar)
val isShowBrushSizeEnabled = config.showBrushSize
stroke_width_bar.beVisibleIf(isShowBrushSizeEnabled)
stroke_width_preview.beVisibleIf(isShowBrushSizeEnabled)
my_canvas.setAllowZooming(config.allowZoomingCanvas)
updateTextColors(main_holder)
if (isBlackAndWhiteTheme()) {
stroke_width_bar.setColors(0, config.canvasBackgroundColor.getContrastColor(), 0)
}
if (config.preventPhoneFromSleeping) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
requestedOrientation = if (config.forcePortraitMode) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
refreshMenuItems()
updateButtonStates()
}
override fun onPause() {
super.onPause()
config.brushColor = color
config.brushSize = brushSize
if (config.preventPhoneFromSleeping) {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
override fun onDestroy() {
super.onDestroy()
my_canvas.mListener = null
}
private fun refreshMenuItems() {
main_toolbar.menu.apply {
findItem(R.id.menu_confirm).isVisible = isImageCaptureIntent || isEditIntent
findItem(R.id.menu_save).isVisible = !isImageCaptureIntent && !isEditIntent
findItem(R.id.menu_share).isVisible = !isImageCaptureIntent && !isEditIntent
findItem(R.id.open_file).isVisible = !isEditIntent
}
}
private fun setupOptionsMenu() {
main_toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.menu_confirm -> confirmImage()
R.id.menu_save -> trySaveImage()
R.id.menu_share -> shareImage()
R.id.clear -> clearCanvas()
R.id.open_file -> tryOpenFile()
R.id.change_background -> changeBackgroundClicked()
R.id.menu_print -> printImage()
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
override fun onBackPressed() {
val hasUnsavedChanges = savedPathsHash != my_canvas.getDrawingHashCode()
if (hasUnsavedChanges && System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL) {
lastSavePromptTS = System.currentTimeMillis()
ConfirmationAdvancedDialog(this, "", R.string.save_before_closing, R.string.save, R.string.discard) {
if (it) {
trySaveImage()
} else {
super.onBackPressed()
}
}
} else {
super.onBackPressed()
}
}
private fun launchSettings() {
hideKeyboard()
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
private fun launchAbout() {
val licenses = LICENSE_GLIDE
val faqItems = ArrayList<FAQItem>()
if (!resources.getBoolean(R.bool.hide_google_relations)) {
faqItems.add(FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons))
faqItems.add(FAQItem(R.string.faq_6_title_commons, R.string.faq_6_text_commons))
faqItems.add(FAQItem(R.string.faq_7_title_commons, R.string.faq_7_text_commons))
faqItems.add(FAQItem(R.string.faq_10_title_commons, R.string.faq_10_text_commons))
}
startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, false)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (requestCode == PICK_IMAGE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
tryOpenUri(resultData.data!!, resultData)
} else if (requestCode == SAVE_IMAGE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
if (defaultExtension == SVG) {
Svg.saveToOutputStream(this, outputStream, my_canvas)
} else {
saveToOutputStream(outputStream, defaultExtension.getCompressionFormat(), false)
}
savedPathsHash = my_canvas.getDrawingHashCode()
}
}
private fun tryOpenFile() {
Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "image/*"
try {
startActivityForResult(this, PICK_IMAGE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
private fun checkIntents() {
if (intent?.action == Intent.ACTION_SEND && intent.type?.startsWith("image/") == true) {
val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
tryOpenUri(uri!!, intent)
}
if (intent?.action == Intent.ACTION_SEND_MULTIPLE && intent.type?.startsWith("image/") == true) {
val imageUris = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)!!
imageUris.any { tryOpenUri(it, intent) }
}
if (intent?.action == Intent.ACTION_VIEW && intent.data != null) {
tryOpenUri(intent.data!!, intent)
}
if (intent?.action == MediaStore.ACTION_IMAGE_CAPTURE) {
val output = intent.extras?.get(MediaStore.EXTRA_OUTPUT)
if (output != null && output is Uri) {
isImageCaptureIntent = true
intentUri = output
defaultPath = output.path!!
refreshMenuItems()
}
}
if (intent?.action == Intent.ACTION_EDIT) {
val data = intent.data
val output = intent.extras?.get(MediaStore.EXTRA_OUTPUT)
if (data != null && output != null && output is Uri) {
tryOpenUri(data, intent)
isEditIntent = true
intentUri = output
}
}
}
private fun getStoragePermission(callback: () -> Unit) {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
callback()
} else {
toast(R.string.no_storage_permissions)
}
}
}
private fun tryOpenUri(uri: Uri, intent: Intent) = when {
uri.scheme == "file" -> {
uriToLoad = uri
openPath(uri.path!!)
}
uri.scheme == "content" -> {
uriToLoad = uri
openUri(uri, intent)
}
else -> false
}
private fun openPath(path: String) = when {
path.endsWith(".svg") -> {
my_canvas.mBackgroundBitmap = null
Svg.loadSvg(this, File(path), my_canvas)
defaultExtension = SVG
true
}
File(path).isImageSlow() -> {
lastBitmapPath = path
my_canvas.drawBitmap(this, path)
defaultExtension = JPG
true
}
else -> {
toast(R.string.invalid_file_format)
false
}
}
private fun openUri(uri: Uri, intent: Intent): Boolean {
val mime = MimeTypeMap.getSingleton()
val type = mime.getExtensionFromMimeType(contentResolver.getType(uri)) ?: intent.type ?: contentResolver.getType(uri)
return when (type) {
"svg", "image/svg+xml" -> {
my_canvas.mBackgroundBitmap = null
Svg.loadSvg(this, uri, my_canvas)
defaultExtension = SVG
true
}
"jpg", "jpeg", "png", "gif", "image/jpg", "image/png", "image/gif" -> {
my_canvas.drawBitmap(this, uri)
defaultExtension = JPG
true
}
else -> {
toast(R.string.invalid_file_format)
false
}
}
}
private fun eraserClicked() {
if (isEyeDropperOn) {
eyeDropperClicked()
} else if (isBucketFillOn) {
bucketFillClicked()
}
isEraserOn = !isEraserOn
updateEraserState()
}
private fun updateEraserState() {
updateButtonStates()
my_canvas.toggleEraser(isEraserOn)
}
private fun changeBackgroundClicked() {
val oldColor = (my_canvas.background as ColorDrawable).color
ColorPickerDialog(this, oldColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
config.canvasBackgroundColor = color
setBackgroundColor(color)
if (uriToLoad != null) {
tryOpenUri(uriToLoad!!, intent)
}
}
}
}
private fun eyeDropperClicked() {
if (isEraserOn) {
eraserClicked()
} else if (isBucketFillOn) {
bucketFillClicked()
}
isEyeDropperOn = !isEyeDropperOn
if (isEyeDropperOn) {
eyeDropper.start()
} else {
eyeDropper.stop()
}
updateButtonStates()
}
private fun bucketFillClicked() {
if (isEraserOn) {
eraserClicked()
} else if (isEyeDropperOn) {
eyeDropperClicked()
}
isBucketFillOn = !isBucketFillOn
updateButtonStates()
my_canvas.toggleBucketFill(isBucketFillOn)
}
private fun updateButtonStates() {
if (config.showBrushSize) {
hideBrushSettings(isEyeDropperOn || isBucketFillOn)
}
updateButtonColor(eraser, isEraserOn)
updateButtonColor(eye_dropper, isEyeDropperOn)
updateButtonColor(bucket_fill, isBucketFillOn)
}
private fun updateButtonColor(view: ImageView, enabled: Boolean) {
if (enabled) {
view.applyColorFilter(getProperPrimaryColor())
} else {
view.applyColorFilter(config.canvasBackgroundColor.getContrastColor())
}
}
private fun hideBrushSettings(hide: Boolean) {
arrayOf(stroke_width_bar, stroke_width_preview).forEach {
it.beGoneIf(hide)
}
}
private fun confirmImage() {
when {
isEditIntent -> {
try {
val outputStream = contentResolver.openOutputStream(intentUri!!)
saveToOutputStream(outputStream, defaultPath.getCompressionFormat(), true)
} catch (e: Exception) {
showErrorToast(e)
}
}
intentUri?.scheme == "content" -> {
val outputStream = contentResolver.openOutputStream(intentUri!!)
saveToOutputStream(outputStream, defaultPath.getCompressionFormat(), true)
}
else -> handlePermission(PERMISSION_WRITE_STORAGE) {
val fileDirItem = FileDirItem(defaultPath, defaultPath.getFilenameFromPath())
getFileOutputStream(fileDirItem, true) {
saveToOutputStream(it, defaultPath.getCompressionFormat(), true)
}
}
}
}
private fun saveToOutputStream(outputStream: OutputStream?, format: Bitmap.CompressFormat, finishAfterSaving: Boolean) {
if (outputStream == null) {
toast(R.string.unknown_error_occurred)
return
}
val quality = if (format == Bitmap.CompressFormat.PNG) {
100
} else {
70
}
outputStream.use {
my_canvas.getBitmap().compress(format, quality, it)
}
if (finishAfterSaving) {
setResult(Activity.RESULT_OK)
finish()
}
}
private fun trySaveImage() {
if (isQPlus()) {
SaveImageDialog(this, defaultPath, defaultFilename, defaultExtension, true) { fullPath, filename, extension ->
val mimetype = if (extension == SVG) "svg+xml" else extension
defaultFilename = filename
defaultExtension = extension
config.lastSaveExtension = extension
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "image/$mimetype"
putExtra(Intent.EXTRA_TITLE, "$filename.$extension")
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, SAVE_IMAGE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
getStoragePermission {
saveImage()
}
}
}
private fun saveImage() {
SaveImageDialog(this, defaultPath, defaultFilename, defaultExtension, false) { fullPath, filename, extension ->
savedPathsHash = my_canvas.getDrawingHashCode()
saveFile(fullPath)
defaultPath = fullPath.getParentPath()
defaultFilename = filename
defaultExtension = extension
config.lastSaveFolder = defaultPath
config.lastSaveExtension = extension
}
}
private fun saveFile(path: String) {
when (path.getFilenameExtension()) {
SVG -> Svg.saveSvg(this, path, my_canvas)
else -> saveImageFile(path)
}
rescanPaths(arrayListOf(path)) {}
}
private fun saveImageFile(path: String) {
val fileDirItem = FileDirItem(path, path.getFilenameFromPath())
getFileOutputStream(fileDirItem, true) {
if (it != null) {
writeToOutputStream(path, it)
toast(R.string.file_saved)
} else {
toast(R.string.unknown_error_occurred)
}
}
}
private fun writeToOutputStream(path: String, out: OutputStream) {
out.use {
my_canvas.getBitmap().compress(path.getCompressionFormat(), 70, out)
}
}
private fun shareImage() {
getImagePath(my_canvas.getBitmap()) {
if (it != null) {
sharePathIntent(it, BuildConfig.APPLICATION_ID)
} else {
toast(R.string.unknown_error_occurred)
}
}
}
private fun getImagePath(bitmap: Bitmap, callback: (path: String?) -> Unit) {
val bytes = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bytes)
val folder = File(cacheDir, FOLDER_NAME)
if (!folder.exists()) {
if (!folder.mkdir()) {
callback(null)
return
}
}
val newPath = "$folder/$FILE_NAME"
val fileDirItem = FileDirItem(newPath, FILE_NAME)
getFileOutputStream(fileDirItem, true) {
if (it != null) {
try {
it.write(bytes.toByteArray())
callback(newPath)
} catch (e: Exception) {
} finally {
it.close()
}
} else {
callback("")
}
}
}
private fun clearCanvas() {
uriToLoad = null
my_canvas.clearCanvas()
defaultExtension = PNG
defaultPath = ""
lastBitmapPath = ""
}
private fun pickColor() {
ColorPickerDialog(this, color) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (isEyeDropperOn) {
eyeDropperClicked()
}
setColor(color)
}
}
}
fun setBackgroundColor(pickedColor: Int) {
if (isEyeDropperOn) {
eyeDropperClicked()
}
val contrastColor = pickedColor.getContrastColor()
undo.applyColorFilter(contrastColor)
eraser.applyColorFilter(contrastColor)
redo.applyColorFilter(contrastColor)
eye_dropper.applyColorFilter(contrastColor)
bucket_fill.applyColorFilter(contrastColor)
if (isBlackAndWhiteTheme()) {
stroke_width_bar.setColors(0, contrastColor, 0)
}
my_canvas.updateBackgroundColor(pickedColor)
defaultExtension = PNG
getBrushPreviewView().setStroke(getBrushStrokeSize(), contrastColor)
}
private fun setColor(pickedColor: Int) {
color = pickedColor
color_picker.setFillWithStroke(color, config.canvasBackgroundColor, true)
my_canvas.setColor(color)
isEraserOn = false
updateEraserState()
getBrushPreviewView().setColor(color)
}
private fun getBrushPreviewView() = stroke_width_preview.background as GradientDrawable
private fun getBrushStrokeSize() = resources.getDimension(R.dimen.preview_dot_stroke_size).toInt()
override fun toggleUndoVisibility(visible: Boolean) {
undo.beVisibleIf(visible)
}
override fun toggleRedoVisibility(visible: Boolean) {
redo.beVisibleIf(visible)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(BITMAP_PATH, lastBitmapPath)
if (uriToLoad != null) {
outState.putString(URI_TO_LOAD, uriToLoad.toString())
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
lastBitmapPath = savedInstanceState.getString(BITMAP_PATH)!!
if (lastBitmapPath.isNotEmpty()) {
openPath(lastBitmapPath)
} else if (savedInstanceState.containsKey(URI_TO_LOAD)) {
uriToLoad = Uri.parse(savedInstanceState.getString(URI_TO_LOAD))
tryOpenUri(uriToLoad!!, intent)
}
}
private var onStrokeWidthBarChangeListener: SeekBar.OnSeekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
brushSize = Math.max(progress.toFloat(), 5f)
updateBrushSize()
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
}
private fun updateBrushSize() {
my_canvas.setBrushSize(brushSize)
val scale = Math.max(0.03f, brushSize / 100f)
stroke_width_preview.scaleX = scale
stroke_width_preview.scaleY = scale
}
private fun printImage() {
val printHelper = PrintHelper(this)
printHelper.scaleMode = PrintHelper.SCALE_MODE_FIT
try {
printHelper.printBitmap(getString(R.string.app_name), my_canvas.getBitmap())
} catch (e: Exception) {
showErrorToast(e)
}
}
private fun checkWhatsNewDialog() {
arrayListOf<Release>().apply {
add(Release(18, R.string.release_18))
add(Release(20, R.string.release_20))
add(Release(38, R.string.release_38))
checkWhatsNew(this, BuildConfig.VERSION_CODE)
}
}
}
| gpl-3.0 | 3d5df76984227142c56c17325707c068 | 33.28165 | 150 | 0.604481 | 4.735704 | false | false | false | false |
pdvrieze/ProcessManager | PMEditor/src/main/java/nl/adaptivity/process/editor/android/MyDiagramAdapter.kt | 1 | 11568 | /*
* Copyright (c) 2016.
*
* 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.editor.android
import android.app.Activity
import android.app.DialogFragment
import android.content.Context
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.MotionEvent
import android.widget.Toast
import nl.adaptivity.android.graphics.BackgroundDrawable
import nl.adaptivity.android.graphics.LineView
import nl.adaptivity.diagram.android.AndroidDrawableLightView
import nl.adaptivity.diagram.android.DiagramView
import nl.adaptivity.diagram.android.LightView
import nl.adaptivity.diagram.android.RelativeLightView
import nl.adaptivity.diagram.android.RelativeLightView.BOTTOM
import nl.adaptivity.diagram.android.RelativeLightView.HGRAVITY
import nl.adaptivity.process.diagram.*
import nl.adaptivity.process.processModel.*
import java.util.*
/**
* The MyDiagramAdapter to use for the editor.
* @author Paul de Vrieze
*/
class MyDiagramAdapter(private val context: Context, diagram: DrawableProcessModel.Builder) :
BaseProcessAdapter(diagram) {
override var overlay: LightView? = null
private val cachedDecorations = arrayOfNulls<RelativeLightView>(3)
private val cachedStartDecorations = arrayOfNulls<RelativeLightView>(2)
private val cachedEndDecorations = arrayOfNulls<RelativeLightView>(1)
private var cachedDecorationItem: DrawableProcessNode.Builder<*>? = null
private var connectingItem = -1
override fun getRelativeDecorations(position: Int, scale: Double, selected: Boolean): List<RelativeLightView> {
if (!selected) {
return emptyList()
}
val drawableProcessNode = getItem(position)
val decorations: Array<RelativeLightView>
if (drawableProcessNode is StartNode.Builder) {
decorations = getStartDecorations(drawableProcessNode, scale)
} else if (drawableProcessNode is EndNode.Builder) {
decorations = getEndDecorations(drawableProcessNode, scale)
} else {
decorations = getDefaultDecorations(drawableProcessNode, scale)
}
val centerX = drawableProcessNode.x
val topY = drawableProcessNode.bounds.bottom + DECORATION_VSPACING / scale
layoutHorizontal(centerX, topY, scale, decorations)
return Arrays.asList(*decorations)
}
private fun getDefaultDecorations(item: DrawableProcessNode.Builder<*>, scale: Double): Array<RelativeLightView> {
if (item != cachedDecorationItem) {
cachedDecorationItem = item
cachedDecorations[0] = RelativeLightView(
AndroidDrawableLightView(loadDrawable(R.drawable.ic_cont_delete), scale), BOTTOM or HGRAVITY)
cachedDecorations[1] = RelativeLightView(
AndroidDrawableLightView(loadDrawable(R.drawable.ic_cont_edit), scale), BOTTOM or HGRAVITY)
cachedDecorations[2] = RelativeLightView(
AndroidDrawableLightView(loadDrawable(R.drawable.ic_cont_arrow), scale), BOTTOM or HGRAVITY)
}
@Suppress("UNCHECKED_CAST")
return cachedDecorations as Array<RelativeLightView>
}
private fun getStartDecorations(item: DrawableProcessNode.Builder<*>, scale: Double): Array<RelativeLightView> {
if (item != cachedDecorationItem) {
cachedDecorationItem = item
// Assign to both caches to allow click to remain working.
cachedStartDecorations[0] = RelativeLightView(
AndroidDrawableLightView(loadDrawable(R.drawable.ic_cont_delete), scale), BOTTOM or HGRAVITY)
cachedDecorations[0] = cachedStartDecorations[0]
cachedStartDecorations[1] = RelativeLightView(
AndroidDrawableLightView(loadDrawable(R.drawable.ic_cont_arrow), scale), BOTTOM or HGRAVITY)
cachedDecorations[2] = cachedStartDecorations[1]
}
@Suppress("UNCHECKED_CAST")
return cachedStartDecorations as Array<RelativeLightView>
}
private fun getEndDecorations(item: DrawableProcessNode.Builder<*>, scale: Double): Array<RelativeLightView> {
if (item != cachedDecorationItem) {
cachedDecorationItem = item
// Assign to both caches to allow click to remain working.
cachedEndDecorations[0] = RelativeLightView(
AndroidDrawableLightView(loadDrawable(R.drawable.ic_cont_delete), scale), BOTTOM or HGRAVITY)
cachedDecorations[0] = cachedEndDecorations[0]
}
@Suppress("UNCHECKED_CAST")
return cachedEndDecorations as Array<RelativeLightView>
}
private fun loadDrawable(resId: Int): Drawable {
// TODO get the button drawable out of the style.
return BackgroundDrawable(context, R.drawable.btn_context, resId)
}
fun notifyDatasetChanged() {
invalidate()
}
override fun onDecorationClick(view: DiagramView, position: Int, decoration: LightView) {
if (decoration === cachedDecorations[0]) {
removeNode(position)
view.invalidate()
} else if (decoration === cachedDecorations[1]) {
doEditNode(position)
} else if (decoration === cachedDecorations[2]) {
val o = overlay
if (o is LineView) {
view.invalidate(o)
overlay = null
} else {
decoration.isActive = true
connectingItem = position
}
}
}
private fun removeNode(position: Int) {
val item = getItem(position)
mViewCache.remove(item)
diagram.nodes.remove(item)
if (item == cachedDecorationItem) {
cachedDecorationItem = null
}
}
private fun doEditNode(position: Int) {
if (context is Activity) {
val node = diagram.childElements.get(position)
val fragment: DialogFragment
if (node is IDrawableJoinSplit) {
fragment = JoinSplitNodeEditDialogFragment.newInstance(position)
} else if (node is IDrawableActivity) {
fragment = ActivityEditDialogFragment.newInstance(position)
} else {
fragment = NodeEditDialogFragment.newInstance(position)
}
fragment.show(context.fragmentManager, "editNode")
}
}
override fun onDecorationMove(view: DiagramView, position: Int, decoration: RelativeLightView, x: Float, y: Float) {
if (decoration === cachedDecorations[2]) {
val start = cachedDecorationItem!!
val x1 = (start.bounds.right - RootDrawableProcessModel.STROKEWIDTH).toFloat()
val y1 = start.y.toFloat()
val overlay = (overlay as? LineView)?.also {
view.invalidate(it) // invalidate both old
it.setPos(x1, y1, x, y)
} ?: LineView(x1, y1, x, y).also { overlay = it }
view.invalidate(overlay) // and new bounds
}
}
override fun onDecorationUp(view: DiagramView,
position: Int,
decoration: RelativeLightView,
x: Float,
y: Float) {
if (decoration === cachedDecorations[2]) {
if (overlay is LineView) {
view.invalidate(overlay!!)
overlay = null
}
var next: DrawableProcessNode.Builder<*>? = null
for (item in diagram.childElements) {
if (item.getItemAt(x.toDouble(), y.toDouble()) != null) {
next = item
break
}
}
if (next != null) {
tryAddSuccessor(getItem(position), next)
}
}
}
override fun onNodeClickOverride(diagramView: DiagramView, touchedElement: Int, e: MotionEvent): Boolean {
if (connectingItem >= 0) {
val prev = getItem(connectingItem)
val next = getItem(touchedElement)
tryAddSuccessor(prev, next)
connectingItem = -1
cachedDecorations[2]!!.isActive = false
diagramView.invalidate()
return true
}
return false
}
fun tryAddSuccessor(prev: DrawableProcessNode.Builder<DrawableProcessNode>, next: DrawableProcessNode.Builder<DrawableProcessNode>) {
if (prev.successors.any { it.id == next.id }) {
prev.removeSuccessor(next)
} else {
if (prev.successors.size < prev.maxSuccessorCount && next.predecessors.size < next.maxPredecessorCount) {
try {
if (prev is Split.Builder) {
if (prev.min >= prev.max) {
prev.min = prev.min + 1
}
if (prev.max >= prev.successors.size) {
prev.max = prev.max + 1
}
}
if (next is Join.Builder) {
if (next.min >= next.max) {
next.min = next.min + 1
}
if (next.max >= prev.predecessors.size) {
next.max = next.max + 1
}
}
prev.addSuccessor(next.identifier!!)
} catch (e: IllegalProcessModelException) {
Log.w(MyDiagramAdapter::class.java.name, e.message, e)
Toast.makeText(context, "These can not be connected", Toast.LENGTH_LONG).show()
}
} else {
Toast.makeText(context, "These can not be connected", Toast.LENGTH_LONG).show()
// TODO Better errors
}
}
}
companion object {
private val DECORATION_VSPACING = 12.0
private val DECORATION_HSPACING = 12.0
private fun layoutHorizontal(centerX: Double,
top: Double,
scale: Double,
decorations: Array<RelativeLightView>) {
if (decorations.size == 0) {
return
}
val hspacing = DECORATION_HSPACING / scale
var totalWidth = -hspacing
val bounds = RectF()
for (decoration in decorations) {
decoration.getBounds(bounds)
totalWidth += bounds.width() + hspacing
}
var leftF = (centerX - totalWidth / 2).toFloat()
val topF = top.toFloat()
for (decoration in decorations) {
decoration.setPos(leftF, topF)
decoration.getBounds(bounds)
leftF += (bounds.width() + hspacing).toFloat()
}
}
}
}
| lgpl-3.0 | 79a234f5228a60ead48d3178954c1ebe | 39.447552 | 137 | 0.604772 | 4.860504 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/search/SearchResultsFragment.kt | 1 | 15302 | package org.fossasia.openevent.general.search
import android.content.res.ColorStateList
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.CompoundButton
import android.widget.ImageView
import androidx.appcompat.view.ContextThemeWrapper
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.chip.Chip
import kotlin.math.abs
import kotlinx.android.synthetic.main.content_no_internet.view.noInternetCard
import kotlinx.android.synthetic.main.content_no_internet.view.retry
import kotlinx.android.synthetic.main.fragment_search_results.view.appBar
import kotlinx.android.synthetic.main.fragment_search_results.view.chipGroup
import kotlinx.android.synthetic.main.fragment_search_results.view.chipGroupLayout
import kotlinx.android.synthetic.main.fragment_search_results.view.clearSearchText
import kotlinx.android.synthetic.main.fragment_search_results.view.eventsRecycler
import kotlinx.android.synthetic.main.fragment_search_results.view.filter
import kotlinx.android.synthetic.main.fragment_search_results.view.noSearchResults
import kotlinx.android.synthetic.main.fragment_search_results.view.scrollView
import kotlinx.android.synthetic.main.fragment_search_results.view.searchText
import kotlinx.android.synthetic.main.fragment_search_results.view.shimmerSearch
import kotlinx.android.synthetic.main.fragment_search_results.view.toolbar
import kotlinx.android.synthetic.main.fragment_search_results.view.toolbarLayout
import kotlinx.android.synthetic.main.fragment_search_results.view.toolbarTitle
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.EventClickListener
import org.fossasia.openevent.general.common.FavoriteFabClickListener
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventUtils
import org.fossasia.openevent.general.event.RedirectToLogin
import org.fossasia.openevent.general.event.types.EventType
import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard
import org.fossasia.openevent.general.utils.Utils.setToolbar
import org.fossasia.openevent.general.utils.Utils.showSoftKeyboard
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.fossasia.openevent.general.utils.extensions.setPostponeSharedElementTransition
import org.fossasia.openevent.general.utils.extensions.setStartPostponedEnterTransition
import org.jetbrains.anko.design.longSnackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
const val SEARCH_RESULTS_FRAGMENT = "searchResultsFragment"
class SearchResultsFragment : Fragment(), CompoundButton.OnCheckedChangeListener {
private lateinit var rootView: View
private val searchResultsViewModel by viewModel<SearchResultsViewModel>()
private val safeArgs: SearchResultsFragmentArgs by navArgs()
private val searchPagedListAdapter = SearchPagedListAdapter()
private lateinit var days: Array<String>
private lateinit var eventDate: String
private lateinit var eventType: String
private var eventTypesList: List<EventType>? = arrayListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
days = resources.getStringArray(R.array.days)
eventDate = searchResultsViewModel.savedTime ?: safeArgs.date
eventType = searchResultsViewModel.savedType ?: safeArgs.type
searchResultsViewModel.loadEventTypes()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_search_results, container, false)
setPostponeSharedElementTransition()
setupToolbar()
setChips()
searchResultsViewModel.eventTypes
.nonNull()
.observe(viewLifecycleOwner, Observer { list ->
eventTypesList = list
})
rootView.eventsRecycler.layoutManager = LinearLayoutManager(context)
rootView.eventsRecycler.adapter = searchPagedListAdapter
rootView.eventsRecycler.isNestedScrollingEnabled = false
rootView.viewTreeObserver.addOnDrawListener {
setStartPostponedEnterTransition()
}
rootView.searchText.setText(safeArgs.query)
rootView.clearSearchText.isVisible = !rootView.searchText.text.isNullOrBlank()
searchResultsViewModel.pagedEvents
.nonNull()
.observe(viewLifecycleOwner, Observer { list ->
searchPagedListAdapter.submitList(list)
Timber.d("Fetched events of size %s", searchPagedListAdapter.itemCount)
})
searchResultsViewModel.showShimmerResults
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (it) {
rootView.shimmerSearch.startShimmer()
showNoSearchResults(false)
showNoInternetError(false)
} else {
rootView.shimmerSearch.stopShimmer()
showNoSearchResults(searchPagedListAdapter.currentList?.isEmpty() ?: false)
}
rootView.shimmerSearch.isVisible = it
})
searchResultsViewModel.connection
.nonNull()
.observe(viewLifecycleOwner, Observer { isConnected ->
val currentPagedSearchEvents = searchResultsViewModel.pagedEvents.value
if (currentPagedSearchEvents != null) {
showNoInternetError(false)
searchPagedListAdapter.submitList(currentPagedSearchEvents)
} else {
if (isConnected)
performSearch()
else
showNoInternetError(true)
}
})
searchResultsViewModel.message
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.longSnackbar(it)
})
rootView.retry.setOnClickListener {
searchResultsViewModel.clearEvents()
performSearch()
}
return rootView
}
override fun onDestroyView() {
super.onDestroyView()
hideSoftKeyboard(context, rootView)
searchPagedListAdapter.apply {
onEventClick = null
onFavFabClick = null
}
}
private fun setChips(date: String = eventDate, type: String = eventType) {
if (rootView.chipGroup.childCount> 0) {
rootView.chipGroup.removeAllViews()
}
when {
date != getString(R.string.anytime) && type != getString(R.string.anything) -> {
addChips(date, true)
addChips(type, true)
}
date != getString(R.string.anytime) && type == getString(R.string.anything) -> {
addChips(date, true)
searchResultsViewModel.eventTypes
.nonNull()
.observe(viewLifecycleOwner, Observer { list ->
list.forEach {
addChips(it.name, false)
}
})
}
date == getString(R.string.anytime) && type != getString(R.string.anything) -> {
addChips(type, true)
days.forEach {
addChips(it, false)
}
}
else -> {
days.forEach {
addChips(it, false)
}
}
}
}
private fun setupToolbar() {
setToolbar(activity, show = false)
rootView.toolbar.setNavigationOnClickListener {
activity?.onBackPressed()
}
rootView.filter.setOnClickListener {
findNavController(rootView)
.navigate(SearchResultsFragmentDirections.actionSearchResultsToSearchFilter(
date = safeArgs.date,
freeEvents = safeArgs.freeEvents,
location = safeArgs.location,
type = safeArgs.type,
query = safeArgs.query,
sort = safeArgs.sort,
sessionsAndSpeakers = safeArgs.sessionsAndSpeakers,
callForSpeakers = safeArgs.callForSpeakers))
}
rootView.clearSearchText.setOnClickListener {
searchResultsViewModel.clearEvents()
rootView.searchText.setText("")
performSearch("")
}
}
private fun addChips(name: String, checked: Boolean) {
val newContext = ContextThemeWrapper(context, R.style.CustomChipChoice)
val chip = Chip(newContext)
chip.text = name
chip.isCheckable = true
chip.isChecked = checked
chip.isClickable = true
if (checked) {
chip.chipBackgroundColor =
ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.colorPrimary))
}
chip.setOnCheckedChangeListener(this)
rootView.chipGroup.addView(chip)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val eventClickListener: EventClickListener = object : EventClickListener {
override fun onClick(eventID: Long, imageView: ImageView) {
findNavController(rootView)
.navigate(SearchResultsFragmentDirections.actionSearchResultsToEventDetail(eventID),
FragmentNavigatorExtras(imageView to "eventDetailImage"))
}
}
val redirectToLogin = object : RedirectToLogin {
override fun goBackToLogin() {
findNavController(rootView).navigate(SearchResultsFragmentDirections
.actionSearchResultsToAuth(redirectedFrom = SEARCH_RESULTS_FRAGMENT))
}
}
val favFabClickListener: FavoriteFabClickListener = object : FavoriteFabClickListener {
override fun onClick(event: Event, itemPosition: Int) {
if (searchResultsViewModel.isLoggedIn()) {
event.favorite = !event.favorite
searchResultsViewModel.setFavorite(event, event.favorite)
searchPagedListAdapter.notifyItemChanged(itemPosition)
} else {
EventUtils.showLoginToLikeDialog(requireContext(),
layoutInflater, redirectToLogin, event.originalImageUrl, event.name)
}
}
}
searchPagedListAdapter.apply {
onEventClick = eventClickListener
onFavFabClick = favFabClickListener
}
rootView.searchText.setOnEditorActionListener { _, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.action == KeyEvent.ACTION_DOWN &&
event.keyCode == KeyEvent.KEYCODE_ENTER) {
searchResultsViewModel.clearEvents()
performSearch(rootView.searchText.text.toString())
true
} else {
false
}
}
rootView.searchText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do Nothing*/ }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { /*Do Nothing*/ }
override fun afterTextChanged(s: Editable?) {
rootView.clearSearchText.visibility = if (s.toString().isNullOrBlank()) View.GONE else View.VISIBLE
}
})
rootView.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, offset ->
if (abs(offset) == appBarLayout.totalScrollRange) {
rootView.toolbarTitle.text = if (rootView.searchText.text.isNullOrBlank())
getString(R.string.search_hint) else rootView.searchText.text.toString()
rootView.toolbarLayout.elevation = resources.getDimension(R.dimen.custom_toolbar_elevation)
} else {
rootView.toolbarTitle.text = ""
rootView.toolbarLayout.elevation = 0F
}
})
rootView.toolbar.toolbarTitle.setOnClickListener {
rootView.scrollView.scrollTo(0, 0)
rootView.appBar.setExpanded(true, true)
showSoftKeyboard(context, rootView)
rootView.searchText.isFocusable = true
}
}
private fun performSearch(query: String = safeArgs.query) {
val location = safeArgs.location
val type = eventType
val date = eventDate
val freeEvents = safeArgs.freeEvents
val sortBy = safeArgs.sort
val callForSpeakers = safeArgs.callForSpeakers
val sessionsAndSpeakers = safeArgs.sessionsAndSpeakers
searchResultsViewModel.searchEvent = query
searchResultsViewModel
.loadEvents(location, date, type, freeEvents, sortBy, sessionsAndSpeakers, callForSpeakers)
hideSoftKeyboard(requireContext(), rootView)
}
private fun showNoSearchResults(show: Boolean) {
rootView.noSearchResults.isVisible = show
}
private fun showNoInternetError(show: Boolean) {
rootView.noInternetCard.isVisible = show
rootView.chipGroupLayout.visibility = if (show) View.GONE else View.VISIBLE
}
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
days.forEach {
if (it == buttonView?.text) {
searchResultsViewModel.savedTime = if (isChecked) it else null
eventDate = if (isChecked) it else getString(R.string.anytime)
setChips(date = it)
refreshEvents()
return@forEach
}
}
eventTypesList?.forEach {
if (it.name == buttonView?.text) {
searchResultsViewModel.savedType = if (isChecked) it.name else null
eventType = if (isChecked) it.name else getString(R.string.anything)
refreshEvents()
return@forEach
}
}
}
private fun refreshEvents() {
setChips()
rootView.noSearchResults.isVisible = false
searchPagedListAdapter.submitList(null)
searchResultsViewModel.clearEvents()
if (searchResultsViewModel.isConnected()) {
performSearch()
} else showNoInternetError(true)
}
}
| apache-2.0 | d32361ead056fc2b4123d8719d5ef9a0 | 41.038462 | 116 | 0.656058 | 5.333566 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/common/gui/ItemStackPiece.kt | 1 | 1567 | package net.ndrei.teslapoweredthingies.common.gui
import net.minecraft.client.renderer.RenderHelper
import net.ndrei.teslacorelib.compatibility.FontRendererUtil
import net.ndrei.teslacorelib.gui.BasicContainerGuiPiece
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import net.ndrei.teslacorelib.render.GhostedItemRenderer
/**
* Created by CF on 2017-06-30.
*/
open class ItemStackPiece(left: Int, top: Int, width: Int, height: Int, private val provider: IWorkItemProvider, private val alpha: Float = 1.0f)
: BasicContainerGuiPiece(left, top, width, height) {
override fun drawMiddleLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) {
val stack = this.provider.workItem
if (!stack.isEmpty) {
val x = this.left + (this.width - 16) / 2
val y = this.top + (this.height - 16) / 2
if (this.alpha >= 1.0f) {
RenderHelper.enableGUIStandardItemLighting()
container.itemRenderer.renderItemAndEffectIntoGUI(stack, guiX + x, guiY + y)
container.itemRenderer.renderItemOverlayIntoGUI(FontRendererUtil.fontRenderer, stack, x, y, null)
RenderHelper.disableStandardItemLighting()
}
else {
RenderHelper.enableGUIStandardItemLighting()
GhostedItemRenderer.renderItemInGUI(container.itemRenderer, stack, guiX + x, guiY + y, this.alpha)
RenderHelper.disableStandardItemLighting()
}
}
}
}
| mit | aa5490829219464a9747626be86a3f22 | 45.088235 | 145 | 0.680919 | 4.201072 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/models/ResourcesBlueprint.kt | 1 | 3427 | /*
Copyright 2017 Google 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
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.google.androidstudiopoet.models
import com.google.androidstudiopoet.Blueprint
import com.google.androidstudiopoet.utils.joinPath
data class ResourcesBlueprint(private val moduleName: String,
private val enableCompose: Boolean,
val resDirPath: String,
private val stringCount: Int,
private val imageCount: Int,
private val layoutCount: Int,
private val resourcesToReferWithin: ResourcesToRefer,
private val actionClasses: List<ClassBlueprint>) : Blueprint {
val stringNames = (0 until stringCount).map { "${moduleName}string$it" }
val imageNames = (0 until imageCount).map { "${moduleName.toLowerCase()}image$it" }
val layoutNames = (0 until layoutCount).map {
if (enableCompose) {
"com.${moduleName}.Activity${it}Screen"
} else {
"${moduleName.toLowerCase()}activity_main$it"
}
}
val layoutsDir = resDirPath.joinPath("layout")
private val textsWithActions: List<Pair<String, ClassBlueprint?>> = (stringNames + resourcesToReferWithin.strings)
.mapIndexed { index, stringName ->
Pair(stringName, actionClasses.getOrNull(index))
}
private val imagesWithActions: List<Pair<String, ClassBlueprint?>> = (imageNames + resourcesToReferWithin.images)
.mapIndexed { index, stringName ->
Pair(stringName, actionClasses.getOrNull(index + textsWithActions.size))
}
private val stringsWithActionsPerLayout by lazy {
textsWithActions.splitPerLayout(layoutCount)
}
private val imagesWithActionsPerLayout by lazy {
imagesWithActions.splitPerLayout(layoutCount)
}
val layoutBlueprints = layoutNames.mapIndexed { index, layoutName ->
LayoutBlueprint(layoutName,
layoutsDir,
enableCompose,
stringsWithActionsPerLayout.getOrElse(index) { emptyList() },
imagesWithActionsPerLayout.getOrElse(index) { emptyList() },
if (index == 0) resourcesToReferWithin.layouts else emptyList())
}
val dataBindingListenersPerLayout = layoutBlueprints.map { it.classesToBind }
val resourcesToReferFromOutside by lazy {
ResourcesToRefer(listOf(stringNames.last()), listOf(imageNames.last()), listOf(layoutNames.last()))
}
}
fun <T> List<T>.splitPerLayout(limit: Int) =
this.foldIndexed(mutableListOf<List<T>>()) { index, acc, stringName ->
if (index < limit) {
acc.add(listOf(stringName))
} else {
acc.add(limit - 1, acc[limit - 1] + stringName)
}
return@foldIndexed acc
} | apache-2.0 | 5991b419373a746fee482465bd35239c | 39.329412 | 118 | 0.645171 | 4.746537 | false | false | false | false |
epool/pikmail-api | src/main/kotlin/com/nearsoft/pikmail/api/Main.kt | 1 | 2822 | package com.nearsoft.pikmail.api
import com.nearsoft.ipapiklient.IpApiKlient
import com.nearsoft.ipapiklient.models.IpCheckResult
import com.nearsoft.pikmail.Pikmail
import com.nearsoft.pikmail.ProfileNotFountException
import io.ktor.application.call
import io.ktor.content.default
import io.ktor.content.files
import io.ktor.content.static
import io.ktor.content.staticRootFolder
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.response.respondRedirect
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import kotlinx.coroutines.experimental.rx2.await
import java.io.File
class Main {
companion object {
private val analyticsManager = AnalyticsManager()
@JvmStatic
fun main(args: Array<String>) {
val port = System.getenv("PORT")?.toInt() ?: 8080
embeddedServer(Netty, port) {
routing {
static {
staticRootFolder = File("./static")
files("./")
default("index.html")
}
get("/{email}") {
// Since the email is part of the endpoint path, it won't be null ever
val email = call.parameters["email"]!!
val size = call.request.queryParameters["size"]
val ip = call.request.headers["X-Forwarded-For"]
?: "RemoteHost[${call.request.local.remoteHost}]"
val ipCheckResult: IpCheckResult = IpApiKlient.getIpInfo(ip).await()
try {
val profilePictureUrl = Pikmail.getProfilePictureUrl(email, size?.toInt()).await()
call.respondRedirect(profilePictureUrl)
analyticsManager.trackSuccess(email, ipCheckResult, size?.toInt())
} catch (throwable: Throwable) {
if (throwable is ProfileNotFountException) {
with(HttpStatusCode.NotFound) {
call.respondText(
"""{"email": "$email","status":$value,"error":"$description"}""",
ContentType.Application.Json,
this
)
}
}
analyticsManager.trackError(email, ipCheckResult, throwable)
}
}
}
}.start(wait = true)
}
}
} | apache-2.0 | 70546845a5014f95da4d24c77a479acf | 38.760563 | 110 | 0.525868 | 5.324528 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/misc/functions.kt | 1 | 5107 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.misc
import com.google.common.collect.ImmutableTable
import com.google.common.collect.Table
import org.droidmate.explorationModel.interaction.Interaction
import org.droidmate.legacy.Resource
import org.droidmate.misc.SysCmdExecutor
import java.io.BufferedInputStream
import java.io.FileOutputStream
import java.math.BigDecimal
import java.math.RoundingMode
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.time.Duration
import java.util.zip.ZipFile
fun plot(dataFilePath: String, outputFilePath: String, resourceDir: Path) {
require(Files.isRegularFile(Paths.get(dataFilePath)), { "Paths.get(dataFilePath='$dataFilePath').isRegularFile" })
require(Files.isDirectory(Paths.get(outputFilePath).parent), { "Paths.get(outputFilePath='$outputFilePath').parent.isDirectory" })
require(Files.isDirectory(resourceDir), { "resourceDir(=$resourceDir).isDirectory" })
val plotTemplatePathString = Resource("plot_template.plt").extractTo(resourceDir).toString()
SysCmdExecutor().execute("Generating plot with GNUPlot",
"gnuplot",
"-c",
plotTemplatePathString,
"0",
dataFilePath,
outputFilePath)
}
fun <V> buildTable(headers: Iterable<String>, rowCount: Int, computeRow: (Int) -> Iterable<V>): Table<Int, String, V> {
require(rowCount >= 0)
val builder = ImmutableTable.Builder<Int, String, V>()
.orderColumnsBy(compareBy<String> { headers.indexOf(it) })
.orderRowsBy(naturalOrder<Int>())
val rows: List<Pair<Int, Iterable<V>>> = 0.rangeTo(rowCount - 1).step(1)
.map { rowIndex ->
val row = computeRow(rowIndex)
check(headers.count() == row.count())
Pair(rowIndex, row)
}
rows.forEach { row: Pair<Int, Iterable<V>> ->
row.second.forEachIndexed { columnIndex: Int, columnValue: V ->
builder.put(row.first, headers.elementAt(columnIndex), columnValue)
}
}
return builder.build()
}
/**
* Unzips a zipped archive into [targetDirectory].
*/
fun Path.unzip(targetDirectory: Path): Path {
val file = ZipFile(this.toAbsolutePath().toString())
val fileSystem = this.fileSystem
val entries = file.entries()
Files.createDirectory(fileSystem.getPath(targetDirectory.toString()))
while (entries.hasMoreElements()) {
val entry = entries.nextElement()
if (entry.isDirectory) {
Files.createDirectories(targetDirectory.resolve(entry.name))
} else {
val bis = BufferedInputStream(file.getInputStream(entry))
val fName = targetDirectory.resolve(entry.name).toAbsolutePath().toString()
Files.createFile(fileSystem.getPath(fName))
val fileOutput = FileOutputStream(fName)
while (bis.available() > 0) {
fileOutput.write(bis.read())
}
fileOutput.close()
}
}
file.close()
return targetDirectory
}
val Duration.minutesAndSeconds: String
get() {
val m = this.toMinutes()
val s = this.seconds - m * 60
return "$m".padStart(4, ' ') + "m " + "$s".padStart(2, ' ') + "s"
}
/**
* Given a string builder over a string containing variables in form of "$var_name" (without ""), it will replace
* all such variables with their value.
*/
fun StringBuilder.replaceVariable(varName: String, value: String): StringBuilder {
val fullVarName = "$$varName"
while (this.indexOf(fullVarName) != -1) {
val startIndex = this.indexOf(fullVarName)
val endIndex = startIndex + fullVarName.length
this.replace(startIndex, endIndex, value)
}
return this
}
/**
* Zeroes digits before (i.e. left of) comma. E.g. if [digitsToZero] is 2, then 6789 will become 6700.
*/
// Reference: http://stackoverflow.com/questions/2808535/round-a-double-to-2-decimal-places
fun Int.zeroLeastSignificantDigits(digitsToZero: Int): Long {
return BigDecimal(this.toString()).setScale(-digitsToZero, RoundingMode.DOWN).toBigInteger().toLong()
}
fun Interaction<*>.actionString(sep:String = ";") = listOf(prevState.toString(), actionType,
targetWidget?.id.toString(), resState.toString(), startTimestamp.toString(), endTimestamp.toString(),
successful.toString(), exception, data).joinToString(separator = sep) | gpl-3.0 | a300bdb84f5fd19ba678fd021427316e | 33.748299 | 131 | 0.738398 | 3.714182 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/core/src/test/kotlin/org/droidmate/exceptions/ExceptionSpec.kt | 1 | 2281 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exceptions
class ExceptionSpec constructor(override val methodName: String,
override val packageName: String = "",
override val callIndex: Int = 1,
override val throwsEx: Boolean = true,
override val exceptionalReturnBool: Boolean? = null,
private val throwsAssertionError: Boolean = false) : IExceptionSpec {
companion object {
private const val serialVersionUID: Long = 1
}
init {
assert(this.throwsEx == (this.exceptionalReturnBool == null))
assert(!this.throwsAssertionError || this.throwsEx)
}
override fun matches(methodName: String, packageName: String, callIndex: Int): Boolean {
if (this.methodName == methodName && (this.packageName in arrayListOf("", packageName)) && this.callIndex == callIndex)
return true
return false
}
override fun throwEx() {
assert(this.exceptionalReturnBool == null)
if (this.throwsAssertionError)
throw TestAssertionError(this)
else
throw TestDeviceException(this)
}
override fun toString(): String {
return "mthd: $methodName pkg: $packageName idx: $callIndex throw: $throwsEx"
}
}
| gpl-3.0 | d10add400b873eeaf7fe2bf32aab8df1 | 37.661017 | 121 | 0.693994 | 4.320076 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/misc/extensions_time_series.kt | 1 | 5024 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.misc
import org.droidmate.legacy.associateMany
import org.droidmate.legacy.flatten
import java.lang.Math.max
import java.time.Duration
import java.time.LocalDateTime
private fun computeDuration(startTime: LocalDateTime, time: LocalDateTime): Long {
return Duration.between(startTime, time).toMillis()
}
fun <T, TItem> Iterable<T>.itemsAtTime(
startTime: LocalDateTime,
extractTime: (T) -> LocalDateTime,
extractItems: (T) -> Iterable<TItem>
): Map<Long, Iterable<TItem>> {
// Implicit assumption: each element of receiver has a different key (== duration).
return this.associate {
Pair(
computeDuration(startTime, extractTime(it)),
extractItems(it)
)
}
}
fun <T, TItem> Iterable<T>.itemsAtTimes(
startTime: LocalDateTime,
extractTime: (TItem) -> LocalDateTime,
extractItems: (T) -> Iterable<TItem>
): Map<Long, Iterable<TItem>> {
val itemsAtTimesGroupedByOriginElement: Iterable<Map<Long, Iterable<TItem>>> = this.map {
// Items from the currently processed element.
val items: Iterable<TItem> = extractItems(it)
// Items from the currently processed element, keyed by the computed duration. Multiple items might have
// the same time.
val itemsAtTime: Map<Long, Iterable<TItem>> =
items
.associateMany {
Pair(
computeDuration(startTime, extractTime(it)),
it)
}
itemsAtTime
}
// We do not care from which element given (time->item) mapping came, so we flatten it.
return itemsAtTimesGroupedByOriginElement.flatten()
}
fun Map<Long, Iterable<String>>.accumulate(): Map<Long, Iterable<String>> {
val uniqueStringsAcc: MutableSet<String> = hashSetOf()
return this.mapValues {
uniqueStringsAcc.addAll(it.value)
uniqueStringsAcc.toList()
}
}
fun <T> Map<Long, T>.partition(partitionSize: Long): Map<Long, List<T>> {
tailrec fun <T> _partition(
acc: Collection<Pair<Long, List<T>>>,
remainder: Collection<Pair<Long, T>>,
partitionSize: Long,
currentPartitionValue: Long): Collection<Pair<Long, List<T>>> {
if (remainder.isEmpty()) return acc else {
val currentPartition = remainder.partition { it.first <= currentPartitionValue }
val current: List<Pair<Long, T>> = currentPartition.first
val currentValues: List<T> = current.fold(mutableListOf(), { out, pair -> out.add(pair.second); out })
return _partition(acc.plus(Pair(currentPartitionValue, currentValues)), currentPartition.second, partitionSize, currentPartitionValue + partitionSize)
}
}
return _partition(mutableListOf(Pair(0L, emptyList<T>())), this.toList(), partitionSize, partitionSize).toMap()
}
fun <T> Map<Long, T>.accumulateMaxes(
extractMax: (T) -> Int
): Map<Long, Int> {
var currMaxVal = 0
return this.mapValues {
currMaxVal = max(extractMax(it.value), currMaxVal)
currMaxVal
}
}
fun Map<Long, Int>.padPartitions(
partitionSize: Long,
lastPartition: Long
): Map<Long, Int> {
require(lastPartition.rem(partitionSize) == 0L, { "lastPartition: $lastPartition partitionSize: $partitionSize" })
require(this.all { it.key.rem(partitionSize) == 0L })
return if (this.isEmpty())
(0..lastPartition step partitionSize).associate { Pair(it, -1) }
else {
val maxKey = this.keys.max() ?: 0
val paddedPartitions: Map<Long, Int> = ((maxKey + partitionSize)..lastPartition step partitionSize).associate { Pair(it, -1) }
return this.plus(paddedPartitions)
}
}
fun Map<Long, Iterable<String>>.countsPartitionedByTime(
partitionSize: Long,
lastPartition: Int
): Map<Long, Int> {
return this
.mapKeys {
// KNOWN BUG got here time with relation to exploration start of -25, but it should be always > 0.
// The currently applied workaround is to update 100 milliseconds.
it.key + 100L
}
.accumulate()
.mapValues { it.value.count() }
.partition(partitionSize)
.accumulateMaxes(extractMax = { it.max() ?: 0 })
.padPartitions(partitionSize, lastPartition.zeroLeastSignificantDigits(3))
} | gpl-3.0 | 2a81aeae6d1a4899752376c7470e9ddd | 31.419355 | 153 | 0.723129 | 3.570718 | false | false | false | false |
renard314/textfairy | app/src/main/java/com/renard/ocr/main_menu/language/OcrLanguage.kt | 1 | 1834 | package com.renard.ocr.main_menu.language
import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import com.renard.ocr.util.AppStorage.setTrainedDataDestinationForDownload
import java.util.*
import java.util.Locale.getAvailableLocales
/**
* @author renard
*/
data class OcrLanguage(
val value: String,
val installStatus: InstallStatus = InstallStatus(false),
val isDownloading: Boolean = false
) {
data class InstallStatus(val isInstalled: Boolean, val installedSize: Long = 0)
val isInstalled: Boolean
get() = installStatus.isInstalled
val size: Long
get() = installStatus.installedSize
val displayText: String = LOCALIZED_DISPLAY_LANGUAGES[value]
?: OCR_LANGUAGES[value]
?: value
fun installLanguage(context: Context) {
val dm = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = if (value == "sat") {
Uri.parse("https://github.com/indic-ocr/tessdata/raw/master/sat/sat.traineddata")
} else {
Uri.parse("https://github.com/tesseract-ocr/tessdata_fast/raw/4.0.0/$value.traineddata")
}
val request = DownloadManager.Request(uri)
setTrainedDataDestinationForDownload(context, request, uri.lastPathSegment!!)
request.setTitle(displayText)
dm.enqueue(request)
}
override fun toString() = displayText
}
private val LOCALIZED_DISPLAY_LANGUAGES: Map<String, String> by lazy {
getAvailableLocales()
.associateBy({ it.getIso3Language() }, Locale::getDisplayLanguage)
.filterKeys { it.isNotEmpty() }
.filterValues { it.isNotEmpty() }
}
private fun Locale.getIso3Language() = try {
isO3Language
} catch (e: MissingResourceException) {
""
}
| apache-2.0 | b3aafa8545ea3ab0441ab3fc98480e1a | 30.084746 | 100 | 0.683206 | 4.149321 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleHeat.kt | 2 | 7006 | package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.core.INode
import com.cout970.magneticraft.api.core.ITileRef
import com.cout970.magneticraft.api.core.NodeID
import com.cout970.magneticraft.api.heat.IHeatConnection
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.api.heat.IHeatNodeHandler
import com.cout970.magneticraft.api.internal.heat.HeatNode
import com.cout970.magneticraft.misc.getTagCompound
import com.cout970.magneticraft.misc.list
import com.cout970.magneticraft.misc.network.FloatSyncVariable
import com.cout970.magneticraft.misc.network.SyncVariable
import com.cout970.magneticraft.misc.newNbt
import com.cout970.magneticraft.misc.readList
import com.cout970.magneticraft.misc.tileentity.shouldTick
import com.cout970.magneticraft.misc.tileentity.tryConnect
import com.cout970.magneticraft.misc.vector.toBlockPos
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.registry.HEAT_NODE_HANDLER
import com.cout970.magneticraft.registry.getOrNull
import com.cout970.magneticraft.systems.gui.DATA_ID_HEAT_LIST
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.BlockPos
import net.minecraftforge.common.capabilities.Capability
/**
* Created by cout970 on 2017/06/29.
*/
class ModuleHeat(
vararg val heatNodes: IHeatNode,
val canConnect: (ModuleHeat, IHeatNode, IHeatNodeHandler, IHeatNode, EnumFacing?) -> Boolean = ModuleHeat::defaultCanConnectImpl,
val canConnectAtSide: (EnumFacing?) -> Boolean = { true },
val onUpdateConnections: (ModuleHeat) -> Unit = {},
val capabilityFilter: (EnumFacing?) -> Boolean = { true },
val connectableDirections: () -> List<Pair<BlockPos, EnumFacing>> = {
NEGATIVE_DIRECTIONS.filter { canConnectAtSide(it) }.map { it.toBlockPos() to it.opposite }
},
override val name: String = "module_heat"
) : IModule, IHeatNodeHandler {
companion object {
@JvmStatic
val NEGATIVE_DIRECTIONS = EnumFacing.values().filter { it.axisDirection == EnumFacing.AxisDirection.NEGATIVE }
}
override lateinit var container: IModuleContainer
val inputNormalConnections = mutableListOf<IHeatConnection>()
val outputNormalConnections = mutableListOf<IHeatConnection>()
override fun update() {
if (world.isClient) return
updateConnections()
iterate()
}
fun updateConnections() {
if (container.shouldTick(40)) {
updateNormalConnections()
onUpdateConnections(this)
container.sendUpdateToNearPlayers()
}
}
fun updateNormalConnections() {
clearNormalConnections()
heatNodes.forEach { thisNode ->
val conDir = connectableDirections()
val spots = conDir.mapNotNull { (vec, side) ->
val tile = world.getTileEntity(pos.add(vec)) ?: return@mapNotNull null
tile to side
}
val handlers = spots.mapNotNull { (tile, side) ->
val handler = tile.getOrNull(HEAT_NODE_HANDLER, side)
if (handler === null || handler === this) return@mapNotNull null
handler to side
}
for ((handler, side) in handlers) {
val heatNodes = handler.nodes.filterIsInstance<IHeatNode>()
heatNodes.forEach { otherNode ->
tryConnect(this, thisNode, handler, otherNode, side.opposite)
}
}
}
}
fun iterate() {
outputNormalConnections.forEach(IHeatConnection::iterate)
}
override fun canConnect(thisNode: IHeatNode, other: IHeatNodeHandler, otherNode: IHeatNode,
side: EnumFacing): Boolean = canConnect(this, thisNode, other, otherNode, side)
fun defaultCanConnectImpl(thisNode: IHeatNode, other: IHeatNodeHandler, otherNode: IHeatNode,
side: EnumFacing?): Boolean {
if (other == this || otherNode == thisNode || side == null) return false
return canConnectAtSide(side)
}
override fun addConnection(connection: IHeatConnection, side: EnumFacing, output: Boolean) {
val list = if (output) outputNormalConnections else inputNormalConnections
list.add(connection)
}
override fun removeConnection(connection: IHeatConnection?) {
inputNormalConnections.remove(connection)
outputNormalConnections.remove(connection)
}
override fun onBreak() {
clearNormalConnections()
inputNormalConnections.removeAll { con ->
val handler = getHandler(con.firstNode)
handler?.removeConnection(con)
true
}
}
fun clearNormalConnections() {
outputNormalConnections.removeAll { con ->
val handler = getHandler(con.secondNode)
handler?.removeConnection(con)
true
}
}
fun getHandler(node: IHeatNode): IHeatNodeHandler? {
val tile = node.world.getTileEntity(node.pos) ?: return null
return tile.getOrNull(HEAT_NODE_HANDLER, null) ?: return null
}
override fun getNodes(): MutableList<INode> = heatNodes.toMutableList()
override fun getNode(id: NodeID): INode? = heatNodes.find { it.id == id }
override fun getRef(): ITileRef = container.ref
override fun getInputConnections(): MutableList<IHeatConnection> = inputNormalConnections
override fun getOutputConnections(): MutableList<IHeatConnection> = outputNormalConnections
override fun hasCapability(cap: Capability<*>, facing: EnumFacing?): Boolean {
return cap == HEAT_NODE_HANDLER && capabilityFilter.invoke(facing)
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any?> getCapability(cap: Capability<T>, facing: EnumFacing?): T? {
if (cap != HEAT_NODE_HANDLER) return null
if (!capabilityFilter.invoke(facing)) return null
return this as T
}
override fun deserializeNBT(nbt: NBTTagCompound) {
nbt.readList("HeatNodes") { nodeList ->
nodes.forEachIndexed { index, node ->
node.deserializeNBT(nodeList.getTagCompound(index))
}
}
}
override fun serializeNBT(): NBTTagCompound = newNbt {
list("HeatNodes") {
nodes.forEach { appendTag(it.serializeNBT()) }
}
}
override fun getGuiSyncVariables(): List<SyncVariable> {
return heatNodes
.filterIsInstance<HeatNode>()
.mapIndexed { index, node ->
FloatSyncVariable(
id = DATA_ID_HEAT_LIST[index],
getter = { node.internalEnergy.toFloat() },
setter = { node.internalEnergy = it.toDouble() }
)
}
}
} | gpl-2.0 | 7e337846140368e7f0b93051e6c2cb08 | 36.672043 | 133 | 0.671995 | 4.546398 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/client/DefaultOntrackGitHubClient.kt | 1 | 32206 | package net.nemerosa.ontrack.extension.github.client
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.JsonNode
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import net.nemerosa.ontrack.common.BaseException
import net.nemerosa.ontrack.common.runIf
import net.nemerosa.ontrack.extension.git.model.GitPullRequest
import net.nemerosa.ontrack.extension.github.app.GitHubAppTokenService
import net.nemerosa.ontrack.extension.github.model.*
import net.nemerosa.ontrack.extension.github.support.parseLocalDateTime
import net.nemerosa.ontrack.git.support.GitConnectionRetry
import net.nemerosa.ontrack.json.*
import net.nemerosa.ontrack.model.structure.NameDescription
import net.nemerosa.ontrack.model.support.ApplicationLogEntry
import net.nemerosa.ontrack.model.support.ApplicationLogService
import org.apache.commons.codec.binary.Base64
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.RestClientResponseException
import org.springframework.web.client.RestTemplate
import org.springframework.web.client.getForObject
import java.time.Duration
import java.time.LocalDateTime
/**
* GitHub client which uses the GitHub Rest API at https://docs.github.com/en/rest
*/
class DefaultOntrackGitHubClient(
private val configuration: GitHubEngineConfiguration,
private val gitHubAppTokenService: GitHubAppTokenService,
private val applicationLogService: ApplicationLogService,
private val timeout: Duration = Duration.ofSeconds(60),
private val retries: UInt = 3u,
private val interval: Duration = Duration.ofSeconds(30),
private val notFoundRetries: UInt = 6u,
private val notFoundInterval: Duration = Duration.ofSeconds(5),
) : OntrackGitHubClient {
private val logger: Logger = LoggerFactory.getLogger(OntrackGitHubClient::class.java)
override fun getRateLimit(): GitHubRateLimit? =
try {
createGitHubRestTemplate()("Gets rate limit") {
getForObject<JsonNode>("/rate_limit").getJsonField("resources")?.run {
parse()
}
}
} catch (_: HttpClientErrorException.NotFound) {
// Rate limit not supported
null
} catch (any: Exception) {
applicationLogService.log(
ApplicationLogEntry.error(
any,
NameDescription.nd("github-ratelimit", "Cannot get the GitHub rate limit"),
"Cannot get the rate limit for GitHub at ${configuration.url}"
).withDetail("configuration", configuration.name)
)
// No rate limit
null
}
override val organizations: List<GitHubUser>
get() = if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
listOfNotNull(
gitHubAppTokenService.getAppInstallationAccount(configuration)?.run {
GitHubUser(
login = login,
url = url,
)
}
)
} else {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the organization names
client("Gets list of organizations") {
getForObject<JsonNode>("/user/orgs?per_page=100").map { node ->
node.parse()
}
}
}
override fun findRepositoriesByOrganization(organization: String): List<GitHubRepository> =
paginateGraphQL(
message = "Getting repositories for organization $organization",
query = """
query OrgRepositories(${'$'}login: String!, ${'$'}after: String) {
organization(login: ${'$'}login) {
repositories(first: 100, after: ${'$'}after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
name
description
updatedAt
createdAt
}
}
}
}
""",
variables = mapOf("login" to organization),
collectionAt = listOf("organization", "repositories"),
nodes = true
) { node ->
GitHubRepository(
name = node.path("name").asText(),
description = node.path("description").asText(),
lastUpdate = node.path("updatedAt")?.asText()
?.takeIf { it.isNotBlank() }
?.let { parseLocalDateTime(it) },
createdAt = node.path("createdAt")?.asText()
?.takeIf { it.isNotBlank() }
?.let { parseLocalDateTime(it) }
)
} ?: throw GitHubNoGraphQLResponseException("Getting repositories for organization $organization")
private fun getRepositoryParts(repository: String): Pair<String, String> {
val login = repository.substringBefore("/")
val name = repository.substringAfter("/")
return login to name
}
override fun getIssue(repository: String, id: Int): GitHubIssue? {
// Logging
logger.debug("[github] Getting issue {}/{}", repository, id)
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Gets the issue
return try {
client("Get issue $repository#$id") {
getForObject<JsonNode>("/repos/$owner/$name/issues/$id").let {
GitHubIssue(
id = id,
url = it.getRequiredTextField("html_url"),
summary = it.getRequiredTextField("title"),
body = it.getTextField("body") ?: "",
bodyHtml = it.getTextField("body") ?: "",
assignee = it.getUserField("assignee"),
labels = it.getLabels(),
state = it.getState(),
milestone = it.getMilestone(),
createdAt = it.getCreatedAt(),
updateTime = it.getUpdatedAt(),
closedAt = it.getClosedAt(),
)
}
}
} catch (ex: GitHubErrorsException) {
if (ex.status == 404) {
null
} else {
throw ex
}
}
}
override fun getOrganizationTeams(login: String): List<GitHubTeam>? =
paginateGraphQL(
message = "Getting teams for $login organization",
query = """
query OrgTeams(${'$'}login: String!, ${'$'}after: String) {
organization(login: ${'$'}login) {
teams(first: 100, after: ${'$'}after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
slug
name
description
url
}
}
}
}
""",
variables = mapOf(
"login" to login
),
collectionAt = listOf("organization", "teams"),
nodes = true
) { teamNode ->
GitHubTeam(
slug = teamNode.path("slug").asText(),
name = teamNode.path("name").asText(),
description = teamNode.path("description").asText(),
html_url = teamNode.path("url").asText()
)
}
override fun getTeamRepositories(login: String, teamSlug: String): List<GitHubTeamRepository>? =
paginateGraphQL(
message = "Getting repositories for team $teamSlug in organization $login",
query = """
query TeamRepositories(${'$'}login: String!, ${'$'}team: String!, ${'$'}after: String) {
organization(login: ${'$'}login) {
team(slug: ${'$'}team) {
repositories(first: 100, after: ${'$'}after) {
pageInfo {
hasNextPage
endCursor
}
edges {
permission
node {
name
}
}
}
}
}
}
""",
variables = mapOf(
"login" to login,
"team" to teamSlug
),
collectionAt = listOf("organization", "team", "repositories"),
nodes = false
) { edge ->
GitHubTeamRepository(
repository = edge.path("node").path("name").asText(),
permission = edge.path("permission").asText().let { GitHubRepositoryPermission.valueOf(it) }
)
}
private fun <T> paginateGraphQL(
message: String,
query: String,
variables: Map<String, *> = emptyMap<String, Any>(),
collectionAt: List<String>,
nodes: Boolean = false,
code: (node: JsonNode) -> T,
): List<T>? {
val results = mutableListOf<T>()
var hasNext = true
var after: String? = null
while (hasNext) {
val actualVariables = variables + ("after" to after)
try {
graphQL(message, query, actualVariables) { data ->
var page = data
collectionAt.forEach { childName ->
page = page.path(childName)
}
// List of results
val list = if (nodes) {
page.path("nodes")
} else {
page.path("edges")
}
// Conversion
list.forEach { item ->
results += code(item)
}
// Pagination
val pageInfo = page.path("pageInfo")
hasNext = pageInfo.path("hasNextPage").asBoolean()
if (hasNext) {
after = pageInfo.path("endCursor").asText()
}
}
} catch (_: GitHubNoGraphQLResponseException) {
return null
}
}
return results
}
override fun <T> graphQL(
message: String,
query: String,
variables: Map<String, *>,
token: String?,
code: (data: JsonNode) -> T,
): T {
// Getting a client
val client = createGitHubTemplate(graphql = true, token = token)
// GraphQL call
return client(message) {
val response = postForObject(
"/graphql",
mapOf(
"query" to query,
"variables" to variables
),
JsonNode::class.java
)
if (response != null) {
val errors = response.path("errors")
if (errors != null && errors.isArray && errors.size() > 0) {
val messages: List<String> = errors.map { it.path("message").asText() }
throw GitHubNoGraphQLErrorsException(message, messages)
} else {
val data = response.path("data")
code(data)
}
} else {
throw GitHubNoGraphQLResponseException(message)
}
}
}
private operator fun <T> RestTemplate.invoke(
message: String,
code: RestTemplate.() -> T,
): T {
logger.debug("[github] {}", message)
return try {
GitConnectionRetry.retry(message, retries, interval) {
code()
}
} catch (ex: RestClientResponseException) {
@Suppress("UNNECESSARY_SAFE_CALL")
val contentType: Any? = ex.responseHeaders?.contentType
if (contentType != null && contentType is MediaType && contentType.includes(MediaType.APPLICATION_JSON)) {
val json = ex.responseBodyAsString
try {
val error: GitHubErrorMessage = json.parseAsJson().parse()
throw GitHubErrorsException(message, error, ex.rawStatusCode)
} catch (_: JsonParseException) {
throw ex
}
} else {
throw ex
}
}
}
override fun createGitHubRestTemplate(token: String?): RestTemplate =
createGitHubTemplate(graphql = false, token = token)
private fun createGitHubTemplate(graphql: Boolean, token: String?): RestTemplate = RestTemplateBuilder()
.rootUri(getApiRoot(configuration.url, graphql))
.setConnectTimeout(timeout)
.setReadTimeout(timeout)
.run {
if (token != null) {
defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer $token")
} else {
when (configuration.authenticationType()) {
GitHubAuthenticationType.ANONYMOUS -> this // Nothing to be done
GitHubAuthenticationType.PASSWORD -> {
basicAuthentication(configuration.user, configuration.password)
}
GitHubAuthenticationType.USER_TOKEN -> {
basicAuthentication(configuration.user, configuration.oauth2Token)
}
GitHubAuthenticationType.TOKEN -> {
defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer ${configuration.oauth2Token}")
}
GitHubAuthenticationType.APP -> {
defaultHeader(
HttpHeaders.AUTHORIZATION,
"Bearer ${gitHubAppTokenService.getAppInstallationToken(configuration)}"
)
}
}
}
}
.build()
override fun getPullRequest(repository: String, id: Int, ignoreError: Boolean): GitPullRequest? {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Getting the PR
return try {
client("Get PR $repository#$id") {
getForObject<JsonNode?>("/repos/$owner/$name/pulls/$id")?.run {
GitPullRequest(
id = id,
key = "#$id",
source = path("head").path("ref").asText(),
target = path("base").path("ref").asText(),
title = getRequiredTextField("title"),
status = getRequiredTextField("state"),
url = getRequiredTextField("html_url"),
)
}
}
} catch (ex: GitHubErrorsException) {
if (ex.status == 404 || ignoreError) {
null
} else {
throw ex
}
}
}
override fun getRepositorySettings(repository: String, askVisibility: Boolean): GitHubRepositorySettings {
val (login, name) = getRepositoryParts(repository)
return graphQL(
message = "Get description for $repository",
query = """
query Description(${'$'}login: String!, ${'$'}name: String!) {
organization(login: ${'$'}login) {
repository(name: ${'$'}name) {
description
defaultBranchRef {
name
}
hasWikiEnabled
hasIssuesEnabled
hasProjectsEnabled
}
}
}
""",
variables = mapOf("login" to login, "name" to name)
) { data ->
val repo = data.path("organization").path("repository")
val description = repo.path("description")
.asText()
?.takeIf { it.isNotBlank() }
val branch = repo.path("defaultBranchRef")
.path("name")
.asText()
?.takeIf { it.isNotBlank() }
val hasWikiEnabled = repo.getBooleanField("hasWikiEnabled") ?: false
val hasIssuesEnabled = repo.getBooleanField("hasIssuesEnabled") ?: false
val hasProjectsEnabled = repo.getBooleanField("hasProjectsEnabled") ?: false
// Visibility
var visibility: GitHubRepositoryVisibility? = null
if (askVisibility) {
// Unfortunately, as of now, the visibility flag is not available through the GraphQL API
// and a REST call is therefore needed to get this information
val rest = createGitHubRestTemplate()
visibility = rest.getForObject("/repos/${login}/${name}", GitHubRepositoryWithVisibility::class.java)
?.visibility
?.uppercase()
?.let { GitHubRepositoryVisibility.valueOf(it) }
}
// OK
GitHubRepositorySettings(
description = description,
defaultBranch = branch,
hasWikiEnabled = hasWikiEnabled,
hasIssuesEnabled = hasIssuesEnabled,
hasProjectsEnabled = hasProjectsEnabled,
visibility = visibility,
)
}
}
override fun getFileContent(
repository: String,
branch: String?,
path: String,
retryOnNotFound: Boolean,
): ByteArray? =
getFile(repository, branch, path, retryOnNotFound)?.contentAsBinary()
override fun getFile(repository: String, branch: String?, path: String, retryOnNotFound: Boolean): GitHubFile? {
// Logging
logger.debug("[github] Getting file {}/{}@{} with retryOnNotFound=$retryOnNotFound", repository, path, branch)
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
fun internalDownload(): GitHubFile? {
return try {
val restPath = "/repos/$owner/$name/contents/$path".runIf(branch != null) {
"$this?ref=$branch"
}
client("Get file content $repository/$path@$branch") {
getForObject<GitHubGetContentResponse>(restPath).let {
GitHubFile(
content = it.content,
sha = it.sha,
)
}
}
} catch (ex: GitHubErrorsException) {
if (ex.status == 404) {
null
} else {
throw ex
}
}
}
return if (retryOnNotFound) {
var file: GitHubFile? = null
var tries = 0u
runBlocking {
while (file == null && tries < notFoundRetries) {
tries++
logger.debug("[github] Getting file {}/{}@{} with tries $tries/$notFoundRetries", repository, path, branch)
file = internalDownload()
if (file == null) {
// Waiting before the next retry
delay(notFoundInterval.toMillis())
}
}
}
file
} else {
internalDownload()
}
}
override fun getBranchLastCommit(repository: String, branch: String): String? {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Call
return client("Get last commit for $branch") {
getForObject(
"/repos/${owner}/${name}/git/ref/heads/${branch}",
GitHubGetRefResponse::class.java
)?.`object`?.sha
}
}
override fun createBranch(repository: String, source: String, destination: String): String? {
// Gets the last commit of the source branch
val sourceCommit = getBranchLastCommit(repository, source) ?: return null
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Creating the branch
return client("Create branch $destination from $source") {
val response = postForObject(
"/repos/${owner}/${name}/git/refs",
mapOf(
"ref" to "refs/heads/$destination",
"sha" to sourceCommit
),
GitHubGetRefResponse::class.java
)
// Returns the new commit
response?.`object`?.sha
}
}
override fun setFileContent(repository: String, branch: String, sha: String, path: String, content: ByteArray) {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Call
client("Setting file content at $path for branch $branch") {
put(
"/repos/$owner/$name/contents/$path",
mapOf(
"message" to "Creating $path",
"content" to Base64.encodeBase64String(content),
"sha" to sha,
"branch" to branch
)
)
}
}
override fun createPR(repository: String, title: String, head: String, base: String, body: String): GitHubPR {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Call
return client("Creating PR from $head to $base") {
postForObject(
"/repos/$owner/$name/pulls",
mapOf(
"title" to title,
"head" to head,
"base" to base,
"body" to body
),
GitHubPullRequestResponse::class.java
)
}?.run {
GitHubPR(
number = number,
mergeable = mergeable,
mergeable_state = mergeable_state,
html_url = html_url
)
} ?: throw IllegalStateException("PR creation response did not return a PR.")
}
override fun approvePR(repository: String, pr: Int, body: String, token: String?) {
// Getting a client
val client = createGitHubRestTemplate(token)
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Call
client("Approving PR $pr") {
postForObject(
"/repos/$owner/$name/pulls/$pr/reviews",
mapOf(
"body" to body,
"event" to "APPROVE"
),
JsonNode::class.java
)
}
}
override fun enableAutoMerge(repository: String, pr: Int) {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Gets the GraphQL node ID for this PR
val nodeId = client("Getting PR node ID") {
getForObject(
"/repos/${owner}/${name}/pulls/${pr}",
GitHubPullRequestResponse::class.java
)
}?.node_id ?: error("Cannot get PR node ID")
// Only the GraphQL API is available
graphQL(
"Enabling auto merge on PR $pr",
"""
mutation EnableAutoMerge(${'$'}prNodeId: ID!, ${'$'}commitHeadline: String!) {
enablePullRequestAutoMerge(input: {
pullRequestId: ${'$'}prNodeId,
commitHeadline: ${'$'}commitHeadline
}) {
pullRequest {
number
}
}
}
""",
mapOf(
"prNodeId" to nodeId,
"commitHeadline" to "Automated merged from Ontrack for auto versioning on promotion"
)
) { data ->
val prNumber = data.path("enablePullRequestAutoMerge").path("pullRequest").path("number")
if (prNumber.isNullOrNullNode()) {
throw GitHubAutoMergeNotEnabledException(repository)
}
}
}
override fun isPRMergeable(repository: String, pr: Int): Boolean {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Call
return client("Checking if PR $pr is mergeable") {
val response = getForObject(
"/repos/$owner/$name/pulls/$pr",
GitHubPullRequestResponse::class.java
)
// We need both the mergeable flag and the mergeable state
// Mergeable is not enough since it represents only the fact that the branch can be merged
// from a Git-point of view and does not represent the checks
(response?.mergeable ?: false) && (response?.mergeable_state == "clean")
}
}
override fun mergePR(repository: String, pr: Int, message: String) {
// Getting a client
val client = createGitHubRestTemplate()
// Gets the repository for this project
val (owner, name) = getRepositoryParts(repository)
// Call
client("Merging PR $pr") {
put(
"/repos/$owner/$name/pulls/$pr/merge",
mapOf(
"commit_title" to "Automated merged from Ontrack for auto versioning on promotion"
)
)
}
}
private fun JsonNode.getUserField(field: String): GitHubUser? =
getJsonField(field)?.run {
GitHubUser(
login = getRequiredTextField("login"),
url = getTextField("html_url"),
)
}
private fun JsonNode.getLabels(): List<GitHubLabel> {
val field = "labels"
return if (has(field)) {
val list = get(field)
list.map { node ->
GitHubLabel(
name = node.getRequiredTextField("name"),
color = node.getRequiredTextField("color"),
)
}
} else {
emptyList()
}
}
private fun JsonNode.getState(): GitHubState {
val value = getRequiredTextField("state")
return GitHubState.valueOf(value)
}
private fun JsonNode.getMilestone(): GitHubMilestone? = getJsonField("milestone")?.let { node ->
GitHubMilestone(
title = node.getRequiredTextField("title"),
state = node.getState(),
number = node.getRequiredIntField("number"),
url = node.getRequiredTextField("html_url"),
)
}
private fun JsonNode.getCreatedAt(): LocalDateTime =
getRequiredDateTime("created_at")
private fun JsonNode.getUpdatedAt(): LocalDateTime =
getRequiredDateTime("updated_at")
private fun JsonNode.getClosedAt(): LocalDateTime? =
getDateTime("closed_at")
private fun JsonNode.getRequiredDateTime(field: String): LocalDateTime =
getDateTime(field) ?: throw JsonParseException("Missing field $field")
private fun JsonNode.getDateTime(field: String): LocalDateTime? =
getTextField(field)?.let {
parseLocalDateTime(it)
}
companion object {
/**
* Cloud root API
*/
private const val CLOUD_ROOT_API = "https://api.github.com"
/**
* Gets the API URL for the given server URL, for REST or for GraphQL.
*
* If [graphql] is true, the URL is returned _without_ the `/graphql` suffix.
*/
fun getApiRoot(url: String, graphql: Boolean): String =
// Cloud version
if (url.trimEnd('/') == "https://github.com") {
CLOUD_ROOT_API
}
// Enterprise version
else {
val rootUrl = url.trimEnd('/')
if (graphql) {
"$rootUrl/api"
} else {
"$rootUrl/api/v3"
}
}
}
private class GitHubNoGraphQLResponseException(message: String) : BaseException(
"""
$message
No GraphQL response was returned.
""".trimIndent()
)
private class GitHubNoGraphQLErrorsException(message: String, messages: List<String>) : BaseException(
format(message, messages)
) {
companion object {
fun format(message: String, messages: List<String>): String {
val list = messages.joinToString("\n") { " - $it" }
return "$message\n\n$list"
}
}
}
private class GitHubErrorsException(
message: String,
error: GitHubErrorMessage,
val status: Int,
) : BaseException(error.format(message))
@JsonIgnoreProperties(ignoreUnknown = true)
private data class GitHubErrorMessage(
val message: String,
val errors: List<GitHubError>?,
) {
fun format(message: String): String = mapOf(
"message" to message,
"exception" to this
).toString()
}
@JsonIgnoreProperties(ignoreUnknown = true)
private data class GitHubError(
val resource: String,
val field: String,
val code: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class GitHubGetRefResponse(
val `object`: GitHubObject,
)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class GitHubObject(
val sha: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class GitHubGetContentResponse(
/**
* Base64 encoded content
*/
val content: String,
/**
* SHA of the file
*/
val sha: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class GitHubPullRequestResponse(
/**
* Local ID of the PR
*/
val number: Int,
/**
* Node ID (for use in GraphQL)
*/
val node_id: String,
/**
* Is the PR mergeable?
*/
val mergeable: Boolean?,
/**
* Mergeable status
*/
val mergeable_state: String?,
/**
* Link to the PR
*/
val html_url: String?,
)
} | mit | c35c3301ada37a408d44c2a4ee89905a | 36.363109 | 127 | 0.513693 | 5.488412 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/programs/ProgramViewModel.kt | 1 | 5058 | package org.tvheadend.tvhclient.ui.features.programs
import android.app.Application
import android.content.SharedPreferences
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import org.tvheadend.data.entity.Program
import org.tvheadend.data.entity.Recording
import org.tvheadend.data.entity.ServerProfile
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.ui.base.BaseViewModel
import timber.log.Timber
import java.util.*
class ProgramViewModel(application: Application) : BaseViewModel(application), SharedPreferences.OnSharedPreferenceChangeListener {
var program = MediatorLiveData<Program>()
var programs: LiveData<List<Program>>
var recordings: LiveData<List<Recording>>
var selectedTime: Long = System.currentTimeMillis()
var eventId = 0
var channelId = 0
var channelName = ""
var showProgramChannelIcon = false
var showGenreColor = MutableLiveData<Boolean>()
var showProgramSubtitles = MutableLiveData<Boolean>()
var showProgramArtwork = MutableLiveData<Boolean>()
val eventIdLiveData = MutableLiveData(0)
val channelIdLiveData = MutableLiveData(0)
val selectedTimeLiveData = MutableLiveData(Date().time)
private val defaultShowGenreColor = application.applicationContext.resources.getBoolean(R.bool.pref_default_genre_colors_for_programs_enabled)
private val defaultShowProgramSubtitles = application.applicationContext.resources.getBoolean(R.bool.pref_default_program_subtitle_enabled)
private val defaultShowProgramArtwork = application.applicationContext.resources.getBoolean(R.bool.pref_default_program_artwork_enabled)
init {
Timber.d("Initializing")
onSharedPreferenceChanged(sharedPreferences, "genre_colors_for_programs_enabled")
onSharedPreferenceChanged(sharedPreferences, "program_subtitle_enabled")
onSharedPreferenceChanged(sharedPreferences, "program_artwork_enabled")
program.addSource(eventIdLiveData) { value ->
if (value > 0) {
program.value = appRepository.programData.getItemById(value)
}
}
programs = Transformations.switchMap(ProgramLiveData(channelIdLiveData, selectedTimeLiveData)) { value ->
val channelId = value.first ?: 0
val selectedTime = value.second ?: Date().time
if (channelId == 0) {
return@switchMap appRepository.programData.getLiveDataItemsFromTime(selectedTime)
} else {
return@switchMap appRepository.programData.getLiveDataItemByChannelIdAndTime(channelId, selectedTime)
}
}
recordings = Transformations.switchMap(RecordingLiveData(channelIdLiveData)) { value ->
val channelId = value ?: 0
if (channelId == 0) {
return@switchMap appRepository.recordingData.getLiveDataItems()
} else {
return@switchMap appRepository.recordingData.getLiveDataItemsByChannelId(channelId)
}
}
Timber.d("Registering shared preference change listener")
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onCleared() {
Timber.d("Unregistering shared preference change listener")
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.onCleared()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
Timber.d("Shared preference $key has changed")
if (sharedPreferences == null) return
when (key) {
"genre_colors_for_programs_enabled" -> showGenreColor.value = sharedPreferences.getBoolean(key, defaultShowGenreColor)
"program_subtitle_enabled" -> showProgramSubtitles.value = sharedPreferences.getBoolean(key, defaultShowProgramSubtitles)
"program_artwork_enabled" -> showProgramArtwork.value = sharedPreferences.getBoolean(key, defaultShowProgramArtwork)
}
}
fun getRecordingProfile(): ServerProfile? {
return appRepository.serverProfileData.getItemById(appRepository.serverStatusData.activeItem.recordingServerProfileId)
}
fun getRecordingProfileNames(): Array<String> {
return appRepository.serverProfileData.recordingProfileNames
}
internal class ProgramLiveData(channelId: LiveData<Int>,
selectedTime: LiveData<Long>) : MediatorLiveData<Pair<Int?, Long?>>() {
init {
addSource(channelId) { id ->
value = Pair(id, selectedTime.value)
}
addSource(selectedTime) { time ->
value = Pair(channelId.value, time)
}
}
}
internal inner class RecordingLiveData(channelId: LiveData<Int>) : MediatorLiveData<Int?>() {
init {
addSource(channelId) { id ->
value = id
}
}
}
}
| gpl-3.0 | e538d8265eb5e1d0a431be016cf23e9d | 41.15 | 146 | 0.703045 | 5.236025 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/MessagesParser.kt | 2 | 3905 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC 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.
*
* BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.util.Xml
import edu.berkeley.boinc.utils.Logging
import org.xml.sax.Attributes
import org.xml.sax.SAXException
class MessagesParser : BaseParser() {
val messages: MutableList<Message> = mutableListOf()
private lateinit var message: Message
@Throws(SAXException::class)
override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) {
super.startElement(uri, localName, qName, attributes)
if (localName.equals(MESSAGE, ignoreCase = true) && !this::message.isInitialized) {
message = Message()
} else {
mElementStarted = true
mCurrentElement.setLength(0)
}
}
@Throws(SAXException::class)
override fun endElement(uri: String?, localName: String, qName: String?) {
super.endElement(uri, localName, qName)
try {
if (localName.equals(MESSAGE, ignoreCase = true)) {
if (message.seqno != -1) {
messages.add(message)
}
message = Message()
mElementStarted = false
} else {
when {
localName.equals(Message.Fields.BODY, ignoreCase = true) -> {
message.body = mCurrentElement.toString()
}
localName.equals(Message.Fields.PRIORITY, ignoreCase = true) -> {
message.priority = mCurrentElement.toInt()
}
localName.equals(PROJECT, ignoreCase = true) -> {
message.project = mCurrentElement.toString()
}
localName.equals(Message.Fields.TIMESTAMP, ignoreCase = true) -> {
message.timestamp = mCurrentElement.toDouble().toLong()
}
localName.equals(SEQNO, ignoreCase = true) -> {
message.seqno = mCurrentElement.toInt()
}
}
}
} catch (e: Exception) {
Logging.logException(Logging.Category.XML, "MessagesParser.endElement error: ", e)
}
}
companion object {
const val MESSAGE = "msg"
/**
* Parse the RPC result (messages) and generate corresponding list.
*
* @param rpcResult String returned by RPC call of core client
* @return list of messages
*/
@JvmStatic
fun parse(rpcResult: String): List<Message> {
return try {
// Replace 0x03 character in the rpcResult string
val rpcResultReplaced = rpcResult.replace("\u0003", "")
val parser = MessagesParser()
Xml.parse(rpcResultReplaced, parser)
parser.messages
} catch (e: SAXException) {
Logging.logException(Logging.Category.RPC, "MessagesParser: malformed XML ", e)
Logging.logDebug(Logging.Category.XML, "MessagesParser: $rpcResult")
emptyList()
}
}
}
}
| lgpl-3.0 | 65f9146acaeffed43e9051d46a0f72a3 | 38.444444 | 105 | 0.583611 | 4.899624 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.