repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/privateClassVal.kt
1
797
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.KProperty1 import kotlin.reflect.full.* import kotlin.reflect.jvm.isAccessible class Result { private val value = "OK" fun ref() = Result::class.memberProperties.single() as KProperty1<Result, String> } fun box(): String { val p = Result().ref() try { p.get(Result()) return "Fail: private property is accessible by default" } catch(e: IllegalCallableAccessException) { } p.isAccessible = true val r = p.get(Result()) p.isAccessible = false try { p.get(Result()) return "Fail: setAccessible(false) had no effect" } catch(e: IllegalCallableAccessException) { } return r }
apache-2.0
4aa0ea4ecf183c6451530fc8285369f5
22.441176
85
0.663739
3.887805
false
false
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/custom/CustomRecyclerView.kt
1
2107
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.presentation.ui.custom import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import androidx.core.widget.NestedScrollView import androidx.recyclerview.widget.RecyclerView class CustomRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RecyclerView(context, attrs, defStyleAttr) { private var externalNestedScrollView: NestedScrollView? = null var isEnabledExternalNestedScroll = false override fun onInterceptTouchEvent(event: MotionEvent): Boolean { if (!isEnabledExternalNestedScroll) { if (externalNestedScrollView == null) { externalNestedScrollView = getParentAsNestedScrollView() } if (event.action == MotionEvent.ACTION_DOWN) { externalNestedScrollView?.requestDisallowInterceptTouchEvent(true) } else if (event.action == MotionEvent.ACTION_UP) { externalNestedScrollView?.requestDisallowInterceptTouchEvent(false) } } return super.onInterceptTouchEvent(event) } private fun getParentAsNestedScrollView(): NestedScrollView? { var curParent = parent while (curParent != null) { if (curParent is NestedScrollView) { return curParent } else { curParent = curParent.parent } } return null } }
apache-2.0
1df284496bc539e3e50b0953d37afeef
35.344828
95
0.693878
5.202469
false
false
false
false
AndroidX/androidx
privacysandbox/tools/tools-apicompiler/src/test/java/androidx/privacysandbox/tools/apicompiler/parser/InterfaceParserTest.kt
3
16360
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.privacysandbox.tools.apicompiler.parser import androidx.privacysandbox.tools.apicompiler.util.checkSourceFails import androidx.privacysandbox.tools.apicompiler.util.parseSources import androidx.privacysandbox.tools.core.model.AnnotatedInterface import androidx.privacysandbox.tools.core.model.Method import androidx.privacysandbox.tools.core.model.Parameter import androidx.privacysandbox.tools.core.model.ParsedApi import androidx.privacysandbox.tools.core.model.Types import androidx.privacysandbox.tools.core.model.Type import androidx.room.compiler.processing.util.Source import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class InterfaceParserTest { @Test fun parseServiceInterface_ok() { val source = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService interface MySdk { suspend fun doStuff(x: Int, y: Int): String suspend fun processList(list: List<Int>): List<String> fun doMoreStuff() } """, ) assertThat(parseSources(source)).isEqualTo( ParsedApi( services = mutableSetOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), methods = listOf( Method( name = "doStuff", parameters = listOf( Parameter( name = "x", type = Types.int, ), Parameter( name = "y", type = Types.int, ) ), returnType = Types.string, isSuspend = true, ), Method( name = "processList", parameters = listOf( Parameter( name = "list", type = Types.list(Types.int), ) ), returnType = Types.list(Types.string), isSuspend = true, ), Method( name = "doMoreStuff", parameters = listOf(), returnType = Types.unit, isSuspend = false, ) ) ) ) ) ) } @Test fun serviceAnnotatedClass_fails() { val source = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService abstract class MySdk { // Fails because it's a class, not an interface. abstract fun doStuff(x: Int, y: Int): String } """ ) checkSourceFails(source) .containsError("Only interfaces can be annotated with @PrivacySandboxService.") } @Test fun multipleServices_fails() { val source = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService interface MySdk """ ) val source2 = Source.kotlin( "com/mysdk/MySdk2.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService interface MySdk2 """ ) checkSourceFails(source, source2) .containsError( "Multiple interfaces annotated with @PrivacySandboxService are not " + "supported (MySdk, MySdk2)." ) } @Test fun privateInterface_fails() { checkSourceFails( serviceInterface("private interface MySdk") ).containsError("Error in com.mysdk.MySdk: annotated interfaces should be public.") } @Test fun interfaceWithProperties_fails() { checkSourceFails( serviceInterface( """public interface MySdk { | val x: Int |} """.trimMargin() ) ).containsExactlyErrors( "Error in com.mysdk.MySdk: annotated interfaces cannot declare properties." ) } @Test fun interfaceWithCompanionObject_fails() { checkSourceFails( serviceInterface( """interface MySdk { | companion object { | fun foo() {} | } |} """.trimMargin() ) ).containsExactlyErrors( "Error in com.mysdk.MySdk: annotated interfaces cannot declare companion objects." ) } @Test fun interfaceWithInvalidModifier_fails() { checkSourceFails( serviceInterface( """external fun interface MySdk { | suspend fun apply() |} """.trimMargin() ) ).containsExactlyErrors( "Error in com.mysdk.MySdk: annotated interface contains invalid modifiers (external, " + "fun)." ) } @Test fun interfaceWithGenerics_fails() { checkSourceFails( serviceInterface( """interface MySdk<T, U> { | suspend fun getT() |} """.trimMargin() ) ).containsExactlyErrors( "Error in com.mysdk.MySdk: annotated interfaces cannot declare type parameters (T, U)." ) } @Test fun methodWithImplementation_fails() { checkSourceFails(serviceMethod("suspend fun foo(): Int = 1")).containsExactlyErrors( "Error in com.mysdk.MySdk.foo: method cannot have default implementation." ) } @Test fun methodWithGenerics_fails() { checkSourceFails(serviceMethod("suspend fun <T> foo()")).containsExactlyErrors( "Error in com.mysdk.MySdk.foo: method cannot declare type parameters (<T>)." ) } @Test fun methodWithInvalidModifiers_fails() { checkSourceFails(serviceMethod("suspend inline fun foo()")).containsExactlyErrors( "Error in com.mysdk.MySdk.foo: method contains invalid modifiers (inline)." ) } @Test fun parameterWitDefaultValue_fails() { checkSourceFails(serviceMethod("suspend fun foo(x: Int = 5)")).containsExactlyErrors( "Error in com.mysdk.MySdk.foo: parameters cannot have default values." ) } @Test fun parameterWithGenerics_fails() { checkSourceFails(serviceMethod("suspend fun foo(x: MutableList<Int>)")) .containsExactlyErrors( "Error in com.mysdk.MySdk.foo: only primitives, lists, data classes annotated " + "with @PrivacySandboxValue and interfaces annotated with " + "@PrivacySandboxCallback or @PrivacySandboxInterface are supported as " + "parameter types." ) } @Test fun listParameterWithNonInvariantTypeArgument_fails() { checkSourceFails(serviceMethod("suspend fun foo(x: List<in Int>)")) .containsExactlyErrors( "Error in com.mysdk.MySdk.foo: only invariant type arguments are supported." ) } @Test fun parameterLambda_fails() { checkSourceFails(serviceMethod("suspend fun foo(x: (Int) -> Int)")) .containsExactlyErrors( "Error in com.mysdk.MySdk.foo: only primitives, lists, data classes annotated " + "with @PrivacySandboxValue and interfaces annotated with " + "@PrivacySandboxCallback or @PrivacySandboxInterface are supported as " + "parameter types." ) } @Test fun returnTypeCustomClass_fails() { val source = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService interface MySdk { suspend fun foo(): CustomClass } class CustomClass """ ) checkSourceFails(source).containsExactlyErrors( "Error in com.mysdk.MySdk.foo: only primitives, lists, data classes annotated with " + "@PrivacySandboxValue and interfaces annotated with @PrivacySandboxInterface are " + "supported as return types." ) } @Test fun nullableParameter_fails() { checkSourceFails(serviceMethod("suspend fun foo(x: Int?)")) .containsError( "Error in com.mysdk.MySdk.foo: nullable types are not supported." ) } @Test fun parseCallbackInterface_ok() { val serviceSource = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService interface MySdk """ ) val callbackSource = Source.kotlin( "com/mysdk/MyCallback.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxCallback @PrivacySandboxCallback interface MyCallback { fun onComplete(x: Int, y: Int) } """ ) assertThat(parseSources(serviceSource, callbackSource)).isEqualTo( ParsedApi( services = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), ) ), callbacks = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MyCallback"), methods = listOf( Method( name = "onComplete", parameters = listOf( Parameter( name = "x", type = Types.int, ), Parameter( name = "y", type = Types.int, ) ), returnType = Types.unit, isSuspend = false, ), ) ) ) ) ) } @Test fun parseInterface_ok() { val serviceSource = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService interface MySdk { suspend fun doStuff(request: MyInterface): MyInterface } """ ) val interfaceSource = Source.kotlin( "com/mysdk/MyInterface.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxInterface @PrivacySandboxInterface interface MyInterface { suspend fun doMoreStuff(x: Int, y: Int): String } """ ) assertThat(parseSources(serviceSource, interfaceSource)).isEqualTo( ParsedApi( services = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MySdk"), methods = listOf( Method( name = "doStuff", parameters = listOf( Parameter( name = "request", type = Type( packageName = "com.mysdk", simpleName = "MyInterface" ), ) ), returnType = Type( packageName = "com.mysdk", simpleName = "MyInterface" ), isSuspend = true, ), ) ) ), interfaces = setOf( AnnotatedInterface( type = Type(packageName = "com.mysdk", simpleName = "MyInterface"), methods = listOf( Method( name = "doMoreStuff", parameters = listOf( Parameter( name = "x", type = Types.int, ), Parameter( name = "y", type = Types.int, ) ), returnType = Types.string, isSuspend = true, ), ) ) ) ) ) } private fun serviceInterface(declaration: String) = Source.kotlin( "com/mysdk/MySdk.kt", """ package com.mysdk import androidx.privacysandbox.tools.PrivacySandboxService @PrivacySandboxService $declaration """ ) private fun serviceMethod(declaration: String) = serviceInterface( """ interface MySdk { $declaration } """ ) }
apache-2.0
5adee096f8d1fb26e8accebf66bc701b
36.099773
100
0.454218
6.237133
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt
1
17038
// 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.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables import org.jetbrains.kotlin.idea.references.KtSimpleReference import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.getArgumentByParameterIndex import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntention<KtTypeReference>( KtTypeReference::class.java, KotlinBundle.lazyMessage("convert.function.type.receiver.to.parameter") ) { class ConversionData( val functionParameterIndex: Int?, val lambdaReceiverType: KotlinType, callableDeclaration: KtCallableDeclaration, ) { private val declarationPointer = callableDeclaration.createSmartPointer() val callableDeclaration: KtCallableDeclaration? get() = declarationPointer.element val functionDescriptor by lazy { callableDeclaration.unsafeResolveToDescriptor() as CallableDescriptor } fun functionType(declaration: KtCallableDeclaration? = callableDeclaration): KtFunctionType? { val functionTypeOwner = if (functionParameterIndex != null) declaration?.valueParameters?.getOrNull(functionParameterIndex) else declaration return functionTypeOwner?.typeReference?.typeElement as? KtFunctionType } } class CallableDefinitionInfo(element: KtCallableDeclaration) : AbstractProcessableUsageInfo<KtCallableDeclaration, ConversionData>(element) { override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) { val declaration = element ?: return val functionType = data.functionType(declaration) ?: return val functionTypeParameterList = functionType.parameterList ?: return val functionTypeReceiver = functionType.receiverTypeReference ?: return val parameterToAdd = KtPsiFactory(project).createFunctionTypeParameter(functionTypeReceiver) functionTypeParameterList.addParameterBefore(parameterToAdd, functionTypeParameterList.parameters.firstOrNull()) functionType.setReceiverTypeReference(null) } } class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) { override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) { val callExpression = element ?: return val qualifiedExpression = callExpression.getQualifiedExpressionForSelector() ?: return val receiverExpression = qualifiedExpression.receiverExpression val argumentList = callExpression.getOrCreateValueArgumentList() argumentList.addArgumentBefore(KtPsiFactory(project).createArgument(receiverExpression), argumentList.arguments.firstOrNull()) qualifiedExpression.replace(callExpression) } } class LambdaInfo(element: KtLambdaExpression) : AbstractProcessableUsageInfo<KtLambdaExpression, ConversionData>(element) { override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) { val lambda = element?.functionLiteral ?: return val context = lambda.analyze() val lambdaDescriptor = context[BindingContext.FUNCTION, lambda] ?: return val psiFactory = KtPsiFactory(project) val validator = CollectingNameValidator( lambda.valueParameters.mapNotNull { it.name }, NewDeclarationNameValidator(lambda.bodyExpression!!, null, NewDeclarationNameValidator.Target.VARIABLES) ) val lambdaExtensionReceiver = lambdaDescriptor.extensionReceiverParameter val lambdaDispatchReceiver = lambdaDescriptor.dispatchReceiverParameter val newParameterName = KotlinNameSuggester.suggestNamesByType(data.lambdaReceiverType, validator, "p").first() val newParameterRefExpression = psiFactory.createExpression(newParameterName) lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression is KtOperationReferenceExpression) return val resolvedCall = expression.getResolvedCall(context) ?: return val dispatchReceiverTarget = resolvedCall.dispatchReceiver?.getReceiverTargetDescriptor(context) val extensionReceiverTarget = resolvedCall.extensionReceiver?.getReceiverTargetDescriptor(context) if (dispatchReceiverTarget == lambdaDescriptor || extensionReceiverTarget == lambdaDescriptor) { val parent = expression.parent if (parent is KtCallExpression && expression == parent.calleeExpression) { if ((parent.parent as? KtQualifiedExpression)?.receiverExpression !is KtThisExpression) { parent.replace(psiFactory.createExpressionByPattern("$0.$1", newParameterName, parent)) } } else if (parent is KtQualifiedExpression && parent.receiverExpression is KtThisExpression) { // do nothing } else { val referencedName = expression.getReferencedName() expression.replace(psiFactory.createExpressionByPattern("$newParameterName.$referencedName")) } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(context) ?: return if (resolvedCall.resultingDescriptor == lambdaDispatchReceiver || resolvedCall.resultingDescriptor == lambdaExtensionReceiver ) { expression.replace(newParameterRefExpression.copy()) } } }) val lambdaParameterList = lambda.getOrCreateParameterList() if (lambda.valueParameters.isEmpty() && lambdaDescriptor.valueParameters.isNotEmpty()) { val parameterToAdd = psiFactory.createLambdaParameterList("it").parameters.first() lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull()) } val parameterToAdd = psiFactory.createLambdaParameterList(newParameterName).parameters.first() lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull()) } } private inner class Converter( private val data: ConversionData, editor: Editor?, project: Project, ) : CallableRefactoring<CallableDescriptor>(project, editor, data.functionDescriptor, text) { override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) { val callables = getAffectedCallables(project, descriptorsForChange) val conflicts = MultiMap<PsiElement, String>() val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>() project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) { runReadAction { val progressStep = 1.0 / callables.size val progressIndicator = ProgressManager.getInstance().progressIndicator progressIndicator.isIndeterminate = false for ((i, callable) in callables.withIndex()) { progressIndicator.fraction = (i + 1) * progressStep if (callable !is KtCallableDeclaration) continue if (!checkModifiable(callable)) { val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize() conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable)) } for (ref in callable.searchReferencesOrMethodReferences()) { if (ref !is KtSimpleReference<*>) continue processExternalUsage(ref, usages) } usages += CallableDefinitionInfo(callable) processInternalUsages(callable, usages) } } } project.checkConflictsInteractively(conflicts) { project.executeWriteCommand(text) { val elementsToShorten = ArrayList<KtElement>() usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) } ShortenReferences.DEFAULT.process(elementsToShorten) } } } private fun processExternalUsage( ref: KtSimpleReference<*>, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>> ) { val parameterIndex = data.functionParameterIndex ?: return val callElement = ref.element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression } ?: return val context = callElement.analyze(BodyResolveMode.PARTIAL) val expressionToProcess = callElement .getArgumentByParameterIndex(parameterIndex, context) .singleOrNull() ?.getArgumentExpression() ?.let { KtPsiUtil.safeDeparenthesize(it) } ?: return if (expressionToProcess is KtLambdaExpression) { usages += LambdaInfo(expressionToProcess) } } private fun processInternalUsages( callable: KtCallableDeclaration, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>> ) { val parameterIndex = data.functionParameterIndex ?: return processLambdasInReturnExpressions(callable, usages) val body = when (callable) { is KtConstructor<*> -> callable.containingClassOrObject?.body is KtDeclarationWithBody -> callable.bodyExpression else -> null } if (body != null) { val functionParameter = callable.valueParameters.getOrNull(parameterIndex) ?: return for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) { val element = ref.element as? KtSimpleNameExpression ?: continue val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression } ?: continue usages += ParameterCallInfo(callExpression) } } } private fun processLambdasInReturnExpressions( callable: KtCallableDeclaration, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>, ) { assert(data.functionParameterIndex == null) when (callable) { is KtNamedFunction -> processBody(callable, usages, callable.bodyExpression) is KtProperty -> { processBody(callable, usages, callable.initializer) callable.getter?.let { processBody(it, usages, it.bodyExpression) } } else -> Unit } } private fun processBody( declaration: KtDeclaration, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>, bodyExpression: KtExpression?, ) = when (val body = bodyExpression?.deparenthesize()) { is KtLambdaExpression -> usages += LambdaInfo(body) is KtBlockExpression -> { val context by lazy { declaration.analyze(BodyResolveMode.PARTIAL_WITH_CFA) } val target by lazy { context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] } bodyExpression.forEachDescendantOfType<KtReturnExpression> { returnExpression -> returnExpression.returnedExpression ?.deparenthesize() ?.safeAs<KtLambdaExpression>() ?.takeIf { returnExpression.getTargetFunctionDescriptor(context) == target } ?.let { usages += LambdaInfo(it) } } } else -> Unit } } private fun KtTypeReference.getConversionData(): ConversionData? { val functionTypeReceiver = parent as? KtFunctionTypeReceiver ?: return null val functionType = functionTypeReceiver.parent as? KtFunctionType ?: return null val lambdaReceiverType = functionType .getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) ?.getReceiverTypeFromFunctionType() ?: return null val typeReferenceHolder = functionType.parent?.safeAs<KtTypeReference>()?.parent?.safeAs<KtCallableDeclaration>() ?: return null val (callableDeclaration, parameterIndex) = if (typeReferenceHolder is KtParameter) { val callableDeclaration = typeReferenceHolder.ownerFunction as? KtCallableDeclaration ?: return null callableDeclaration to callableDeclaration.valueParameters.indexOf(typeReferenceHolder) } else typeReferenceHolder to null return ConversionData(parameterIndex, lambdaReceiverType, callableDeclaration) } override fun startInWriteAction(): Boolean = false override fun applicabilityRange(element: KtTypeReference): TextRange? { val data = element.getConversionData() ?: return null val elementBefore = data.functionType() ?: return null val elementAfter = elementBefore.copied().apply { parameterList?.addParameterBefore( KtPsiFactory(element).createFunctionTypeParameter(element), parameterList?.parameters?.firstOrNull() ) setReceiverTypeReference(null) } setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text)) return element.textRange } override fun applyTo(element: KtTypeReference, editor: Editor?) { element.getConversionData()?.let { Converter(it, editor, element.project).run() } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction = ConvertFunctionTypeReceiverToParameterIntention() } }
apache-2.0
abfe0e105c2c321784bb89b61cc61f2a
51.589506
158
0.678953
6.429434
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/sanity/SanityTestElementPicker.kt
6
2932
// 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.structuralsearch.sanity import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.psi.* import kotlin.random.Random object SanityTestElementPicker { private val random = Random(System.currentTimeMillis()) private const val KEEP_RATIO = 0.7 /** Tells which Kotlin [PsiElement]-s can be used directly or not (i.e. some child) as a SSR pattern. */ private val PsiElement.isSearchable: Boolean get() = when (this) { is PsiWhiteSpace, is KtPackageDirective, is KtImportList -> false is KtParameterList, is KtValueArgumentList, is KtSuperTypeList, is KtTypeArgumentList, is KtTypeParameterList, is KtBlockExpression, is KtClassBody -> this.children.any() is KtModifierList, is KtDeclarationModifierList -> false is LeafPsiElement, is KtOperationReferenceExpression -> false is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> false is KDocSection -> false else -> true } private fun shouldStopAt(element: PsiElement) = when (element) { is KtAnnotationEntry -> true else -> false } private fun mustContinueAfter(element: PsiElement) = when (element) { is KtParameterList, is KtValueArgumentList, is KtSuperTypeList, is KtTypeArgumentList, is KtTypeParameterList -> true is KtClassBody, is KtBlockExpression, is KtBlockCodeFragment -> true is KtPrimaryConstructor -> true is KtParameter -> true is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry, is KtSuperTypeCallEntry -> true is KtClassOrObject -> (element.body?.children?.size ?: 0) > 4 is KtContainerNode -> true is KtWhenEntry -> true is KtPropertyAccessor -> true else -> false } /** Returns a random [PsiElement] whose text can be used as a pattern against [tree]. */ fun pickFrom(tree: Array<PsiElement>): PsiElement? { if (tree.isEmpty()) return null var element = tree.filter { it.isSearchable }.random() var canContinue: Boolean var mustContinue: Boolean do { val searchableChildren = element.children.filter { it.isSearchable } if (searchableChildren.isEmpty()) break element = searchableChildren.random() canContinue = element.children.any { it.isSearchable } && !shouldStopAt(element) mustContinue = random.nextFloat() > KEEP_RATIO || mustContinueAfter(element) } while (canContinue && mustContinue) return element } }
apache-2.0
ab9d056ccd5a121803a5b13844aa6977
42.132353
158
0.689973
5.108014
false
false
false
false
Flank/flank
tool/junit/src/main/kotlin/flank/junit/internal/CalculateMedianDurations.kt
1
836
package flank.junit.internal import flank.junit.JUnit /** * Group test case results by full name and associate with calculated median of durations in group. */ internal fun List<JUnit.TestResult>.calculateMedianDurations(): Map<String, Long> = this .map { result -> result.fullName to result.duration } .groupBy(Pair<String, Long>::first, Pair<String, Long>::second) .mapValues { (_, durations) -> durations.median() } private val JUnit.TestResult.fullName get() = className + if (testName.isBlank()) "" else "#$testName" private val JUnit.TestResult.duration get() = (endsAt - startAt) private fun List<Long>.median(): Long = when { isEmpty() -> throw IllegalArgumentException("Cannot calculate median of empty list") size % 2 == 0 -> (size / 2).let { get(it - 1) + get(it) } / 2 else -> get(size / 2) }
apache-2.0
77288efd5705e8e84a7e829b331ee47e
38.809524
102
0.688995
3.852535
false
true
false
false
Pattonville-App-Development-Team/Android-App
app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/directory/detail/single/DataSourceSummaryItem.kt
1
5639
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.pattonvillecs.pattonvilleapp.view.ui.directory.detail.single import android.content.Context import android.content.Intent import android.net.Uri import android.support.annotation.DrawableRes import android.view.View import android.widget.ImageView import android.widget.TextView import com.squareup.picasso.provider.PicassoProvider import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import org.jetbrains.anko.browse import org.jetbrains.anko.find import org.jetbrains.anko.sdk25.coroutines.onClick import org.pattonvillecs.pattonvilleapp.R import org.pattonvillecs.pattonvilleapp.service.model.DataSource import org.pattonvillecs.pattonvilleapp.view.ui.calendar.details.CalendarEventDetailsActivity import org.pattonvillecs.pattonvilleapp.view.ui.directory.detail.IFacultyItem import org.pattonvillecs.pattonvilleapp.view.ui.directory.detail.single.DataSourceSummaryItem.DataSourceSummaryItemViewHolder /** * Created by Mitchell Skaggs on 12/10/2017. */ data class DataSourceSummaryItem(val dataSource: DataSource) : AbstractFlexibleItem<DataSourceSummaryItemViewHolder>(), IFacultyItem<DataSourceSummaryItemViewHolder> { override val location: DataSource? get() = dataSource override fun getLayoutRes(): Int = R.layout.directory_datasource_suummary_item override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<*>>, holder: DataSourceSummaryItemViewHolder, position: Int, payloads: MutableList<Any>?) { PicassoProvider.get() .load(getImageResourceForDataSource(dataSource)) .fit() .centerCrop() .into(holder.schoolImage) holder.address.text = dataSource.address holder.address.onClick { val gmmIntentUri = Uri.parse("geo:" + CalendarEventDetailsActivity.PATTONVILLE_COORDINATES + "?q=" + Uri.encode(dataSource.address)) val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri) it?.context?.startActivity(mapIntent) } holder.mainPhone.apply { text = dataSource.mainNumber onClick { it?.context?.dial(dataSource.mainNumber) } } dataSource.attendanceNumber.ifPresentOrElse({ number -> holder.attendancePhone.apply { text = number onClick { it?.context?.dial(number) } } }, { holder.attendancePhone.text = "N/A" }) dataSource.faxNumber.ifPresentOrElse({ number -> holder.fax.text = number }, { holder.fax.text = "N/A" }) holder.website.onClick { it?.context?.browse(dataSource.websiteURL) } } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<*>>): DataSourceSummaryItemViewHolder = DataSourceSummaryItemViewHolder(view, adapter) class DataSourceSummaryItemViewHolder(view: View, adapter: FlexibleAdapter<out IFlexible<*>>, stickyHeader: Boolean = false) : FlexibleViewHolder(view, adapter, stickyHeader) { val schoolImage = view.find<ImageView>(R.id.school_image) val address = view.find<TextView>(R.id.address) val mainPhone = view.find<TextView>(R.id.main_phone) val attendancePhone = view.find<TextView>(R.id.attendance_phone) val fax = view.find<TextView>(R.id.fax) val website = view.find<TextView>(R.id.website) } @DrawableRes private fun getImageResourceForDataSource(dataSource: DataSource): Int { return when (dataSource) { DataSource.HIGH_SCHOOL -> R.drawable.highschool_building DataSource.HEIGHTS_MIDDLE_SCHOOL -> R.drawable.heights_building DataSource.HOLMAN_MIDDLE_SCHOOL -> R.drawable.holman_building DataSource.REMINGTON_TRADITIONAL_SCHOOL -> R.drawable.remington_building DataSource.BRIDGEWAY_ELEMENTARY -> R.drawable.bridgeway_building DataSource.DRUMMOND_ELEMENTARY -> R.drawable.drummond_building DataSource.PARKWOOD_ELEMENTARY -> R.drawable.parkwood_building DataSource.ROSE_ACRES_ELEMENTARY -> R.drawable.roseacres_building DataSource.WILLOW_BROOK_ELEMENTARY -> R.drawable.willowbrook_building DataSource.DISTRICT -> R.drawable.learningcenter_building else -> R.drawable.learningcenter_building } } } private fun Context.dial(number: String): Boolean { return try { val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$number")) startActivity(intent) true } catch (e: Exception) { e.printStackTrace() false } }
gpl-3.0
2833f12ab304e6f290b2de982a839b18
41.719697
180
0.702962
4.514812
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/services/RemoteVolumeProvider.kt
1
1238
package com.kelsos.mbrc.services import androidx.media.VolumeProviderCompat import com.kelsos.mbrc.constants.Protocol import com.kelsos.mbrc.data.UserAction import com.kelsos.mbrc.events.MessageEvent import com.kelsos.mbrc.events.bus.RxBus import com.kelsos.mbrc.events.ui.VolumeChange import com.kelsos.mbrc.model.MainDataModel import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteVolumeProvider @Inject constructor( private val mainDataModel: MainDataModel, private val bus: RxBus ) : VolumeProviderCompat(VOLUME_CONTROL_ABSOLUTE, 100, 0) { init { super.setCurrentVolume(mainDataModel.volume) bus.register(this, VolumeChange::class.java) { super.setCurrentVolume(it.volume) } } override fun onSetVolumeTo(volume: Int) { post(UserAction.create(Protocol.PlayerVolume, volume)) currentVolume = volume } override fun onAdjustVolume(direction: Int) { if (direction == 0) { return } val volume = mainDataModel.volume.plus(direction) .coerceAtLeast(0) .coerceAtMost(100) post(UserAction.create(Protocol.PlayerVolume, volume)) currentVolume = volume } private fun post(action: UserAction) { bus.post(MessageEvent.action(action)) } }
gpl-3.0
a02939ba5a12ae52dd317b6490add4ad
26.511111
86
0.758481
3.856698
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/HintsTypeRenderer.kt
1
15654
// 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.parameterInfo import org.jetbrains.kotlin.builtins.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetail import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail import org.jetbrains.kotlin.idea.codeInsight.hints.TypeInlayInfoDetail import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.renderer.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.ArrayList /** * copy-pasted and inspired by [DescriptorRendererImpl] * * To render any kotlin type into a sequence of short and human-readable kotlin types like * - Int * - Int? * - List<String?>? * * For each type short name and fqName is provided (see [TypeInlayInfoDetail]). */ class HintsTypeRenderer private constructor(val options: HintsDescriptorRendererOptions) { init { check(options.isLocked) { "options have not been locked yet to prevent mutability" } check(options.textFormat == RenderingFormat.PLAIN) { "only PLAIN text format is supported" } check(!options.verbose) { "verbose mode is not supported" } check(!options.renderTypeExpansions) { "Type expansion rendering is unsupported" } } private val renderer = DescriptorRenderer.COMPACT_WITH_SHORT_TYPES.withOptions {} @Suppress("SuspiciousCollectionReassignment") private val functionTypeAnnotationsRenderer: HintsTypeRenderer by lazy { withOptions { excludedTypeAnnotationClasses += listOf(StandardNames.FqNames.extensionFunctionType) } } /* FORMATTING */ private fun renderError(keyword: String): String = keyword private fun escape(string: String) = options.textFormat.escape(string) private fun lt() = escape("<") private fun gt() = escape(">") private fun arrow(): String = escape("->") /* NAMES RENDERING */ private fun renderName(name: Name): String = escape(name.render()) /* TYPES RENDERING */ fun renderType(type: KotlinType): List<InlayInfoDetail> { val list = mutableListOf<InlayInfoDetail>() return options.typeNormalizer.invoke(type).renderNormalizedTypeTo(list) } private fun MutableList<InlayInfoDetail>.append(text: String): MutableList<InlayInfoDetail> = apply { add(TextInlayInfoDetail(text)) } private fun MutableList<InlayInfoDetail>.append(text: String, descriptor: ClassifierDescriptor?): MutableList<InlayInfoDetail> { descriptor?.let { add(TypeInlayInfoDetail(text, it.fqNameSafe.asString())) } ?: run { append(text) } return this } private fun KotlinType.renderNormalizedTypeTo(list: MutableList<InlayInfoDetail>): MutableList<InlayInfoDetail> { this.unwrap().safeAs<AbbreviatedType>()?.let { abbreviated -> // TODO nullability is lost for abbreviated type? abbreviated.abbreviation.renderNormalizedTypeAsIsTo(list) if (options.renderUnabbreviatedType) { abbreviated.renderAbbreviatedTypeExpansionTo(list) } return list } this.renderNormalizedTypeAsIsTo(list) return list } private fun AbbreviatedType.renderAbbreviatedTypeExpansionTo(list: MutableList<InlayInfoDetail>) { list.append(" /* = ") this.expandedType.renderNormalizedTypeAsIsTo(list) list.append(" */") } private fun KotlinType.renderNormalizedTypeAsIsTo(list: MutableList<InlayInfoDetail>) { if (this is WrappedType && !this.isComputed()) { list.append("<Not computed yet>") return } when (val unwrappedType = this.unwrap()) { is FlexibleType -> list.append(unwrappedType.render(renderer, options)) is SimpleType -> unwrappedType.renderSimpleTypeTo(list) } } private fun SimpleType.renderSimpleTypeTo(list: MutableList<InlayInfoDetail>) { if (this == TypeUtils.CANT_INFER_FUNCTION_PARAM_TYPE || TypeUtils.isDontCarePlaceholder(this)) { list.append("???") return } if (ErrorUtils.isUninferredParameter(this)) { if (options.uninferredTypeParameterAsName) { list.append(renderError((this.constructor as ErrorUtils.UninferredParameterTypeConstructor).typeParameterDescriptor.name.toString())) } else { list.append("???") } return } if (this.isError) { this.renderDefaultTypeTo(list) return } if (shouldRenderAsPrettyFunctionType(this)) { this.renderFunctionTypeTo(list) } else { this.renderDefaultTypeTo(list) } } private fun shouldRenderAsPrettyFunctionType(type: KotlinType): Boolean { return type.isBuiltinFunctionalType && type.arguments.none { it.isStarProjection } } private fun List<TypeProjection>.renderTypeArgumentsTo(list: MutableList<InlayInfoDetail>) { if (this.isNotEmpty()) { list.append(lt()) this.appendTypeProjectionsTo(list) list.append(gt()) } } private fun KotlinType.renderDefaultTypeTo(list: MutableList<InlayInfoDetail>) { renderAnnotationsTo(list) if (this.isError) { if (this is UnresolvedType && options.presentableUnresolvedTypes) { list.append(this.presentableName) } else { if (this is ErrorType && !options.informativeErrorType) { list.append(this.presentableName) } else { list.append(this.constructor.toString()) // Debug name of an error type is more informative } } this.arguments.renderTypeArgumentsTo(list) } else { this.renderTypeConstructorAndArgumentsTo(list) } if (this.isMarkedNullable) { list.append("?") } if (this.isDefinitelyNotNullType) { list.append("!!") } } private fun KotlinType.renderTypeConstructorAndArgumentsTo( list: MutableList<InlayInfoDetail>, typeConstructor: TypeConstructor = this.constructor ) { val possiblyInnerType = this.buildPossiblyInnerType() if (possiblyInnerType == null) { typeConstructor.renderTypeConstructorTo(list) this.arguments.renderTypeArgumentsTo(list) return } possiblyInnerType.renderPossiblyInnerTypeTo(list) } private fun PossiblyInnerType.renderPossiblyInnerTypeTo(list: MutableList<InlayInfoDetail>) { this.outerType?.let { it.renderPossiblyInnerTypeTo(list) list.append(".") list.append(renderName(this.classifierDescriptor.name)) } ?: this.classifierDescriptor.typeConstructor.renderTypeConstructorTo(list) this.arguments.renderTypeArgumentsTo(list) } fun TypeConstructor.renderTypeConstructorTo(list: MutableList<InlayInfoDetail>){ val text = when (val cd = this.declarationDescriptor) { is TypeParameterDescriptor, is ClassDescriptor, is TypeAliasDescriptor -> renderClassifierName(cd) null -> this.toString() else -> error("Unexpected classifier: " + cd::class.java) } list.append(text, this.declarationDescriptor) } fun renderClassifierName(klass: ClassifierDescriptor): String = if (ErrorUtils.isError(klass)) { klass.typeConstructor.toString() } else options.hintsClassifierNamePolicy.renderClassifier(klass, this) private fun KotlinType.renderFunctionTypeTo(list: MutableList<InlayInfoDetail>) { val type = this val lengthBefore = list.size // we need special renderer to skip @ExtensionFunctionType with(functionTypeAnnotationsRenderer) { type.renderAnnotationsTo(list) } val hasAnnotations = list.size != lengthBefore val isSuspend = this.isSuspendFunctionType val isNullable = this.isMarkedNullable val receiverType = this.getReceiverTypeFromFunctionType() val needParenthesis = isNullable || (hasAnnotations && receiverType != null) if (needParenthesis) { if (isSuspend) { list.add(lengthBefore, TextInlayInfoDetail("(")) } else { if (hasAnnotations) { if (list[list.lastIndex - 1].text != ")") { // last annotation rendered without parenthesis - need to add them otherwise parsing will be incorrect list.add(list.lastIndex, TextInlayInfoDetail("()")) } } list.append("(") } } if (receiverType != null) { val surroundReceiver = shouldRenderAsPrettyFunctionType(receiverType) && !receiverType.isMarkedNullable || receiverType.hasModifiersOrAnnotations() if (surroundReceiver) { list.append("(") } receiverType.renderNormalizedTypeTo(list) if (surroundReceiver) { list.append(")") } list.append(".") } list.append("(") val parameterTypes = this.getValueParameterTypesFromFunctionType() for ((index, typeProjection) in parameterTypes.withIndex()) { if (index > 0) list.append(", ") if (options.parameterNamesInFunctionalTypes) { typeProjection.type.extractParameterNameFromFunctionTypeArgument()?.let { name -> list.append(renderName(name)) list.append(": ") } } typeProjection.renderTypeProjectionTo(list) } list.append(") ").append(arrow()).append(" ") this.getReturnTypeFromFunctionType().renderNormalizedTypeTo(list) if (needParenthesis) list.append(")") if (isNullable) list.append("?") } private fun KotlinType.hasModifiersOrAnnotations() = isSuspendFunctionType || !annotations.isEmpty() fun TypeProjection.renderTypeProjectionTo(list: MutableList<InlayInfoDetail>) = listOf(this).appendTypeProjectionsTo(list) private fun List<TypeProjection>.appendTypeProjectionsTo(list: MutableList<InlayInfoDetail>) { val iterator = this.iterator() while (iterator.hasNext()) { val next = iterator.next() if (next.isStarProjection) { list.append("*") } else { val renderedType = renderType(next.type) if (next.projectionKind != Variance.INVARIANT) { list.append("${next.projectionKind} ") } list.addAll(renderedType) } if (iterator.hasNext()) { list.append(", ") } } } private fun Annotated.renderAnnotationsTo(list: MutableList<InlayInfoDetail>, target: AnnotationUseSiteTarget? = null) { if (DescriptorRendererModifier.ANNOTATIONS !in options.modifiers) return val excluded = if (this is KotlinType) options.excludedTypeAnnotationClasses else options.excludedAnnotationClasses val annotationFilter = options.annotationFilter for (annotation in this.annotations) { if (annotation.fqName !in excluded && !annotation.isParameterName() && (annotationFilter == null || annotationFilter(annotation)) ) { list.append(renderAnnotation(annotation, target)) if (options.eachAnnotationOnNewLine) { list.append("\n") } else { list.append(" ") } } } } private fun AnnotationDescriptor.isParameterName(): Boolean { return fqName == StandardNames.FqNames.parameterName } fun renderAnnotation(annotation: AnnotationDescriptor, target: AnnotationUseSiteTarget?): String { return buildString { append('@') if (target != null) { append(target.renderName + ":") } val annotationType = annotation.type append(renderType(annotationType)) } } companion object { @JvmStatic private fun withOptions(changeOptions: HintsDescriptorRendererOptions.() -> Unit): HintsTypeRenderer { val options = HintsDescriptorRendererOptions() options.changeOptions() options.lock() return HintsTypeRenderer(options) } internal fun getInlayHintsTypeRenderer(bindingContext: BindingContext, context: KtElement) = withOptions { modifiers = emptySet() parameterNameRenderingPolicy = ParameterNameRenderingPolicy.ONLY_NON_SYNTHESIZED enhancedTypes = true textFormat = RenderingFormat.PLAIN renderUnabbreviatedType = false hintsClassifierNamePolicy = ImportAwareClassifierNamePolicy(bindingContext, context) } } internal class ImportAwareClassifierNamePolicy( val bindingContext: BindingContext, val context: KtElement ): HintsClassifierNamePolicy { override fun renderClassifier(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String { if (classifier.containingDeclaration is ClassDescriptor) { val resolutionFacade = context.getResolutionFacade() val scope = context.getResolutionScope(bindingContext, resolutionFacade) if (scope.findClassifier(classifier.name, NoLookupLocation.FROM_IDE) == classifier) { return classifier.name.asString() } } return shortNameWithCompanionNameSkip(classifier, renderer) } private fun shortNameWithCompanionNameSkip(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String { if (classifier is TypeParameterDescriptor) return renderer.renderName(classifier.name) val qualifiedNameParts = classifier.parentsWithSelf .takeWhile { it is ClassifierDescriptor } .filter { !(it.isCompanionObject() && it.name == SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT) } .mapTo(ArrayList()) { it.name } .reversed() return renderFqName(qualifiedNameParts) } } }
apache-2.0
4051b278648355a838d80e0749e263ac
38.334171
158
0.646544
5.230204
false
false
false
false
idea4bsd/idea4bsd
platform/script-debugger/backend/src/ScriptManagerBase.kt
16
1796
/* * 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.debugger import com.intellij.util.Url import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.PromiseManager import org.jetbrains.concurrency.rejectedPromise abstract class ScriptManagerBase<SCRIPT : ScriptBase> : ScriptManager { @Suppress("UNCHECKED_CAST") @SuppressWarnings("unchecked") private val scriptSourceLoader = object : PromiseManager<ScriptBase, String>(ScriptBase::class.java) { override fun load(script: ScriptBase) = loadScriptSource(script as SCRIPT) } protected abstract fun loadScriptSource(script: SCRIPT): Promise<String> override fun getSource(script: Script): Promise<String> { if (!containsScript(script)) { return rejectedPromise("No Script") } @Suppress("UNCHECKED_CAST") return scriptSourceLoader.get(script as SCRIPT) } override fun hasSource(script: Script): Boolean { @Suppress("UNCHECKED_CAST") return scriptSourceLoader.has(script as SCRIPT) } fun setSource(script: SCRIPT, source: String?) { scriptSourceLoader.set(script, source) } } val Url.isSpecial: Boolean get() = !isInLocalFileSystem && (scheme == null || scheme == VM_SCHEME || authority == null)
apache-2.0
ca6121a12f15588380f62737f207f79f
34.235294
104
0.744989
4.235849
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/nanovg/src/templates/kotlin/nanovg/BNDTypes.kt
4
2805
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package nanovg import org.lwjgl.generator.* val BNDcornerFlags = "BNDcornerFlags".enumType val BNDicon = "BNDicon".enumType val BNDtextAlignment = "BNDtextAlignment".enumType val BNDwidgetState = "BNDwidgetState".enumType val BNDwidgetTheme = struct(Module.NANOVG, "BNDwidgetTheme") { documentation = """ Describes the theme used to draw a single widget or widget box; these values correspond to the same values that can be retrieved from the Theme panel in the Blender preferences. """ NVGcolor("outlineColor", "color of widget box outline") NVGcolor("itemColor", "color of widget item (meaning changes depending on class)") NVGcolor("innerColor", "fill color of widget box") NVGcolor("innerSelectedColor", "fill color of widget box when active") NVGcolor("textColor", "color of text label") NVGcolor("textSelectedColor", "color of text label when active") int("shadeTop", "delta modifier for upper part of gradient (-100 to 100)") int("shadeDown", "delta modifier for lower part of gradient (-100 to 100)") } val BNDnodeTheme = struct(Module.NANOVG, "BNDnodeTheme") { documentation = "Describes the theme used to draw nodes." NVGcolor("nodeSelectedColor", "inner color of selected node (and downarrow)") NVGcolor("wiresColor", "outline of wires") NVGcolor("textSelectedColor", "color of text label when active") NVGcolor("activeNodeColor", "inner color of active node (and dragged wire)") NVGcolor("wireSelectColor", "color of selected wire") NVGcolor("nodeBackdropColor", "color of background of node") int("noodleCurving", "how much a noodle curves (0 to 10)") } val BNDtheme = struct(Module.NANOVG, "BNDtheme") { documentation = "Describes the theme used to draw widgets." NVGcolor("backgroundColor", "the background color of panels and windows") BNDwidgetTheme("regularTheme", "theme for labels") BNDwidgetTheme("toolTheme", "theme for tool buttons") BNDwidgetTheme("radioTheme", "theme for radio buttons") BNDwidgetTheme("textFieldTheme", "theme for text fields") BNDwidgetTheme("optionTheme", "theme for option buttons (checkboxes)") BNDwidgetTheme("choiceTheme", "theme for choice buttons (comboboxes) Blender calls them \"menu buttons\"") BNDwidgetTheme("numberFieldTheme", "theme for number fields") BNDwidgetTheme("sliderTheme", "theme for slider controls") BNDwidgetTheme("scrollBarTheme", "theme for scrollbars") BNDwidgetTheme("tooltipTheme", "theme for tooltips") BNDwidgetTheme("menuTheme", "theme for menu backgrounds") BNDwidgetTheme("menuItemTheme", "theme for menu items") BNDnodeTheme("nodeTheme", "theme for nodes") }
bsd-3-clause
0328fdbceaf90d5f58c544d1904e4bbd
45.75
157
0.725847
3.928571
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateToStringActionTest.kt
4
1632
// 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.codeInsight.generate import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.Presentation import org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateToStringAction import org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateToStringAction.Generator import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils abstract class AbstractGenerateToStringActionTest : AbstractCodeInsightActionTest() { override fun createAction(fileText: String) = KotlinGenerateToStringAction() override fun testAction(action: AnAction, forced: Boolean): Presentation { val fileText = file.text val generator = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// GENERATOR: ")?.let { Generator.valueOf(it) } val generateSuperCall = InTextDirectivesUtils.isDirectiveDefined(fileText, "// GENERATE_SUPER_CALL") val klass = file.findElementAt(editor.caretModel.offset)?.getStrictParentOfType<KtClass>() try { with(KotlinGenerateToStringAction) { klass?.adjuster = { it.copy(generateSuperCall = generateSuperCall, generator = generator ?: it.generator) } } return super.testAction(action, forced) } finally { with(KotlinGenerateToStringAction) { klass?.adjuster = null } } } }
apache-2.0
e974fcc4f371591ffab4973b4fc32247
53.4
158
0.756127
4.871642
false
true
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SplitIfIntention.kt
3
5097
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.psi.psiUtil.startOffset class SplitIfIntention : SelfTargetingIntention<KtExpression>(KtExpression::class.java, KotlinBundle.lazyMessage("split.if.into.two")) { override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean { return when (element) { is KtOperationReferenceExpression -> isOperatorValid(element) is KtIfExpression -> getFirstValidOperator(element) != null && element.ifKeyword.textRange.containsOffset(caretOffset) else -> false } } override fun applyTo(element: KtExpression, editor: Editor?) { val operator = when (element) { is KtIfExpression -> getFirstValidOperator(element)!! else -> element as KtOperationReferenceExpression } val ifExpression = operator.getNonStrictParentOfType<KtIfExpression>() val commentSaver = CommentSaver(ifExpression!!) val expression = operator.parent as KtBinaryExpression val rightExpression = KtPsiUtil.safeDeparenthesize(getRight(expression, ifExpression.condition!!, commentSaver)) val leftExpression = KtPsiUtil.safeDeparenthesize(expression.left!!) val thenBranch = ifExpression.then!! val elseBranch = ifExpression.`else` val psiFactory = KtPsiFactory(element) val innerIf = psiFactory.createIf(rightExpression, thenBranch, elseBranch) val newIf = when (operator.getReferencedNameElementType()) { KtTokens.ANDAND -> psiFactory.createIf(leftExpression, psiFactory.createSingleStatementBlock(innerIf), elseBranch) KtTokens.OROR -> { val container = ifExpression.parent // special case if (container is KtBlockExpression && elseBranch == null && thenBranch.lastBlockStatementOrThis().isExitStatement()) { val secondIf = container.addAfter(innerIf, ifExpression) container.addAfter(psiFactory.createNewLine(), ifExpression) val firstIf = ifExpression.replace(psiFactory.createIf(leftExpression, thenBranch)) commentSaver.restore(PsiChildRange(firstIf, secondIf)) return } else { psiFactory.createIf(leftExpression, thenBranch, innerIf) } } else -> throw IllegalArgumentException() } val result = ifExpression.replace(newIf) commentSaver.restore(result) } private fun getRight(element: KtBinaryExpression, condition: KtExpression, commentSaver: CommentSaver): KtExpression { //gets the textOffset of the right side of the JetBinaryExpression in context to condition val conditionRange = condition.textRange val startOffset = element.right!!.startOffset - conditionRange.startOffset val endOffset = conditionRange.length val rightString = condition.text.substring(startOffset, endOffset) val expression = KtPsiFactory(element).createExpression(rightString) commentSaver.elementCreatedByText(expression, condition, TextRange(startOffset, endOffset)) return expression } private fun getFirstValidOperator(element: KtIfExpression): KtOperationReferenceExpression? { val condition = element.condition ?: return null return PsiTreeUtil.findChildrenOfType(condition, KtOperationReferenceExpression::class.java) .firstOrNull { isOperatorValid(it) } } private fun isOperatorValid(element: KtOperationReferenceExpression): Boolean { val operator = element.getReferencedNameElementType() if (operator != KtTokens.ANDAND && operator != KtTokens.OROR) return false var expression = element.parent as? KtBinaryExpression ?: return false if (expression.right == null || expression.left == null) return false while (true) { expression = expression.parent as? KtBinaryExpression ?: break if (expression.operationToken != operator) return false } val ifExpression = expression.parent.parent as? KtIfExpression ?: return false if (ifExpression.condition == null) return false if (!PsiTreeUtil.isAncestor(ifExpression.condition, element, false)) return false if (ifExpression.then == null) return false return true } }
apache-2.0
2840ee57d910e45fae01cdd04846f950
44.508929
158
0.705121
5.613436
false
false
false
false
androidx/androidx
paging/paging-common/src/test/kotlin/androidx/paging/PagingSourceTest.kt
3
15137
/* * Copyright 2019 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.paging import androidx.paging.PagingSource.LoadParams import androidx.paging.PagingSource.LoadResult import androidx.paging.PagingSource.LoadResult.Page.Companion.COUNT_UNDEFINED import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import kotlin.test.assertFailsWith @RunWith(JUnit4::class) class PagingSourceTest { // ----- STANDARD ----- private suspend fun loadInitial( pagingSource: ItemDataSource, key: Key?, initialLoadSize: Int, enablePlaceholders: Boolean ): LoadResult<Key, Item> { return pagingSource.load( LoadParams.Refresh( key, initialLoadSize, enablePlaceholders, ) ) } @Test fun loadInitial() { runBlocking { val pagingSource = ItemDataSource() val key = ITEMS_BY_NAME_ID[49].key() val result = loadInitial(pagingSource, key, 10, true) as LoadResult.Page assertEquals(45, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.data) assertEquals(45, result.itemsAfter) val errorParams = LoadParams.Refresh(key, 10, false) // Verify error is propagated correctly. pagingSource.enqueueError() assertFailsWith<CustomException> { pagingSource.load(errorParams) } // Verify LoadResult.Invalid is returned pagingSource.invalidateLoad() assertTrue(pagingSource.load(errorParams) is LoadResult.Invalid) } } @Test fun loadInitial_keyMatchesSingleItem() = runBlocking { val pagingSource = ItemDataSource(items = ITEMS_BY_NAME_ID.subList(0, 1)) // this is tricky, since load after and load before with the passed key will fail val result = loadInitial(pagingSource, ITEMS_BY_NAME_ID[0].key(), 20, true) as LoadResult.Page assertEquals(0, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(0, 1), result.data) assertEquals(0, result.itemsAfter) } @Test fun loadInitial_keyMatchesLastItem() = runBlocking { val pagingSource = ItemDataSource() // tricky, because load after key is empty, so another load before and load after required val key = ITEMS_BY_NAME_ID.last().key() val result = loadInitial(pagingSource, key, 20, true) as LoadResult.Page assertEquals(90, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(90, 100), result.data) assertEquals(0, result.itemsAfter) } @Test fun loadInitial_nullKey() = runBlocking { val dataSource = ItemDataSource() val result = loadInitial(dataSource, null, 10, true) as LoadResult.Page assertEquals(0, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), result.data) assertEquals(90, result.itemsAfter) } @Test fun loadInitial_keyPastEndOfList() = runBlocking { val dataSource = ItemDataSource() // if key is past entire data set, should return last items in data set val key = Key("fz", 0) val result = loadInitial(dataSource, key, 10, true) as LoadResult.Page // NOTE: ideally we'd load 10 items here, but it adds complexity and unpredictability to // do: load after was empty, so pass full size to load before, since this can incur larger // loads than requested (see keyMatchesLastItem test) assertEquals(95, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(95, 100), result.data) assertEquals(0, result.itemsAfter) } // ----- UNCOUNTED ----- @Test fun loadInitial_disablePlaceholders() = runBlocking { val dataSource = ItemDataSource() // dispatchLoadInitial(key, count) == null padding, loadAfter(key, count), null padding val key = ITEMS_BY_NAME_ID[49].key() val result = loadInitial(dataSource, key, 10, false) as LoadResult.Page assertEquals(COUNT_UNDEFINED, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.data) assertEquals(COUNT_UNDEFINED, result.itemsAfter) } @Test fun loadInitial_uncounted() = runBlocking { val dataSource = ItemDataSource(counted = false) // dispatchLoadInitial(key, count) == null padding, loadAfter(key, count), null padding val key = ITEMS_BY_NAME_ID[49].key() val result = loadInitial(dataSource, key, 10, true) as LoadResult.Page assertEquals(COUNT_UNDEFINED, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.data) assertEquals(COUNT_UNDEFINED, result.itemsAfter) } @Test fun loadInitial_nullKey_uncounted() = runBlocking { val dataSource = ItemDataSource(counted = false) val result = loadInitial(dataSource, null, 10, true) as LoadResult.Page assertEquals(COUNT_UNDEFINED, result.itemsBefore) assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), result.data) assertEquals(COUNT_UNDEFINED, result.itemsAfter) } // ----- EMPTY ----- @Test fun loadInitial_empty() = runBlocking { val dataSource = ItemDataSource(items = ArrayList()) // dispatchLoadInitial(key, count) == null padding, loadAfter(key, count), null padding val key = ITEMS_BY_NAME_ID[49].key() val result = loadInitial(dataSource, key, 10, true) as LoadResult.Page assertEquals(0, result.itemsBefore) assertTrue(result.data.isEmpty()) assertEquals(0, result.itemsAfter) } @Test fun loadInitial_nullKey_empty() = runBlocking { val dataSource = ItemDataSource(items = ArrayList()) val result = loadInitial(dataSource, null, 10, true) as LoadResult.Page assertEquals(0, result.itemsBefore) assertTrue(result.data.isEmpty()) assertEquals(0, result.itemsAfter) } // ----- Other behavior ----- @Test fun loadBefore() { val dataSource = ItemDataSource() runBlocking { val key = ITEMS_BY_NAME_ID[5].key() val params = LoadParams.Prepend(key, 5, false) val observed = (dataSource.load(params) as LoadResult.Page).data assertEquals(ITEMS_BY_NAME_ID.subList(0, 5), observed) val errorParams = LoadParams.Prepend(key, 5, false) // Verify error is propagated correctly. dataSource.enqueueError() assertFailsWith<CustomException> { dataSource.load(errorParams) } // Verify LoadResult.Invalid is returned dataSource.invalidateLoad() assertTrue(dataSource.load(errorParams) is LoadResult.Invalid) } } @Test fun loadAfter() { val dataSource = ItemDataSource() runBlocking { val key = ITEMS_BY_NAME_ID[5].key() val params = LoadParams.Append(key, 5, false) val observed = (dataSource.load(params) as LoadResult.Page).data assertEquals(ITEMS_BY_NAME_ID.subList(6, 11), observed) val errorParams = LoadParams.Append(key, 5, false) // Verify error is propagated correctly. dataSource.enqueueError() assertFailsWith<CustomException> { dataSource.load(errorParams) } // Verify LoadResult.Invalid is returned dataSource.invalidateLoad() assertTrue(dataSource.load(errorParams) is LoadResult.Invalid) } } @Test fun registerInvalidatedCallback_triggersImmediatelyIfAlreadyInvalid() { val pagingSource = TestPagingSource() var invalidateCalls = 0 pagingSource.invalidate() pagingSource.registerInvalidatedCallback { invalidateCalls++ } assertThat(invalidateCalls).isEqualTo(1) } @Test fun registerInvalidatedCallback_avoidsRetriggeringWhenCalledRecursively() { val pagingSource = TestPagingSource() var invalidateCalls = 0 pagingSource.registerInvalidatedCallback { pagingSource.registerInvalidatedCallback { invalidateCalls++ } pagingSource.invalidate() pagingSource.registerInvalidatedCallback { invalidateCalls++ } invalidateCalls++ } pagingSource.invalidate() assertThat(invalidateCalls).isEqualTo(3) } @Test fun page_iterator() { val dataSource = ItemDataSource() runBlocking { val pages = mutableListOf<LoadResult.Page<Key, Item>>() // first page val key = ITEMS_BY_NAME_ID[5].key() val params = LoadParams.Append(key, 5, false) val page = dataSource.load(params) as LoadResult.Page pages.add(page) val iterator = page.iterator() var startIndex = 6 val endIndex = 11 // iterate normally while (iterator.hasNext() && startIndex < endIndex) { val item = iterator.next() assertThat(item).isEqualTo(ITEMS_BY_NAME_ID[startIndex++]) } // second page val params2 = LoadParams.Append( ITEMS_BY_NAME_ID[10].key(), 5, false ) val page2 = dataSource.load(params2) as LoadResult.Page pages.add(page2) // iterate through list of pages assertThat(pages.flatten()).containsExactlyElementsIn( ITEMS_BY_NAME_ID.subList(6, 16) ).inOrder() } } data class Key(val name: String, val id: Int) data class Item( val name: String, val id: Int, val balance: Double, val address: String ) fun Item.key() = Key(name, id) internal class ItemDataSource( private val counted: Boolean = true, private val items: List<Item> = ITEMS_BY_NAME_ID ) : PagingSource<Key, Item>() { fun Item.key() = Key(name, id) private fun List<Item>.asPage( itemsBefore: Int = COUNT_UNDEFINED, itemsAfter: Int = COUNT_UNDEFINED ): LoadResult.Page<Key, Item> = LoadResult.Page( data = this, prevKey = firstOrNull()?.key(), nextKey = lastOrNull()?.key(), itemsBefore = itemsBefore, itemsAfter = itemsAfter ) private var error = false private var invalidLoadResult = false override fun getRefreshKey(state: PagingState<Key, Item>): Key? { return state.anchorPosition ?.let { anchorPosition -> state.closestItemToPosition(anchorPosition) } ?.let { item -> Key(item.name, item.id) } } override suspend fun load(params: LoadParams<Key>): LoadResult<Key, Item> { return when (params) { is LoadParams.Refresh -> loadInitial(params) is LoadParams.Prepend -> loadBefore(params) is LoadParams.Append -> loadAfter(params) } } private fun loadInitial(params: LoadParams<Key>): LoadResult<Key, Item> { if (error) { error = false throw EXCEPTION } else if (invalidLoadResult) { invalidLoadResult = false return LoadResult.Invalid() } val key = params.key ?: Key("", Int.MAX_VALUE) val start = maxOf(0, findFirstIndexAfter(key) - params.loadSize / 2) val endExclusive = minOf(start + params.loadSize, items.size) return if (params.placeholdersEnabled && counted) { val data = items.subList(start, endExclusive) data.asPage(start, items.size - data.size - start) } else { items.subList(start, endExclusive).asPage() } } private fun loadAfter(params: LoadParams<Key>): LoadResult<Key, Item> { if (error) { error = false throw EXCEPTION } else if (invalidLoadResult) { invalidLoadResult = false return LoadResult.Invalid() } val start = findFirstIndexAfter(params.key!!) val endExclusive = minOf(start + params.loadSize, items.size) return items.subList(start, endExclusive).asPage() } private fun loadBefore(params: LoadParams<Key>): LoadResult<Key, Item> { if (error) { error = false throw EXCEPTION } else if (invalidLoadResult) { invalidLoadResult = false return LoadResult.Invalid() } val firstIndexBefore = findFirstIndexBefore(params.key!!) val endExclusive = maxOf(0, firstIndexBefore + 1) val start = maxOf(0, firstIndexBefore - params.loadSize + 1) return items.subList(start, endExclusive).asPage() } private fun findFirstIndexAfter(key: Key): Int { return items.indices.firstOrNull { KEY_COMPARATOR.compare(key, items[it].key()) < 0 } ?: items.size } private fun findFirstIndexBefore(key: Key): Int { return items.indices.reversed().firstOrNull { KEY_COMPARATOR.compare(key, items[it].key()) > 0 } ?: -1 } fun enqueueError() { error = true } fun invalidateLoad() { invalidLoadResult = true } } class CustomException : Exception() companion object { private val ITEM_COMPARATOR = compareBy<Item> { it.name }.thenByDescending { it.id } private val KEY_COMPARATOR = compareBy<Key> { it.name }.thenByDescending { it.id } private val ITEMS_BY_NAME_ID = List(100) { val names = Array(10) { index -> "f" + ('a' + index) } Item( names[it % 10], it, Math.random() * 1000, (Math.random() * 200).toInt().toString() + " fake st." ) }.sortedWith(ITEM_COMPARATOR) private val EXCEPTION = CustomException() } }
apache-2.0
a2ef2fdc6bb595e904b53ced42ff5046
33.71789
98
0.606527
4.728835
false
false
false
false
androidx/androidx
health/connect/connect-client/src/test/java/androidx/health/platform/client/response/ReadDataRangeResponseTest.kt
3
4830
/* * 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.platform.client.response import android.os.Parcel import androidx.health.platform.client.proto.DataProto import androidx.health.platform.client.proto.ResponseProto import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ReadDataRangeResponseTest { @Test fun writeEmptyToParcel() { val readDataRangeResponse = ReadDataRangeResponse(ResponseProto.ReadDataRangeResponse.getDefaultInstance()) val parcel: Parcel = Parcel.obtain() parcel.writeParcelable(readDataRangeResponse, 0) parcel.setDataPosition(0) @Suppress("Deprecation") // readParcelable deprecated in T and introduced new methods val out: ReadDataRangeResponse? = parcel.readParcelable(ReadDataRangeResponse::class.java.classLoader) Truth.assertThat(out?.proto).isEqualTo(readDataRangeResponse.proto) } @Test fun writeToParcel() { val readDataRangeResponse = ReadDataRangeResponse( ResponseProto.ReadDataRangeResponse.newBuilder() .addAllDataPoint( listOf( DataProto.DataPoint.newBuilder() .setStartTimeMillis(1234L) .addSeriesValues( DataProto.SeriesValue.newBuilder() .setInstantTimeMillis(1247L) .putValues( "bpm", DataProto.Value.newBuilder().setLongVal(120).build() ) .build() ) .addSeriesValues( DataProto.SeriesValue.newBuilder() .setInstantTimeMillis(1247L) .putValues( "bpm", DataProto.Value.newBuilder().setLongVal(140).build() ) .build() ) .build(), DataProto.DataPoint.newBuilder() .setStartTimeMillis(2345L) .addSeriesValues( DataProto.SeriesValue.newBuilder() .setInstantTimeMillis(2346L) .putValues( "bpm", DataProto.Value.newBuilder().setLongVal(130).build() ) .build() ) .addSeriesValues( DataProto.SeriesValue.newBuilder() .setInstantTimeMillis(2347L) .putValues( "bpm", DataProto.Value.newBuilder().setLongVal(150).build() ) .build() ) .build() ) ) .setPageToken("somePageToken") .build() ) val parcel: Parcel = Parcel.obtain() parcel.writeParcelable(readDataRangeResponse, 0) parcel.setDataPosition(0) @Suppress("Deprecation") // readParcelable deprecated in T and introduced new methods val out: ReadDataRangeResponse? = parcel.readParcelable(ReadDataRangeResponse::class.java.classLoader) Truth.assertThat(out?.proto).isEqualTo(readDataRangeResponse.proto) } }
apache-2.0
84702bd9359d4154ceeb2c560a2e69c5
45
96
0.480745
6.305483
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/run/PythonScripts.kt
1
11923
// 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. @file:JvmName("PythonScripts") package com.jetbrains.python.run import com.intellij.execution.ExecutionException import com.intellij.execution.Platform import com.intellij.execution.configurations.ParametersList import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.LocalPtyOptions import com.intellij.execution.process.ProcessOutput import com.intellij.execution.target.* import com.intellij.execution.target.TargetEnvironment.TargetPath import com.intellij.execution.target.TargetEnvironment.UploadRoot import com.intellij.execution.target.local.LocalTargetPtyOptions import com.intellij.execution.target.value.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.isAncestor import com.jetbrains.python.HelperPackage import com.jetbrains.python.PythonHelpersLocator import com.jetbrains.python.debugger.PyDebugRunner import com.jetbrains.python.packaging.PyExecutionException import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest import com.jetbrains.python.sdk.PythonEnvUtil import com.jetbrains.python.sdk.PythonSdkType import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import com.jetbrains.python.sdk.configureBuilderToRunPythonOnTarget import com.jetbrains.python.sdk.targetAdditionalData import com.jetbrains.python.target.PyTargetAwareAdditionalData.Companion.pathsAddedByUser import java.nio.file.Path private val LOG = Logger.getInstance("#com.jetbrains.python.run.PythonScripts") @JvmOverloads fun PythonExecution.buildTargetedCommandLine(targetEnvironment: TargetEnvironment, sdk: Sdk, interpreterParameters: List<String>, isUsePty: Boolean = false): TargetedCommandLine { val commandLineBuilder = TargetedCommandLineBuilder(targetEnvironment.request) commandLineBuilder.addEnvironmentVariable(PythonEnvUtil.PYTHONIOENCODING, charset.name()) workingDir?.apply(targetEnvironment)?.let { commandLineBuilder.setWorkingDirectory(it) } commandLineBuilder.charset = charset inputFile?.let { commandLineBuilder.setInputFile(TargetValue.fixed(it.absolutePath)) } sdk.configureBuilderToRunPythonOnTarget(commandLineBuilder) commandLineBuilder.addParameters(interpreterParameters) when (this) { is PythonScriptExecution -> pythonScriptPath?.let { commandLineBuilder.addParameter(it.apply(targetEnvironment)) } ?: throw IllegalArgumentException("Python script path must be set") is PythonModuleExecution -> moduleName?.let { commandLineBuilder.addParameters(listOf("-m", it)) } ?: throw IllegalArgumentException("Python module name must be set") } for (parameter in parameters) { commandLineBuilder.addParameter(parameter.apply(targetEnvironment)) } sdk.targetAdditionalData?.pathsAddedByUser?.map { it.value }?.forEach { path -> appendToPythonPath(constant(path), targetEnvironment.targetPlatform) } for ((name, value) in envs) { commandLineBuilder.addEnvironmentVariable(name, value.apply(targetEnvironment)) } val environmentVariablesForVirtualenv = mutableMapOf<String, String>() // TODO [Targets API] It would be cool to activate environment variables for any type of target PythonSdkType.patchEnvironmentVariablesForVirtualenv(environmentVariablesForVirtualenv, sdk) // TODO [Targets API] [major] PATH env for virtualenv should extend existing PATH env environmentVariablesForVirtualenv.forEach { (name, value) -> commandLineBuilder.addEnvironmentVariable(name, value) } // TODO [Targets API] [major] `PythonSdkFlavor` should be taken into account to pass (at least) "IRONPYTHONPATH" or "JYTHONPATH" // environment variables for corresponding interpreters if (isUsePty) { commandLineBuilder.ptyOptions = LocalTargetPtyOptions(LocalPtyOptions.DEFAULT) } return commandLineBuilder.build() } data class Upload(val localPath: String, val targetPath: TargetEnvironmentFunction<String>) private fun resolveUploadPath(localPath: String, uploads: Iterable<Upload>): TargetEnvironmentFunction<String> { val localFileSeparator = Platform.current().fileSeparator val matchUploads = uploads.mapNotNull { upload -> if (FileUtil.isAncestor(upload.localPath, localPath, false)) { FileUtil.getRelativePath(upload.localPath, localPath, localFileSeparator)?.let { upload to it } } else { null } } if (matchUploads.size > 1) { LOG.warn("Several uploads matches the local path '$localPath': $matchUploads") } val (upload, localRelativePath) = matchUploads.firstOrNull() ?: throw IllegalStateException("Failed to find uploads for the local path '$localPath'") return upload.targetPath.getRelativeTargetPath(localRelativePath) } fun prepareHelperScriptExecution(helperPackage: HelperPackage, helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): PythonScriptExecution = PythonScriptExecution().apply { val uploads = applyHelperPackageToPythonPath(helperPackage, helpersAwareTargetRequest) pythonScriptPath = resolveUploadPath(helperPackage.asParamString(), uploads) } private const val PYTHONPATH_ENV = "PYTHONPATH" /** * Requests the upload of PyCharm helpers root directory to the target. */ fun PythonExecution.applyHelperPackageToPythonPath(helperPackage: HelperPackage, helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): Iterable<Upload> { return applyHelperPackageToPythonPath(helperPackage.pythonPathEntries, helpersAwareTargetRequest) } fun PythonExecution.applyHelperPackageToPythonPath(pythonPathEntries: List<String>, helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): Iterable<Upload> { val localHelpersRootPath = PythonHelpersLocator.getHelpersRoot().absolutePath val targetPlatform = helpersAwareTargetRequest.targetEnvironmentRequest.targetPlatform val targetUploadPath = helpersAwareTargetRequest.preparePyCharmHelpers() val targetPathSeparator = targetPlatform.platform.pathSeparator val uploads = pythonPathEntries.map { // TODO [Targets API] Simplify the paths resolution val relativePath = FileUtil.getRelativePath(localHelpersRootPath, it, Platform.current().fileSeparator) ?: throw IllegalStateException("Helpers PYTHONPATH entry '$it' cannot be resolved" + " against the root path of PyCharm helpers '$localHelpersRootPath'") Upload(it, targetUploadPath.getRelativeTargetPath(relativePath)) } val pythonPathEntriesOnTarget = uploads.map { it.targetPath } val pythonPathValue = pythonPathEntriesOnTarget.joinToStringFunction(separator = targetPathSeparator.toString()) appendToPythonPath(pythonPathValue, targetPlatform) return uploads } /** * Suits for coverage and profiler scripts. */ fun PythonExecution.addPythonScriptAsParameter(targetScript: PythonExecution) { when (targetScript) { is PythonScriptExecution -> targetScript.pythonScriptPath?.let { pythonScriptPath -> addParameter(pythonScriptPath) } ?: throw IllegalArgumentException("Python script path must be set") is PythonModuleExecution -> targetScript.moduleName?.let { moduleName -> addParameters("-m", moduleName) } ?: throw IllegalArgumentException("Python module name must be set") } } fun PythonExecution.addParametersString(parametersString: String) { ParametersList.parse(parametersString).forEach { parameter -> addParameter(parameter) } } private fun PythonExecution.appendToPythonPath(value: TargetEnvironmentFunction<String>, targetPlatform: TargetPlatform) { appendToPythonPath(envs, value, targetPlatform) } fun appendToPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>, value: TargetEnvironmentFunction<String>, targetPlatform: TargetPlatform) { envs.merge(PYTHONPATH_ENV, value) { whole, suffix -> listOf(whole, suffix).joinToPathValue(targetPlatform) } } fun appendToPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>, paths: Collection<TargetEnvironmentFunction<String>>, targetPlatform: TargetPlatform) { val value = paths.joinToPathValue(targetPlatform) envs.merge(PYTHONPATH_ENV, value) { whole, suffix -> listOf(whole, suffix).joinToPathValue(targetPlatform) } } /** * Joins the provided paths collection to single [TargetValue] using target * platform's path separator. * * The result is applicable for `PYTHONPATH` and `PATH` environment variables. */ fun Collection<TargetEnvironmentFunction<String>>.joinToPathValue(targetPlatform: TargetPlatform): TargetEnvironmentFunction<String> = this.joinToStringFunction(separator = targetPlatform.platform.pathSeparator.toString()) // TODO: Make this code python-agnostic, get red of path hardcode fun PythonExecution.extendEnvs(additionalEnvs: Map<String, TargetEnvironmentFunction<String>>, targetPlatform: TargetPlatform) { for ((key, value) in additionalEnvs) { if (key == PYTHONPATH_ENV) { appendToPythonPath(value, targetPlatform) } else { addEnvironmentVariable(key, value) } } } /** * Execute this command in a given environment, throwing an `ExecutionException` in case of a timeout or a non-zero exit code. */ @Throws(ExecutionException::class) fun TargetedCommandLine.execute(env: TargetEnvironment, indicator: ProgressIndicator): ProcessOutput { val process = env.createProcess(this, indicator) val capturingHandler = CapturingProcessHandler(process, charset, getCommandPresentation(env)) val output = capturingHandler.runProcess() if (output.isTimeout || output.exitCode != 0) { val fullCommand = collectCommandsSynchronously() throw PyExecutionException("", fullCommand[0], fullCommand.drop(1), output) } return output } /** * Checks whether the base directory of [project] is registered in [this] request. Adds it if it is not. * You can also provide [modules] to add its content roots and [Sdk] for which user added custom paths */ fun TargetEnvironmentRequest.ensureProjectSdkAndModuleDirsAreOnTarget(project: Project, vararg modules: Module) { fun TargetEnvironmentRequest.addPathToVolume(basePath: Path) { if (uploadVolumes.none { it.localRootPath.isAncestor(basePath) }) { uploadVolumes += UploadRoot(localRootPath = basePath, targetRootPath = TargetPath.Temporary()) } } for (module in modules) { ModuleRootManager.getInstance(module).contentRoots.forEach { try { addPathToVolume(it.toNioPath()) } catch (_: UnsupportedOperationException) { // VirtualFile.toNioPath throws UOE if VirtualFile has no associated path which is common case for JupyterRemoteVirtualFile } } } project.basePath?.let { addPathToVolume(Path.of(it)) } } /** * Mimics [PyDebugRunner.disableBuiltinBreakpoint] for [PythonExecution]. */ fun PythonExecution.disableBuiltinBreakpoint(sdk: Sdk?) { if (sdk != null && PythonSdkFlavor.getFlavor(sdk)?.getLanguageLevel(sdk)?.isAtLeast(LanguageLevel.PYTHON37) == true) { addEnvironmentVariable("PYTHONBREAKPOINT", "0") } }
apache-2.0
dcb41f7365363f78ce002cd107c646e9
47.868852
140
0.759037
4.922791
false
false
false
false
GunoH/intellij-community
xml/impl/src/com/intellij/html/webSymbols/attributes/impl/HtmlAttributeEnumConstValueSymbol.kt
2
1233
// 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.html.webSymbols.attributes.impl import com.intellij.model.Pointer import com.intellij.psi.PsiElement import com.intellij.psi.SmartPointerManager import com.intellij.webSymbols.* internal class HtmlAttributeEnumConstValueSymbol(override val origin: WebSymbolOrigin, override val matchedName: String, override val source: PsiElement?) : PsiSourcedWebSymbol { override val kind: SymbolKind get() = WebSymbol.KIND_HTML_ATTRIBUTE_VALUES override fun createPointer(): Pointer<HtmlAttributeEnumConstValueSymbol> { val origin = this.origin val matchedName = this.matchedName val source = this.source?.let { SmartPointerManager.createPointer(it) } return Pointer<HtmlAttributeEnumConstValueSymbol> { val newSource = source?.dereference() if (newSource == null && source != null) return@Pointer null HtmlAttributeEnumConstValueSymbol(origin, matchedName, newSource) } } override val namespace: SymbolNamespace get() = WebSymbol.NAMESPACE_HTML }
apache-2.0
4a375653442b3442dc4548b28ff85404
41.551724
120
0.713706
4.77907
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToLabeledReturnFix.kt
3
4610
// 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 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.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findLabelAndCall import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class ChangeToLabeledReturnFix( element: KtReturnExpression, val labeledReturn: String ) : KotlinQuickFixAction<KtReturnExpression>(element) { override fun getFamilyName() = KotlinBundle.message("fix.change.to.labeled.return.family") override fun getText() = KotlinBundle.message("fix.change.to.labeled.return.text", labeledReturn) override fun invoke(project: Project, editor: Editor?, file: KtFile) { val returnExpression = element ?: return val factory = KtPsiFactory(project) val returnedExpression = returnExpression.returnedExpression val newExpression = if (returnedExpression == null) factory.createExpression(labeledReturn) else factory.createExpressionByPattern("$0 $1", labeledReturn, returnedExpression) returnExpression.replace(newExpression) } companion object : KotlinIntentionActionsFactory() { private fun findAccessibleLabels(bindingContext: BindingContext, position: KtReturnExpression): List<Name> { val result = mutableListOf<Name>() for (parent in position.parentsWithSelf) { when (parent) { is KtClassOrObject -> break is KtFunctionLiteral -> { val (label, call) = parent.findLabelAndCall() if (label != null) { result.add(label) } // check if the current function literal is inlined and stop processing outer declarations if it's not val callee = call?.calleeExpression as? KtReferenceExpression ?: break if (!InlineUtil.isInline(bindingContext[BindingContext.REFERENCE_TARGET, callee])) break } else -> {} } } return result } override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val element = diagnostic.psiElement as? KtElement ?: return emptyList() val context by lazy { element.analyze() } val returnExpression = when (diagnostic.factory) { Errors.RETURN_NOT_ALLOWED -> diagnostic.psiElement as? KtReturnExpression Errors.TYPE_MISMATCH, Errors.TYPE_MISMATCH_WARNING, Errors.CONSTANT_EXPECTED_TYPE_MISMATCH, Errors.NULL_FOR_NONNULL_TYPE -> getLambdaReturnExpression(diagnostic.psiElement, context) else -> null } ?: return emptyList() val candidates = findAccessibleLabels(context, returnExpression) return candidates.map { ChangeToLabeledReturnFix(returnExpression, labeledReturn = "return@${it.render()}") } } private fun getLambdaReturnExpression(element: PsiElement, bindingContext: BindingContext): KtReturnExpression? { val returnExpression = element.getStrictParentOfType<KtReturnExpression>() ?: return null val lambda = returnExpression.getStrictParentOfType<KtLambdaExpression>() ?: return null val lambdaReturnType = bindingContext[BindingContext.FUNCTION, lambda.functionLiteral]?.returnType ?: return null val returnType = returnExpression.returnedExpression?.getType(bindingContext) ?: return null if (!returnType.isSubtypeOf(lambdaReturnType)) return null return returnExpression } } }
apache-2.0
e93645362bcf247de7bfc9ad193c97ff
49.119565
158
0.68308
5.488095
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/createClassUtils.kt
1
8147
// 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.createClass import com.intellij.codeInsight.daemon.quickFix.CreateClassOrPackageFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.quickfix.DelegatingIntentionAction import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.guessTypes import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.noSubstitutions import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.Qualifier import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.descriptors.ClassKind as ClassDescriptorKind internal fun String.checkClassName(): Boolean = isNotEmpty() && Character.isUpperCase(first()) private fun String.checkPackageName(): Boolean = isNotEmpty() && Character.isLowerCase(first()) internal fun getTargetParentsByQualifier( element: KtElement, isQualified: Boolean, qualifierDescriptor: DeclarationDescriptor? ): List<PsiElement> { val file = element.containingKtFile val project = file.project val targetParents: List<PsiElement> = when { !isQualified -> element.parents.filterIsInstance<KtClassOrObject>().toList() + file qualifierDescriptor is ClassDescriptor -> listOfNotNull(DescriptorToSourceUtilsIde.getAnyDeclaration(project, qualifierDescriptor)) qualifierDescriptor is PackageViewDescriptor -> if (qualifierDescriptor.fqName != file.packageFqName) { listOfNotNull(JavaPsiFacade.getInstance(project).findPackage(qualifierDescriptor.fqName.asString())) } else listOf(file) else -> emptyList() } return targetParents.filter { it.canRefactor() } } internal fun getTargetParentsByCall(call: Call, context: BindingContext): List<PsiElement> { val callElement = call.callElement val receiver = call.explicitReceiver return when (receiver) { null -> getTargetParentsByQualifier(callElement, false, null) is Qualifier -> getTargetParentsByQualifier( callElement, true, context[BindingContext.REFERENCE_TARGET, receiver.referenceExpression] ) is ReceiverValue -> getTargetParentsByQualifier(callElement, true, receiver.type.constructor.declarationDescriptor) else -> throw AssertionError("Unexpected receiver: $receiver") } } internal fun isInnerClassExpected(call: Call) = call.explicitReceiver is ReceiverValue internal fun KtExpression.guessTypeForClass(context: BindingContext, moduleDescriptor: ModuleDescriptor) = guessTypes(context, moduleDescriptor, coerceUnusedToUnit = false).singleOrNull() internal fun KotlinType.toClassTypeInfo(): TypeInfo { return TypeInfo.ByType(this, Variance.OUT_VARIANCE).noSubstitutions() } internal fun getClassKindFilter(expectedType: KotlinType, containingDeclaration: PsiElement): (ClassKind) -> Boolean { if (expectedType.isAnyOrNullableAny()) { return { _ -> true } } val descriptor = expectedType.constructor.declarationDescriptor ?: return { _ -> false } val canHaveSubtypes = !(expectedType.constructor.isFinal || expectedType.containsStarProjections()) || expectedType.isUnit() val isEnum = DescriptorUtils.isEnumClass(descriptor) if (!(canHaveSubtypes || isEnum) || descriptor is TypeParameterDescriptor ) return { _ -> false } return { classKind -> when (classKind) { ClassKind.ENUM_ENTRY -> isEnum && containingDeclaration == DescriptorToSourceUtils.descriptorToDeclaration(descriptor) ClassKind.INTERFACE -> containingDeclaration !is PsiClass || (descriptor as? ClassDescriptor)?.kind == ClassDescriptorKind.INTERFACE else -> canHaveSubtypes } } } internal fun KtSimpleNameExpression.getCreatePackageFixIfApplicable(targetParent: PsiElement): IntentionAction? { val name = getReferencedName() if (!name.checkPackageName()) return null val basePackage: PsiPackage = when (targetParent) { is KtFile -> JavaPsiFacade.getInstance(targetParent.project).findPackage(targetParent.packageFqName.asString()) is PsiPackage -> targetParent else -> null } ?: return null val baseName = basePackage.qualifiedName val fullName = if (baseName.isNotEmpty()) "$baseName.$name" else name val javaFix = CreateClassOrPackageFix.createFix(fullName, resolveScope, this, basePackage, null, null, null) ?: return null return object : DelegatingIntentionAction(javaFix) { override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family") override fun getText(): String = KotlinBundle.message("create.package.0", fullName) } } data class UnsubstitutedTypeConstraintInfo( val typeParameter: TypeParameterDescriptor, private val originalSubstitution: Map<TypeConstructor, TypeProjection>, val upperBound: KotlinType ) { fun performSubstitution(vararg substitution: Pair<TypeConstructor, TypeProjection>): TypeConstraintInfo? { val currentSubstitution = LinkedHashMap<TypeConstructor, TypeProjection>().apply { this.putAll(originalSubstitution) this.putAll(substitution) } val substitutedUpperBound = TypeSubstitutor.create(currentSubstitution).substitute(upperBound, Variance.INVARIANT) ?: return null return TypeConstraintInfo(typeParameter, substitutedUpperBound) } } data class TypeConstraintInfo( val typeParameter: TypeParameterDescriptor, val upperBound: KotlinType ) fun getUnsubstitutedTypeConstraintInfo(element: KtTypeElement): UnsubstitutedTypeConstraintInfo? { val context = element.analyze(BodyResolveMode.PARTIAL) val containingTypeArg = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null val argumentList = containingTypeArg.parent as? KtTypeArgumentList ?: return null val containingTypeRef = (argumentList.parent as? KtTypeElement)?.parent as? KtTypeReference ?: return null val containingType = containingTypeRef.getAbbreviatedTypeOrType(context) ?: return null val baseType = containingType.constructor.declarationDescriptor?.defaultType ?: return null val typeParameter = containingType.constructor.parameters.getOrNull(argumentList.arguments.indexOf(containingTypeArg)) val upperBound = typeParameter?.upperBounds?.singleOrNull() ?: return null val substitution = getTypeSubstitution(baseType, containingType) ?: return null return UnsubstitutedTypeConstraintInfo(typeParameter, substitution, upperBound) } fun getTypeConstraintInfo(element: KtTypeElement) = getUnsubstitutedTypeConstraintInfo(element)?.performSubstitution()
apache-2.0
4d0a78dcca2868a1bd11c448aa3311e5
47.784431
158
0.769608
5.331806
false
false
false
false
blazsolar/gradle-play-publisher
src/main/java/solar/blaz/gradle/play/PlayPlugin.kt
1
2896
package solar.blaz.gradle.play import com.android.build.gradle.AppExtension import com.android.build.gradle.api.ApplicationVariant import org.gradle.api.Plugin import org.gradle.api.Project import solar.blaz.gradle.play.BasePlayPlugin.ArtifactData import solar.blaz.gradle.play.extension.PublishArtifact import solar.blaz.gradle.play.tasks.UploadApkTask class PlayPlugin : Plugin<Project> { override fun apply(project: Project) { if (!isAndroidProject(project)) { throw IllegalStateException("Play Publish plugin only works with Android application projects but \"" + project.name + "\" is none") } val parent = project.parent val basePlugin: Any basePlugin = if (parent != null && parent.plugins.hasPlugin(BasePlayPlugin::class.java)) { parent.plugins.getPlugin(BasePlayPlugin::class.java) } else { project.plugins.apply(BasePlayPlugin::class.java) } project.afterEvaluate { createTasks(it, basePlugin) } } private fun createTasks(project: Project, basePlugin: BasePlayPlugin) { val extensions = basePlugin.extensions extensions.artifacts.all { artifact -> val baseTasks = basePlugin.getVariantTasks(artifact) val androidExtension = project.extensions.getByType(AppExtension::class.java) androidExtension.applicationVariants.all { variant -> if (variant.buildType.name == "release" && artifact.appId == variant.applicationId) { addVariantTasks(project, variant, baseTasks, artifact) } } } } private fun addVariantTasks(project: Project, variant: ApplicationVariant, baseTasks: ArtifactData, artifact: PublishArtifact) { val createEditTask = baseTasks.createEditTask val appId = variant.applicationId val artifactName = artifact.name.capitalize() variant.outputs.all { output -> val outputNamePostfix = output.filterTypes.joinToString("") { it.capitalize() } val tasksName = UPLOAD_APK_TASK_NAME_PREFIX + artifactName + output.name + outputNamePostfix val uploadTask = project.tasks.register(tasksName, UploadApkTask::class.java, appId, artifact.name, output) uploadTask.configure { it.dependsOn(variant.assembleProvider) it.dependsOn(createEditTask) } baseTasks.trackTask.configure { it.dependsOn(uploadTask) } } } companion object { fun isAndroidProject(project: Project): Boolean { return project.plugins.hasPlugin("com.android.application") } val PLAY_GROUP = "Play Publisher" private const val UPLOAD_APK_TASK_NAME_PREFIX = "playUploadApk" } }
mit
c8d4e8cd3ca84bae620ef53a5e3e76ee
33.070588
144
0.649171
4.641026
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/outerMembers.kt
10
952
package ceSuperAccess fun main(args: Array<String>) { A().Inner().test() } class A { public fun publicFun(): Int = 1 public val publicVal: Int = 2 protected fun protectedFun(): Int = 3 protected val protectedVal: Int = 4 @JvmField protected val protectedField: Int = 5 private fun privateFun() = 6 private val privateVal = 7 inner class Inner { fun test() { //Breakpoint! val a = publicFun() } } } fun <T> intBlock(block: () -> T): T { return block() } // EXPRESSION: intBlock { publicFun() } // RESULT: 1: I // EXPRESSION: intBlock { publicVal } // RESULT: 2: I // EXPRESSION: intBlock { protectedFun() } // RESULT: 3: I // EXPRESSION: intBlock { protectedVal } // RESULT: 4: I // EXPRESSION: intBlock { protectedField } // RESULT: 5: I // EXPRESSION: intBlock { privateFun() } // RESULT: 6: I // EXPRESSION: intBlock { privateVal } // RESULT: 7: I
apache-2.0
a38ef72105a9f714bd68e9770233b6b8
17.666667
42
0.59979
3.512915
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/IsEnumEntryFactory.kt
4
2338
// 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 import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs object IsEnumEntryFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = diagnostic.psiElement.safeAs<KtTypeReference>()?.parent ?: return null return when (element) { is KtIsExpression -> if (element.typeReference == null) null else ReplaceWithComparisonFix(element) is KtWhenConditionIsPattern -> if (element.typeReference == null || element.isNegated) null else RemoveIsFix(element) else -> null } } private class ReplaceWithComparisonFix(isExpression: KtIsExpression) : KotlinQuickFixAction<KtIsExpression>(isExpression) { private val comparison = if (isExpression.isNegated) "!=" else "==" override fun getText() = KotlinBundle.message("replace.with.0", comparison) override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val leftHandSide = element?.leftHandSide ?: return val typeReference = element?.typeReference?.text ?: return val binaryExpression = KtPsiFactory(project).createExpressionByPattern("$0 $comparison $1", leftHandSide, typeReference) element?.replace(binaryExpression) } } private class RemoveIsFix(isPattern: KtWhenConditionIsPattern) : KotlinQuickFixAction<KtWhenConditionIsPattern>(isPattern) { override fun getText() = KotlinBundle.message("remove.expression", "is") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val typeReference = element?.typeReference?.text ?: return element?.replace(KtPsiFactory(project).createWhenCondition(typeReference)) } } }
apache-2.0
3250c45944060240e495a75bc0f5b9eb
48.744681
158
0.724551
5.184035
false
false
false
false
noobyang/AndroidStudy
kotlin/src/main/java/com/lee/kotlin/coroutine/TestCoroutine4.kt
1
4284
package com.lee.kotlin.coroutine import kotlinx.coroutines.* import kotlinx.coroutines.channels.actor import kotlin.system.measureTimeMillis suspend fun massiveRun(action: suspend () -> Unit) { val n = 100 // 启动的协程数量 val k = 1000 // 每个协程重复执行同一动作的次数 val time = measureTimeMillis { coroutineScope { // 协程的作用域 repeat(n) { launch { repeat(k) { action() } } } } } println("Completed ${n * k} actions in $time ms") } // 共享的可变状态与并发 //// volatile 无济于事 //// volatile 变量保证可线性化(这是“原子”的技术术语)读取和写入变量, //// 但在大量动作(在我们的示例中即“递增”操作)发生时并不提供原子性 //@Volatile // 在 Kotlin 中 `volatile` 是一个注解 //var counter = 0 // //// 它不太可能打印出“Counter = 100000”,因为一百个协程在多个线程中同时递增计数器但没有做并发处理。 //fun main() = runBlocking { // withContext(Dispatchers.Default) { // massiveRun { // counter++ // } // } // println("Counter = $counter") //} // 线程安全的数据结构 //var counter = AtomicInteger() // //fun main() = runBlocking { // withContext(Dispatchers.Default) { // massiveRun { // counter.incrementAndGet() // } // } // println("Counter = $counter") //} // 以细粒度限制线程 // 限制线程 是解决共享可变状态问题的一种方案:对特定共享状态的所有访问权都限制在单个线程中。 //val counterContext = newSingleThreadContext("CounterContext") //var counter = 0 // //fun main() = runBlocking { // withContext(Dispatchers.Default) { // massiveRun { // // 将每次自增限制在单线程上下文中 // withContext(counterContext) { // counter++ // } // } // } // println("Counter = $counter") //} // 以粗粒度限制线程 //val counterContext = newSingleThreadContext("CounterContext") //var counter = 0 // //fun main() = runBlocking { // // 将一切都限制在单线程上下文中 // withContext(counterContext) { // massiveRun { // counter++ // } // } // println("Counter = $counter") //} // 互斥 // 通常会为此目的使用 synchronized 或者 ReentrantLock。 在协程中的替代品叫做 Mutex 。 // 它具有 lock 和 unlock 方法, 可以隔离关键的部分。 // 关键的区别在于 Mutex.lock() 是一个挂起函数,它不会阻塞线程。 //val mutex = Mutex() //var counter = 0 // //fun main() = runBlocking { // withContext(Dispatchers.Default) { // massiveRun { // // 用锁保护每次自增 // mutex.withLock { // counter++ // } // } // } // println("Counter = $counter") //} // Actors //一个 actor 是由协程、 被限制并封装到该协程中的状态以及一个与其它协程通信的 通道 组合而成的一个实体。 // 一个简单的 actor 可以简单的写成一个函数, 但是一个拥有复杂状态的 actor 更适合由类来表示。 // 计数器 Actor 的各种类型 sealed class CounterMsg object IncCounter : CounterMsg() // 递增计数器的单向消息 class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // 携带回复的请求 // 这个函数启动一个新的计数器 actor fun CoroutineScope.counterActor() = actor<CounterMsg> { var counter = 0 // actor 状态 for (msg in channel) { // 即将到来消息的迭代器 when (msg) { is IncCounter -> counter++ is GetCounter -> msg.response.complete(counter) } } } fun main() = runBlocking<Unit> { val counter = counterActor() // 创建该 actor withContext(Dispatchers.Default) { massiveRun { counter.send(IncCounter) } } // 发送一条消息以用来从一个 actor 中获取计数值 val response = CompletableDeferred<Int>() counter.send(GetCounter(response)) println("Counter = ${response.await()}") counter.close() // 关闭该actor }
apache-2.0
bbfe7ac079807a2a1d0e42b2a7edb8d7
23.306569
82
0.593994
3.097674
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/Mito/ImageSubjectInfoActivity.kt
1
7458
package stan.androiddemo.project.Mito import android.content.Intent import android.graphics.drawable.Drawable import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.graphics.drawable.VectorDrawableCompat import android.support.v4.graphics.drawable.DrawableCompat import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.StaggeredGridLayoutManager import android.view.View import android.widget.ImageView import android.widget.Toast import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.facebook.drawee.view.SimpleDraweeView import kotlinx.android.synthetic.main.activity_image_subject_info.* import org.litepal.crud.DataSupport import stan.androiddemo.Model.ResultInfo import stan.androiddemo.R import stan.androiddemo.project.Mito.Model.ImageSetInfo import stan.androiddemo.project.Mito.Model.ImageSubjectInfo import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder class ImageSubjectInfoActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener { //这个是某个专题里的图片 var arrImageSet = ArrayList<ImageSetInfo>() lateinit var mAdapter: BaseQuickAdapter<ImageSetInfo, BaseViewHolder> lateinit var imageSubject:ImageSubjectInfo lateinit var failView: View lateinit var loadingView: View lateinit var progressLoading: Drawable var index = 0 var count = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_subject_info) toolbar.setNavigationOnClickListener { onBackPressed() } imageSubject = intent.getParcelableExtra<ImageSubjectInfo>("subject") txt_toolbar_title.text = imageSubject.subjectName val d0 = VectorDrawableCompat.create(resources,R.drawable.ic_toys_black_24dp,null) progressLoading = DrawableCompat.wrap(d0!!.mutate()) DrawableCompat.setTint(progressLoading,resources.getColor(R.color.tint_list_pink)) mAdapter = object:BaseQuickAdapter<ImageSetInfo,BaseViewHolder>(R.layout.image_set_item,arrImageSet){ override fun convert(helper: BaseViewHolder, item: ImageSetInfo) { val img = helper.getView<SimpleDraweeView>(R.id.img_set) img.aspectRatio = item.resolution.pixelX.toFloat() / item.resolution.pixelY.toFloat() ImageLoadBuilder.Start(this@ImageSubjectInfoActivity,img,item.mainImage).setProgressBarImage(progressLoading).build() helper.setText(R.id.txt_image_title,item.title) helper.setText(R.id.txt_image_tag,item.category) helper.setText(R.id.txt_image_resolution,item.resolutionStr) helper.setText(R.id.txt_image_theme,item.theme) val imgCollect = helper.getView<ImageView>(R.id.img_mito_collect) if (item.isCollected){ imgCollect.setImageDrawable(resources.getDrawable(R.drawable.ic_star_theme_24dp)) } else{ imgCollect.setImageDrawable(resources.getDrawable(R.drawable.ic_star_border_white_24dp)) } imgCollect.setOnClickListener { if (item.isCollected){ imgCollect.setImageDrawable(resources.getDrawable(R.drawable.ic_star_border_white_24dp)) DataSupport.deleteAll(ImageSetInfo::class.java,"hashId = " + item.hashId ) item.isCollected = !item.isCollected } else{ imgCollect.setImageDrawable(resources.getDrawable(R.drawable.ic_star_theme_24dp)) item.isCollected = !item.isCollected val result = item.save() if (result){ Toast.makeText(this@ImageSubjectInfoActivity,"收藏成功",Toast.LENGTH_LONG).show() } else{ Toast.makeText(this@ImageSubjectInfoActivity,"收藏失败",Toast.LENGTH_LONG).show() } } } } } swipe_refresh_subjectinfo_mito.setColorSchemeResources(R.color.colorPrimary) swipe_refresh_subjectinfo_mito.setOnRefreshListener(this) recycler_view_subjectinfo_images.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL) recycler_view_subjectinfo_images.adapter = mAdapter loadingView = View.inflate(this@ImageSubjectInfoActivity,R.layout.list_loading_hint,null) failView = View.inflate(this@ImageSubjectInfoActivity,R.layout.list_empty_hint,null) failView.setOnClickListener { mAdapter.emptyView = loadingView index = 0 loadData() } mAdapter.emptyView = loadingView mAdapter.setEnableLoadMore(true) mAdapter.setOnLoadMoreListener({ loadData() },recycler_view_subjectinfo_images) mAdapter.setOnItemClickListener { _, _, position -> val set = arrImageSet[position] val intent = Intent(this@ImageSubjectInfoActivity,ImageSetActivity::class.java) intent.putExtra("set",set) startActivity(intent) } loadData() } override fun onRefresh() { } private fun loadData(){ var url = imageSubject.subjectUrl if (index >= 1){ if (count <= 0){ mAdapter.loadMoreEnd() return } if (arrImageSet.count() >= count){ mAdapter.loadMoreEnd() return } else{ url = url + "index-"+ (index + 1) +".html" } } ImageSubjectInfo.getImageSubject(url) { result:ResultInfo -> runOnUiThread { count = result.count if (swipe_refresh_subjectinfo_mito != null){ swipe_refresh_subjectinfo_mito.isRefreshing = false } if (result.code != 0) { Toast.makeText(this@ImageSubjectInfoActivity,result.message, Toast.LENGTH_LONG).show() mAdapter.emptyView = failView return@runOnUiThread } val imageSets = result.data!! as ArrayList<ImageSetInfo> if (imageSets.size <= 0){ if (index == 0){ mAdapter.emptyView = failView return@runOnUiThread } else{ mAdapter.loadMoreEnd() } } if (index == 0){ arrImageSet.clear() } else{ mAdapter.loadMoreComplete() } index ++ val collectedImages = DataSupport.findAll(ImageSetInfo::class.java) arrImageSet.addAll(imageSets.map { val img = it if (collectedImages.find { it.hashId == img.hashId } != null){ it.isCollected = true } it }) mAdapter.notifyDataSetChanged() } } } }
mit
dfb7d132792b33a42fe844cc31258d00
40.920904
133
0.604178
4.959893
false
false
false
false
7449/Album
core/src/main/java/com/gallery/core/entity/ScanEntity.kt
1
1677
package com.gallery.core.entity import android.content.ContentUris import android.net.Uri import android.os.Parcelable import android.provider.MediaStore import com.gallery.scan.impl.file.FileScanEntity import kotlinx.parcelize.Parcelize /** [FileScanEntity]中介 */ @Parcelize data class ScanEntity( val delegate: FileScanEntity, val count: Int = 0, var isSelected: Boolean = false, ) : Parcelable { val id: Long get() = delegate.id val parent: Long get() = delegate.parent val size: Long get() = delegate.size val duration: Long get() = delegate.duration val dateModified: Long get() = delegate.dateModified val bucketDisplayName: String get() = delegate.bucketDisplayName val uri: Uri get() = when (delegate.mediaType) { MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE.toString() -> ContentUris.withAppendedId( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id ) MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO.toString() -> ContentUris.withAppendedId( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id ) else -> Uri.EMPTY } val isGif: Boolean get() = delegate.mimeType.contains("gif") || delegate.mimeType.contains("GIF") val isVideo: Boolean get() = delegate.mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO.toString() val isImage: Boolean get() = delegate.mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE.toString() }
mpl-2.0
a4f6cd9129086338b563409d24ce39c8
33.638298
99
0.624029
4.546196
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/discovery/SettingsInfoItem.kt
2
2203
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments.discovery import android.view.View import android.widget.TextView import androidx.annotation.DrawableRes import androidx.annotation.StringRes import butterknife.BindView import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import im.vector.R import im.vector.ui.epoxy.BaseEpoxyHolder import im.vector.ui.util.setTextOrHide @EpoxyModelClass(layout = R.layout.item_settings_helper_info) abstract class SettingsInfoItem : EpoxyModelWithHolder<SettingsInfoItem.Holder>() { @EpoxyAttribute var helperText: String? = null @EpoxyAttribute @StringRes var helperTextResId: Int? = null @EpoxyAttribute var itemClickListener: View.OnClickListener? = null @EpoxyAttribute @DrawableRes var compoundDrawable: Int = R.drawable.vector_warning_red @EpoxyAttribute var showCompoundDrawable: Boolean = false override fun bind(holder: Holder) { super.bind(holder) if (helperTextResId != null) { holder.text.setText(helperTextResId!!) } else { holder.text.setTextOrHide(helperText) } holder.main.setOnClickListener(itemClickListener) if (showCompoundDrawable) { holder.text.setCompoundDrawablesWithIntrinsicBounds(compoundDrawable, 0, 0, 0) } else { holder.text.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0) } } class Holder : BaseEpoxyHolder() { @BindView(R.id.settings_helper_text) lateinit var text: TextView } }
apache-2.0
849e3f9e5134998fb4a06e211c27bebe
28.783784
90
0.723559
4.450505
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/usersview/userslist.kt
1
1417
package koma.gui.view.usersview import javafx.collections.ObservableList import javafx.scene.layout.Priority import koma.gui.element.control.PrettyListView import koma.gui.view.usersview.fragment.MemberCell import koma.matrix.UserId import kotlinx.coroutines.ExperimentalCoroutinesApi import link.continuum.desktop.gui.StyleBuilder import link.continuum.desktop.gui.VBox import link.continuum.desktop.gui.add import link.continuum.desktop.gui.em import link.continuum.desktop.gui.list.user.UserDataStore import link.continuum.desktop.gui.view.AccountContext import link.continuum.desktop.util.debugAssertUiThread @ExperimentalCoroutinesApi class RoomMemberListView( context: AccountContext, userData: UserDataStore ) { val root = VBox(5.0) private val userlist = PrettyListView<UserId>() fun setList(memList: ObservableList<UserId>){ debugAssertUiThread() userlist.items = memList } init { with(root) { userlist.apply { isFocusTraversable = false style = listStyle VBox.setVgrow(this, Priority.ALWAYS) setCellFactory { MemberCell(context, userData) } } add(userlist) } } companion object { private val listStyle = StyleBuilder().apply { minWidth = 3.em }.toStyle() } }
gpl-3.0
8e33da60c366a0078e9cca1992722fd9
28.520833
57
0.678193
4.400621
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/output/service/HttpWsTestCaseWriter.kt
1
21618
package org.evomaster.core.output.service import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.CookieWriter import org.evomaster.core.output.Lines import org.evomaster.core.output.OutputFormat import org.evomaster.core.output.TokenWriter import org.evomaster.core.output.formatter.OutputFormatter import org.evomaster.core.output.service.TestWriterUtils.Companion.formatJsonWithEscapes import org.evomaster.core.problem.enterprise.EnterpriseActionGroup import org.evomaster.core.problem.external.service.httpws.HttpExternalServiceAction import org.evomaster.core.problem.httpws.service.HttpWsAction import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.problem.rest.param.BodyParam import org.evomaster.core.problem.rest.param.HeaderParam import org.evomaster.core.search.ActionResult import org.evomaster.core.search.EvaluatedAction import org.evomaster.core.search.FitnessValue import org.evomaster.core.search.gene.utils.GeneUtils import org.slf4j.LoggerFactory import javax.ws.rs.core.MediaType abstract class HttpWsTestCaseWriter : ApiTestCaseWriter() { companion object { private val log = LoggerFactory.getLogger(HttpWsTestCaseWriter::class.java) } abstract fun getAcceptHeader(call: HttpWsAction, res: HttpWsCallResult): String override fun shouldFailIfException(result: ActionResult): Boolean { /* Fail test if exception is not thrown, but not if it was a timeout, otherwise the test would become flaky */ return !(result as HttpWsCallResult).getTimedout() } protected fun handlePreCallSetup(call: HttpWsAction, lines: Lines, res: HttpWsCallResult) { /* This is needed when we need to execute some code before each HTTP call. Cannot be in @Before/Fixture, as it must be done for each HTTP call , and not just once for test */ if (format.isCsharp()) { lines.add("Client.DefaultRequestHeaders.Clear();") lines.add(getAcceptHeader(call, res)) lines.addEmpty() } } protected fun handleFirstLine(call: HttpWsAction, lines: Lines, res: HttpWsCallResult, resVarName: String) { lines.addEmpty() handlePreCallSetup(call, lines, res) if (needsResponseVariable(call, res) && !res.failedCall()) { when { format.isKotlin() -> lines.append("val $resVarName: ValidatableResponse = ") format.isJava() -> lines.append("ValidatableResponse $resVarName = ") format.isJavaScript() -> lines.append("const $resVarName = ") format.isCsharp() -> lines.append("var $resVarName = ") } } when { format.isJavaOrKotlin() -> lines.append("given()") format.isJavaScript() -> lines.append("await superagent") format.isCsharp() -> lines.append("await Client") } if (!format.isJavaScript() && !format.isCsharp()) { // in JS, the Accept must be after the verb // in C#, must be before the call lines.append(getAcceptHeader(call, res)) } } protected fun isVerbWithPossibleBodyPayload(verb: String): Boolean { val verbs = arrayOf("post", "put", "patch") if (verbs.contains(verb.toLowerCase())) return true; return false; } protected fun openAcceptHeader(): String { return when { format.isJavaOrKotlin() -> ".accept(" format.isJavaScript() -> ".set('Accept', " format.isCsharp() -> "Client.DefaultRequestHeaders.Add(\"Accept\", " else -> throw IllegalArgumentException("Invalid format: $format") } } protected fun closeAcceptHeader(openedHeader: String): String { var result = openedHeader result += ")" if (format.isCsharp()) result = "$result;" return result } open fun needsResponseVariable(call: HttpWsAction, res: HttpWsCallResult): Boolean { /* Bit tricky... when using RestAssured on JVM, we can assert directly on the call... but that is not the case for the other libraries used for example in JS and C# */ return config.outputFormat == OutputFormat.JS_JEST || config.outputFormat == OutputFormat.CSHARP_XUNIT } protected fun handleHeaders(call: HttpWsAction, lines: Lines) { if (format.isCsharp()) { //FIXME log.warn("Currently not handling headers in C#") return } val prechosenAuthHeaders = call.auth.headers.map { it.name } val set = when { format.isJavaOrKotlin() -> "header" format.isJavaScript() -> "set" //TODO C# else -> throw IllegalArgumentException("Not supported format: $format") } call.auth.headers.forEach { lines.add(".$set(\"${it.name}\", \"${it.value}\") // ${call.auth.name}") } call.parameters.filterIsInstance<HeaderParam>() .filter { !prechosenAuthHeaders.contains(it.name) } .filter { !(call.auth.jsonTokenPostLogin != null && it.name.equals("Authorization", true)) } .filter { it.isInUse() } .forEach { val x = it.gene.getValueAsRawString() lines.add(".$set(\"${it.name}\", \"${GeneUtils.applyEscapes(x, GeneUtils.EscapeMode.BODY, format)}\")") } val cookieLogin = call.auth.cookieLogin if (cookieLogin != null) { when { format.isJavaOrKotlin() -> lines.add(".cookies(${CookieWriter.cookiesName(cookieLogin)})") format.isJavaScript() -> lines.add(".set('Cookies', ${CookieWriter.cookiesName(cookieLogin)})") //TODO C# } } //TODO make sure header was not already set val tokenLogin = call.auth.jsonTokenPostLogin if (tokenLogin != null) { lines.add(".$set(\"Authorization\", ${TokenWriter.tokenName(tokenLogin)}) // ${call.auth.name}") } } protected fun handleResponseAfterTheCall( call: HttpWsAction, res: HttpWsCallResult, responseVariableName: String, lines: Lines ) { if (format.isJavaOrKotlin() //assertions handled in the call || !needsResponseVariable(call, res) || res.failedCall() ) { return } lines.addEmpty() val code = res.getStatusCode() when { format.isJavaScript() -> { lines.add("expect($responseVariableName.status).toBe($code);") } format.isCsharp() -> { lines.add("Assert.Equal($code, (int) $responseVariableName.StatusCode);") } else -> { LoggingUtil.uniqueWarn(log, "No status assertion supported for format $format") } } handleLastStatementComment(res, lines) if (config.enableBasicAssertions) { handleResponseAssertions(lines, res, responseVariableName) } } protected open fun handleLastStatementComment(res: HttpWsCallResult, lines: Lines) { val code = res.getStatusCode() if (code == 500 && !config.blackBox) { lines.append(" // " + res.getLastStatementWhen500()) } } protected fun handleSingleCall( evaluatedAction: EvaluatedAction, index: Int, fv : FitnessValue, lines: Lines, baseUrlOfSut: String ) { val exActions = mutableListOf<HttpExternalServiceAction>() var anyDnsCache = false // add all used external service actions for the action if (config.isEnabledExternalServiceMocking()) { if (evaluatedAction.action.parent !is EnterpriseActionGroup) throw IllegalStateException("invalid parent of the RestAction, it is expected to be EnterpriseActionGroup, but it is ${evaluatedAction.action.parent!!::class.java.simpleName}") val group = evaluatedAction.action.parent as EnterpriseActionGroup exActions.addAll( group.getExternalServiceActions().filterIsInstance<HttpExternalServiceAction>() .filter { it.active }) if (format.isJavaOrKotlin()) anyDnsCache = handleDnsForExternalServiceActions( lines, exActions, fv.getViewExternalRequestToDefaultWMByAction(index)) if (exActions.isNotEmpty()) { if (format.isJavaOrKotlin()) { handleExternalServiceActions(lines, exActions) } else { log.warn("In mocking of external services, we do NOT support for other format ($format) except JavaOrKotlin") } } } lines.addEmpty() val call = evaluatedAction.action as HttpWsAction val res = evaluatedAction.result as HttpWsCallResult if (res.failedCall()) { addActionInTryCatch(call, lines, res, baseUrlOfSut) } else { addActionLines(call, lines, res, baseUrlOfSut) } // reset all used external service action if (exActions.isNotEmpty()) { if (!format.isJavaOrKotlin()) { log.warn("NOT support for other format ($format) except JavaOrKotlin") } else { lines.addEmpty(1) exActions .distinctBy { it.externalService.getSignature() } .forEach { action -> lines.add("${TestWriterUtils.getWireMockVariableName(action.externalService)}.resetAll()") lines.appendSemicolon(format) } } } if (anyDnsCache){ lines.add("DnsCacheManipulator.clearDnsCache()") lines.appendSemicolon(format) } } protected fun makeHttpCall(call: HttpWsAction, lines: Lines, res: HttpWsCallResult, baseUrlOfSut: String): String { //first handle the first line val responseVariableName = createUniqueResponseVariableName() handleFirstLine(call, lines, res, responseVariableName) when { format.isJavaOrKotlin() -> { lines.indent(2) handleHeaders(call, lines) handleBody(call, lines) handleVerbEndpoint(baseUrlOfSut, call, lines) } format.isJavaScript() -> { lines.indent(2) //in SuperAgent, verb must be first handleVerbEndpoint(baseUrlOfSut, call, lines) lines.append(getAcceptHeader(call, res)) handleHeaders(call, lines) handleBody(call, lines) } format.isCsharp() -> { handleVerbEndpoint(baseUrlOfSut, call, lines) //TODO headers } } if (format.isJavaOrKotlin()) { handleResponseDirectlyInTheCall(call, res, lines) } handleLastLine(call, res, lines, responseVariableName) return responseVariableName } abstract fun handleVerbEndpoint(baseUrlOfSut: String, _call: HttpWsAction, lines: Lines) protected fun sendBodyCommand(): String { return when { format.isJavaOrKotlin() -> "body" format.isJavaScript() -> "send" format.isCsharp() -> "" else -> throw IllegalArgumentException("Format not supported $format") } } //TODO: check again for C#, especially when not json protected open fun handleBody(call: HttpWsAction, lines: Lines) { val bodyParam = call.parameters.find { p -> p is BodyParam } as BodyParam? if (format.isCsharp() && bodyParam == null) { lines.append("null") return } if (bodyParam != null) { val send = sendBodyCommand() when { format.isJavaOrKotlin() -> lines.add(".contentType(\"${bodyParam.contentType()}\")") format.isJavaScript() -> lines.add(".set('Content-Type','${bodyParam.contentType()}')") //FIXME //format.isCsharp() -> lines.add("Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"${bodyParam.contentType()}\"));") } if (bodyParam.isJson()) { val json = bodyParam.gene.getValueAsPrintableString(mode = GeneUtils.EscapeMode.JSON, targetFormat = format) printSendJsonBody(json, lines) } else if (bodyParam.isTextPlain()) { val body = bodyParam.gene.getValueAsPrintableString(mode = GeneUtils.EscapeMode.TEXT, targetFormat = format) if (body != "\"\"") { if (!format.isCsharp()) lines.add(".$send($body)") else { lines.append("new StringContent(\"$body\", Encoding.UTF8, \"${bodyParam.contentType()}\")") } } else { if (!format.isCsharp()) lines.add(".$send(\"${"""\"\""""}\")") else { lines.append("new StringContent(\"${"""\"\""""}\", Encoding.UTF8, \"${bodyParam.contentType()}\")") } } //BMR: this is needed because, if the string is empty, it causes a 400 (bad request) code on the test end. // inserting \"\" should prevent that problem // TODO: get some tests done of this } else if (bodyParam.isForm()) { val body = bodyParam.gene.getValueAsPrintableString( mode = GeneUtils.EscapeMode.X_WWW_FORM_URLENCODED, targetFormat = format ) if (!format.isCsharp()) lines.add(".$send(\"$body\")") else { lines.append("new StringContent(\"$body\", Encoding.UTF8, \"${bodyParam.contentType()}\")") } } else { //TODO XML LoggingUtil.uniqueWarn(log, "Unhandled type for body payload: " + bodyParam.contentType()) } } } fun printSendJsonBody(json: String, lines: Lines) { val send = sendBodyCommand() val bodyLines = formatJsonWithEscapes(json, format) if (bodyLines.size == 1) { if (!format.isCsharp()) { lines.add(".$send(${bodyLines.first()})") } else { lines.add("new StringContent(${bodyLines.first()}, Encoding.UTF8, \"application/json\")") } } else { if (!format.isCsharp()) { lines.add(".$send(${bodyLines.first()} + ") lines.indented { (1 until bodyLines.lastIndex).forEach { i -> lines.add("${bodyLines[i]} + ") } lines.add("${bodyLines.last()})") } } else { lines.add("new StringContent(") lines.add("${bodyLines.first()} +") lines.indented { (1 until bodyLines.lastIndex).forEach { i -> lines.add("${bodyLines[i]} + ") } lines.add("${bodyLines.last()}") } lines.add(", Encoding.UTF8, \"application/json\")") } } } /** * This is done mainly for RestAssured */ protected fun handleResponseDirectlyInTheCall(call: HttpWsAction, res: HttpWsCallResult, lines: Lines) { if (!res.failedCall()) { val code = res.getStatusCode() when { format.isJavaOrKotlin() -> { lines.add(".then()") lines.add(".statusCode($code)") } else -> throw IllegalStateException("No assertion in calls for format: $format") } handleLastStatementComment(res, lines) if (config.enableBasicAssertions) { handleResponseAssertions(lines, res, null) } } // else if (partialOracles.generatesExpectation(call, res) // && format.isJavaOrKotlin()){ // //FIXME what is this for??? // lines.add(".then()") // } } //---------------------------------------------------------------------------------------- // assertion lines protected fun handleResponseAssertions(lines: Lines, res: HttpWsCallResult, responseVariableName: String?) { assert(responseVariableName != null || format.isJavaOrKotlin()) /* there are 2 cases: a) assertions directly as part of the HTTP call, eg, as done in RestAssured b) assertions on response object, stored in a variable after the HTTP call based on this, the code to add is quite different. Note, in case of (b), we must have the name of the variable */ val isInCall = responseVariableName == null if (isInCall) { lines.add(".assertThat()") } val bodyString = res.getBody() if (bodyString.isNullOrBlank()) { lines.add(emptyBodyCheck(responseVariableName)) return } if (res.getBodyType() != null) { //TODO is there a better solution? where was this a problem? val bodyTypeSimplified = res.getBodyType() .toString() .split(";") // remove all associated variables .first() val instruction = when { format.isJavaOrKotlin() -> ".contentType(\"$bodyTypeSimplified\")" format.isJavaScript() -> "expect($responseVariableName.header[\"content-type\"].startsWith(\"$bodyTypeSimplified\")).toBe(true);" format.isCsharp() -> "Assert.Contains(\"$bodyTypeSimplified\", $responseVariableName.Content.Headers.GetValues(\"Content-Type\").First());" else -> throw IllegalStateException("Unsupported format $format") } lines.add(instruction) } val type = res.getBodyType() // if there is payload, but no type identified, treat it as plain text ?: MediaType.TEXT_PLAIN_TYPE var bodyVarName = responseVariableName if (format.isCsharp()) { //cannot use response object directly, as need to unmarshall the body payload manually bodyVarName = createUniqueBodyVariableName() lines.add("dynamic $bodyVarName = ") } if (type.isCompatible(MediaType.APPLICATION_JSON_TYPE) || type.toString().toLowerCase().contains("+json")) { if (format.isCsharp()) { lines.append("JsonConvert.DeserializeObject(await $responseVariableName.Content.ReadAsStringAsync());") } handleJsonStringAssertion(bodyString, lines, bodyVarName, res.getTooLargeBody()) } else if (type.isCompatible(MediaType.TEXT_PLAIN_TYPE)) { if (format.isCsharp()) { lines.append("await $responseVariableName.Content.ReadAsStringAsync();") } handleTextPlainTextAssertion(bodyString, lines, bodyVarName) } else { if (format.isCsharp()) { lines.append("await $responseVariableName.Content.ReadAsStringAsync();") } LoggingUtil.uniqueWarn(log, "Currently no assertions are generated for response type: $type") } } protected fun handleLastLine(call: HttpWsAction, res: HttpWsCallResult, lines: Lines, resVarName: String) { if (format.isJavaScript()) { /* This is to deal with very weird behavior in SuperAgent that crashes the tests for status codes different from 2xx... so, here we make it passes as long as a status was present */ lines.add(".ok(res => res.status)") } if (lines.shouldUseSemicolon(format)) { /* FIXME this is wrong when // is in a string of response, like a URL. Need to check last //, and that is not inside "" Need tests for it... albeit tricky as Kotlin does not use ;, so need Java or unit test However, currently we have comments _only_ on status codes, which does not use ". so a dirty quick fix is to check if no " is used */ if (lines.currentContains("//") && !lines.currentContains("\"")) { //a ; after a comment // would be ignored otherwise if (lines.isCurrentACommentLine()) { //let's not lose indentation lines.replaceInCurrent(Regex("//"), "; //") } else { //there can be any number of spaces between the statement and the // lines.replaceInCurrent(Regex("\\s*//"), "; //") } } else { lines.appendSemicolon(format) } } //TODO what was the reason for this? if (!format.isCsharp()) { lines.deindent(2) } } }
lgpl-3.0
a4fc941585936c504d990221aacd7fd1
36.274138
192
0.563743
4.961671
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/editor/SkinFoldingBuilder.kt
1
3266
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.editor import com.gmail.blueboxware.libgdxplugin.filetypes.skin.SkinElementTypes import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinClassSpecification import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinResource import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.findFurthestSiblingOfSameType import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.TextRange /* * * Adapted from https://github.com/JetBrains/intellij-community/tree/ab08c979a5826bf293ae03cd67463941b0066eb8/json * */ class SkinFoldingBuilder : FoldingBuilder, DumbAware { override fun getPlaceholderText(node: ASTNode): String = when (node.elementType) { SkinElementTypes.OBJECT -> "{...}" SkinElementTypes.ARRAY -> "[...]" SkinElementTypes.LINE_COMMENT -> "//..." SkinElementTypes.BLOCK_COMMENT -> "/*...*/" SkinElementTypes.RESOURCE -> "{ " + ((node.psi as? SkinResource)?.name ?: "") + " ...}" SkinElementTypes.CLASS_SPECIFICATION -> "{ " + ((node.psi as? SkinClassSpecification)?.classNameAsString?.dollarName ?: "") + " ...}" else -> "..." } override fun buildFoldRegions(node: ASTNode, document: Document): Array<out FoldingDescriptor> { val descriptors = mutableListOf<FoldingDescriptor>() collectDescriptorsRecursively(node, document, descriptors) return descriptors.toTypedArray() } override fun isCollapsedByDefault(node: ASTNode) = false private fun collectDescriptorsRecursively( node: ASTNode, document: Document, descriptors: MutableList<FoldingDescriptor> ) { val type = node.elementType if ((type == SkinElementTypes.OBJECT || type == SkinElementTypes.ARRAY || type == SkinElementTypes.BLOCK_COMMENT || type == SkinElementTypes.CLASS_SPECIFICATION || type == SkinElementTypes.RESOURCE ) && spansMultipleLines(node, document) ) { descriptors.add(FoldingDescriptor(node, node.textRange)) } else if (type == SkinElementTypes.LINE_COMMENT) { val firstNode = findFurthestSiblingOfSameType(node.psi, false) val lastNode = findFurthestSiblingOfSameType(node.psi, true) val start = firstNode.textRange.startOffset val end = lastNode.textRange.endOffset if (document.getLineNumber(start) != document.getLineNumber(end)) { descriptors.add(FoldingDescriptor(node, TextRange(start, end))) } } for (child in node.getChildren(null)) { collectDescriptorsRecursively(child, document, descriptors) } } private fun spansMultipleLines(node: ASTNode, document: Document): Boolean { val range = node.textRange return document.getLineNumber(range.startOffset) < document.getLineNumber(range.endOffset) } }
apache-2.0
3d73149b6e50a5d14f22c539dffe6f81
38.829268
128
0.67177
4.774854
false
false
false
false
ibinti/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/SchemeManagerIprProvider.kt
3
3382
/* * 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.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ArrayUtil import com.intellij.util.PathUtilRt import com.intellij.util.containers.ContainerUtil import com.intellij.util.loadElement import com.intellij.util.text.UniqueNameGenerator import com.intellij.util.toByteArray import org.jdom.Element import java.io.InputStream import java.util.* class SchemeManagerIprProvider(private val subStateTagName: String) : StreamProvider { private val nameToData = ContainerUtil.newConcurrentMap<String, ByteArray>() override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { nameToData.get(PathUtilRt.getFileName(fileSpec))?.let(ByteArray::inputStream).let { consumer(it) } return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { nameToData.remove(PathUtilRt.getFileName(fileSpec)) return true } override fun processChildren(path: String, roamingType: RoamingType, filter: (String) -> Boolean, processor: (String, InputStream, Boolean) -> Boolean): Boolean { for ((name, data) in nameToData) { if (filter(name) && !data.inputStream().use { processor(name, it, false) }) { break } } return true } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { LOG.assertTrue(content.isNotEmpty()) nameToData.put(PathUtilRt.getFileName(fileSpec), ArrayUtil.realloc(content, size)) } fun load(state: Element?, nameGetter: ((Element) -> String)? = null) { nameToData.clear() if (state == null) { return } val nameGenerator = UniqueNameGenerator() for (child in state.getChildren(subStateTagName)) { var name = nameGetter?.invoke(child) ?: child.getAttributeValue("name") if (name == null) { for (optionElement in child.getChildren("option")) { if (optionElement.getAttributeValue("name") == "myName") { name = optionElement.getAttributeValue("value") } } } if (name.isNullOrEmpty()) { continue } nameToData.put(nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(name, false) + ".xml"), child.toByteArray()) } } fun writeState(state: Element, comparator: Comparator<String>? = null) { val names = nameToData.keys.toTypedArray() if (comparator == null) { names.sort() } else { names.sortWith(comparator) } for (name in names) { nameToData.get(name)?.let { state.addContent(loadElement(it.inputStream())) } } } }
apache-2.0
990588aa4c1a761df7c11c5ec08dce51
33.520408
124
0.685393
4.420915
false
false
false
false
sunghwanJo/workshop-jb
src/iii_conventions/MyDate.kt
1
1522
package iii_conventions class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (year != other.year) return year - other.year if (month != other.month) return month - other.month return dayOfMonth - other.dayOfMonth } override fun equals(other: Any?): Boolean { return compareTo(other as MyDate) == 0 } } enum class TimeInterval { DAY, WEEK, YEAR } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int); operator fun TimeInterval.times(timeNumber: Int) = RepeatedTimeInterval(this, timeNumber) operator fun MyDate.rangeTo(other: MyDate) = DateRange(this, other) operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval, 1) operator fun MyDate.plus(repeatedTimeInterval: RepeatedTimeInterval) = addTimeIntervals(repeatedTimeInterval.ti, repeatedTimeInterval.n ) class DateRange(public override val start: MyDate, public override val end: MyDate) : Iterable<MyDate>, Range<MyDate> { override fun contains(item: MyDate): Boolean = start <= item && item <= end override fun iterator(): Iterator<MyDate> = DateIterator(this) } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var cursor: MyDate = dateRange.start override fun next(): MyDate { val current = cursor cursor = cursor.nextDay() return current } override fun hasNext(): Boolean = cursor <= dateRange.end }
mit
df7b23cd8ea1efd34f3688d1071e926a
31.382979
119
0.704993
4.361032
false
false
false
false
mniami/android.kotlin.benchmark
app/src/main/java/guideme/volunteers/ui/dialogs/UrlRequestDialog.kt
2
1063
package guideme.volunteers.ui.dialogs import android.content.Context import android.support.v7.app.AlertDialog import android.widget.EditText import guideme.volunteers.R class UrlRequestDialog { fun show(title: String, message: String, context: Context?, onFinished: (url: String?) -> Unit) { if (context == null) { onFinished(null) return } val editText = EditText(context) val alert = AlertDialog.Builder(context) alert.setTitle(title) alert.setMessage(message) alert.setView(editText) alert.setPositiveButton(context.getString(R.string.accept_dialog_button_text)) { dialog, whichButton -> //What ever you want to do with the value val url = editText.text.toString() onFinished(url) } alert.setNegativeButton(context.getString(R.string.cancel_dialog_button_text)) { dialog, whichButton -> // what ever you want to do with No option. onFinished(null) } alert.show() } }
apache-2.0
c7c0249741cf2225bfb3da4609231873
32.21875
111
0.639699
4.374486
false
false
false
false
AlmasB/FXGL
fxgl-entity/src/test/kotlin/com/almasb/fxgl/entity/level/text/TextLevelLoaderTest.kt
1
3355
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.entity.level.text import com.almasb.fxgl.entity.* import javafx.geometry.Point2D import org.hamcrest.BaseMatcher import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.hasItem import org.hamcrest.Description import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import java.io.FileNotFoundException import java.nio.file.Paths /** * * @author Almas Baimagambetov ([email protected]) */ class TextLevelLoaderTest { companion object { private val BLOCK_WIDTH = 40 private val BLOCK_HEIGHT = 40 } @Test fun `Default char is empty char`() { val loader = TextLevelLoader(BLOCK_WIDTH, BLOCK_HEIGHT) assertThat(loader.blockWidth, `is`(BLOCK_WIDTH)) assertThat(loader.blockHeight, `is`(BLOCK_HEIGHT)) assertThat(loader.emptyChar, `is`(' ')) } @Test fun `Load text level`() { val loader = TextLevelLoader(BLOCK_WIDTH, BLOCK_HEIGHT, '0') val world = GameWorld() world.addEntityFactory(TestEntityFactory()) val level = loader.load(javaClass.getResource("test_level.txt"), world) assertThat(level.width, `is`(4 * BLOCK_WIDTH)) assertThat(level.height, `is`(5 * BLOCK_HEIGHT)) assertThat(level.entities.size, `is`(4)) assertThat(level.entities, hasItem(EntityMatcher(0, 2, EntityType.TYPE1))) assertThat(level.entities, hasItem(EntityMatcher(1, 2, EntityType.TYPE1))) assertThat(level.entities, hasItem(EntityMatcher(3, 0, EntityType.TYPE2))) assertThat(level.entities, hasItem(EntityMatcher(3, 4, EntityType.TYPE3))) } private enum class EntityType { TYPE1, TYPE2, TYPE3 } @Test fun `Throw if file not found`() { assertThrows(FileNotFoundException::class.java, { TextLevelLoader(BLOCK_WIDTH, BLOCK_HEIGHT).load(Paths.get("bla-bla").toUri().toURL(), GameWorld()) }) } private class EntityMatcher(val x: Int, val y: Int, val entityType: EntityType) : BaseMatcher<Entity>() { override fun matches(item: Any): Boolean { val position = (item as Entity).position return position.x.toInt() == x*BLOCK_WIDTH && position.y.toInt() == y*BLOCK_HEIGHT && item.isType(entityType) } override fun describeTo(description: Description) { description.appendText("Entity at $x,$y with type $entityType") } } class TestEntityFactory : EntityFactory { @Spawns("1") fun newType1(data: SpawnData): Entity { val e = Entity() e.position = Point2D(data.x, data.y) e.type = EntityType.TYPE1 return e } @Spawns("2") fun newType2(data: SpawnData): Entity { val e = Entity() e.position = Point2D(data.x, data.y) e.type = EntityType.TYPE2 return e } @Spawns("3") fun newType3(data: SpawnData): Entity { val e = Entity() e.position = Point2D(data.x, data.y) e.type = EntityType.TYPE3 return e } } }
mit
53dfd454fb67df23eb6e1a1cca3f4e18
29.509091
121
0.629806
3.998808
false
true
false
false
industrial-data-space/trusted-connector
ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CertApi.kt
1
16272
/*- * ========================LICENSE_START================================= * ids-webconsole * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.webconsole.api import de.fhg.aisec.ids.api.acme.AcmeClient import de.fhg.aisec.ids.api.acme.AcmeTermsOfService import de.fhg.aisec.ids.api.settings.Settings import de.fhg.aisec.ids.webconsole.api.data.Cert import de.fhg.aisec.ids.webconsole.api.data.Identity import de.fhg.aisec.ids.webconsole.api.helper.ProcessExecutor import io.swagger.annotations.Api import io.swagger.annotations.ApiImplicitParam import io.swagger.annotations.ApiImplicitParams import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiParam import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import io.swagger.annotations.Authorization import org.apache.cxf.jaxrs.ext.multipart.Attachment import org.apache.cxf.jaxrs.ext.multipart.Multipart import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.net.URI import java.net.URISyntaxException import java.nio.charset.StandardCharsets import java.nio.file.FileSystems import java.security.KeyStore import java.security.cert.CertificateFactory import java.security.cert.X509Certificate import java.util.UUID import javax.ws.rs.Consumes import javax.ws.rs.GET import javax.ws.rs.InternalServerErrorException import javax.ws.rs.NotFoundException import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.QueryParam import javax.ws.rs.core.MediaType /** * REST API interface for managing certificates in the connector. * * * The API will be available at http://localhost:8181/cxf/api/v1/certs/<method>. * * @author Hamed Rasifard ([email protected]) </method> */ @Component @Path("/certs") @Api(value = "Identities and Certificates", authorizations = [Authorization(value = "oauth2")]) class CertApi(@Autowired private val settings: Settings) { @Autowired(required = false) private var acmeClient: AcmeClient? = null @GET @ApiOperation(value = "Starts ACME renewal over X509v3 certificates") @Path("acme_renew/{target}") @AuthorizationRequired fun getAcmeCert( @ApiParam(value = "Identifier of the component to renew. Currently, the only valid value is __webconsole__") @PathParam("target") target: String ): Boolean { val config = settings.connectorConfig return if ("webconsole" == target && acmeClient != null) { acmeClient?.renewCertificate( FileSystems.getDefault().getPath("etc", "tls-webconsole"), URI.create(config.acmeServerWebcon), config.acmeDnsWebcon.trim { it <= ' ' }.split("\\s*,\\s*".toRegex()).toTypedArray(), config.acmePortWebcon ) true } else { LOG.warn("ACME renewal for services other than WebConsole is not yet implemented!") false } } @GET @ApiOperation( value = "Retrieves the Terms of Service (tos) of the ACME endpoint", response = AcmeTermsOfService::class ) @Path("acme_tos") @AuthorizationRequired fun getAcmeTermsOfService( @ApiParam(value = "URI to retrieve the TOS from") @QueryParam("uri") uri: String ): AcmeTermsOfService? { return acmeClient?.getTermsOfService(URI.create(uri.trim { it <= ' ' })) } @GET @Path("list_certs") @ApiOperation( value = "List installed certificates from trust store.", notes = "Certificates in this list refer to public keys that are trusted by this connector." ) @ApiResponses( ApiResponse(code = 200, message = "List of certificates"), ApiResponse(code = 500, message = "_Truststore not found_: If no trust store available") ) @Produces( MediaType.APPLICATION_JSON ) @AuthorizationRequired fun listCerts(): List<Cert> { val truststore = getKeystoreFile(settings.connectorConfig.truststoreName) return getKeystoreEntries(truststore) } @GET @Path("list_identities") @ApiOperation( value = "List installed certificates from the private key store.", notes = "Certificates in this list refer to private keys that can be used as identities by the connector." ) @Produces( MediaType.APPLICATION_JSON ) @AuthorizationRequired fun listIdentities(): List<Cert> { val keystoreFile = getKeystoreFile(settings.connectorConfig.keystoreName) return getKeystoreEntries(keystoreFile) } @POST @Path("create_identity") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @AuthorizationRequired fun createIdentity( @ApiParam(value = "Specification of the identity to create a key pair for") spec: Identity ): String { val alias = UUID.randomUUID().toString() try { doGenKeyPair( alias, spec, "RSA", 2048, "SHA1WITHRSA", getKeystoreFile(settings.connectorConfig.keystoreName) ) } catch (e: Exception) { throw InternalServerErrorException(e) } return alias } /** Delete a private/public key pair. */ @POST @Path("delete_identity") @ApiOperation(value = "Deletes a public/private key pair") @Produces(MediaType.APPLICATION_JSON) @AuthorizationRequired fun deleteIdentity(alias: String): String { val keyStoreFile = getKeystoreFile(settings.connectorConfig.keystoreName) val success = delete(alias, keyStoreFile) return if (success) { alias } else { throw InternalServerErrorException() } } /** Deletes a trusted certificate. */ @POST @Path("delete_cert") @ApiOperation(value = "Deletes a trusted certificate") @Produces(MediaType.APPLICATION_JSON) @AuthorizationRequired fun deleteCert(alias: String): String { val keyStoreFile = getKeystoreFile(settings.connectorConfig.keystoreName) val success = delete(alias, keyStoreFile) return if (success) { alias } else { throw InternalServerErrorException() } } @POST @Path("/install_trusted_cert") @ApiOperation(value = "Installs a new trusted public key certificate.") @ApiImplicitParams(ApiImplicitParam(dataType = "java.io.File", name = "attachment", paramType = "formData")) @Produces( MediaType.TEXT_HTML ) @Consumes(MediaType.MULTIPART_FORM_DATA) @AuthorizationRequired @Throws( IOException::class ) fun installTrustedCert( @ApiParam(hidden = true, name = "attachment") @Multipart("upfile") attachment: Attachment ): String { val filename = attachment.contentDisposition.getParameter("filename") val tempPath = File.createTempFile(filename, "cert") FileOutputStream(tempPath).use { out -> attachment.getObject(InputStream::class.java).use { `in` -> var read: Int val bytes = ByteArray(1024) while (`in`.read(bytes).also { read = it } != -1) { out.write(bytes, 0, read) } } } val trustStoreName = settings.connectorConfig.truststoreName val success = storeCert(getKeystoreFile(trustStoreName), tempPath) if (success) { if (!tempPath.delete()) { LOG.warn("Failed to delete temporary file $tempPath") } return "Trusted certificate has been uploaded to $trustStoreName" } return "Error: certificate has NOT been uploaded to $trustStoreName" } /** Stores a certificate in a JKS truststore. */ private fun storeCert(trustStoreFile: File, certFile: File): Boolean { val cf: CertificateFactory val alias = certFile.name.replace(".", "_") return try { cf = CertificateFactory.getInstance("X.509") val certStream = fullStream(certFile.absolutePath) val certs = cf.generateCertificate(certStream) FileInputStream(trustStoreFile).use { fis -> FileOutputStream(trustStoreFile).use { fos -> val keystore = KeyStore.getInstance(KeyStore.getDefaultType()) val password = KEYSTORE_PWD keystore.load(fis, password.toCharArray()) // Add the certificate keystore.setCertificateEntry(alias, certs) keystore.store(fos, password.toCharArray()) } } true } catch (e: Exception) { LOG.error(e.message, e) false } } /** * Retrieve a keystore file. * * * This method will first try to load keystores from Karaf's ./etc dir, then checks if a path * has been given by -Dkeystore.dir=.. and finally just lets the classloader load the file from * classpath. * * * If the file cannot be found, this method returns null. */ private fun getKeystoreFile(fileName: String): File { // If we run in karaf platform, we expect the keystore to be in // KARAF_BASE/etc val etcDir = System.getProperty("karaf.etc") if (etcDir != null) { val f = File(etcDir + File.separator + fileName) if (f.exists()) { return f } } // Otherwise, we allow setting the directory to search for by // -Dkeystore.dir=... val keystoreDir = System.getProperty("keystore.dir") if (keystoreDir != null) { val f = File(keystoreDir + File.separator + fileName) if (f.exists()) { return f } } // In case of unit tests, we expect resources to be "somehow" available in current working dir val f = File(fileName) if (f.exists()) { return f } // Last resort: let the classloader find the file val clFile = Thread.currentThread().contextClassLoader.getResource(fileName) try { if (clFile != null) { return File(clFile.toURI()) } } catch (e: URISyntaxException) { LOG.error(e.message, e) } throw NotFoundException( "Keystore/truststore file could not be found. Cannot continue. Given filename: " + fileName ) } /** Returns all entries (private keys and certificates) from a Java keystore. */ private fun getKeystoreEntries(keystoreFile: File): List<Cert> { val certs: MutableList<Cert> = ArrayList() try { FileInputStream(keystoreFile).use { fis -> val keystore = KeyStore.getInstance(KeyStore.getDefaultType()) keystore.load(fis, KEYSTORE_PWD.toCharArray()) val enumeration = keystore.aliases() while (enumeration.hasMoreElements()) { val alias = enumeration.nextElement() val certificate = keystore.getCertificate(alias) val cert = Cert() cert.alias = alias cert.file = keystoreFile.name.replaceFirst("[.][^.]+$".toRegex(), "") cert.certificate = certificate.toString() if (certificate !is X509Certificate) { continue } cert.subjectAltNames = certificate.subjectAlternativeNames // Get distinguished name val dn = certificate.subjectX500Principal.name for (entry in dn.split(",".toRegex()).toTypedArray()) { val kv = entry.split("=".toRegex()).toTypedArray() if (kv.size < 2) { continue } when (kv[0]) { "CN" -> cert.subjectCN = kv[1] "OU" -> cert.subjectOU = kv[1] "O" -> cert.subjectO = kv[1] "L" -> cert.subjectL = kv[1] "S" -> cert.subjectS = kv[1] "C" -> cert.subjectC = kv[1] else -> { } } } certs.add(cert) } } } catch (e: Exception) { LOG.error(e.message, e) } return certs } /** * We call the keystore binary programmatically. This is portable, in * contrast to creating key pairs and self-signed certificates * programmatically, which depends on internal classes of the JVM, such * as sun.security.* or oracle.*. */ @Suppress("SameParameterValue") @Throws(InterruptedException::class, IOException::class) private fun doGenKeyPair( alias: String, spec: Identity, keyAlgName: String, keySize: Int, sigAlgName: String, keyStoreFile: File ) { val keytoolCmd = arrayOf( "/bin/sh", "-c", "keytool", "-genkey", "-alias", alias, "-keyalg", keyAlgName, "-keysize", keySize.toString(), "-sigalg", sigAlgName, "-keystore", keyStoreFile.absolutePath, "-dname", "CN=" + spec.cn + ", OU=" + spec.ou + ", O=" + spec.o + ", L=" + spec.l + ", S=" + spec.s + ", C=" + spec.c, "-storepass", KEYSTORE_PWD, "-keypass", KEYSTORE_PWD ) val bos = ByteArrayOutputStream() ProcessExecutor().execute(keytoolCmd, bos, bos) LOG.debug("Keytool: {}", bos.toString(StandardCharsets.UTF_8)) } private fun delete(alias: String, file: File): Boolean { try { FileInputStream(file).use { fis -> val keystore = KeyStore.getInstance(KeyStore.getDefaultType()) keystore.load(fis, KEYSTORE_PWD.toCharArray()) if (keystore.containsAlias(alias)) { keystore.deleteEntry(alias) FileOutputStream(file).use { keystore.store(it, KEYSTORE_PWD.toCharArray()) } } else { LOG.warn("Alias not available. Cannot delete it: $alias") } } } catch (e: Exception) { LOG.error(e.message, e) return false } return true } companion object { private val LOG = LoggerFactory.getLogger(CertApi::class.java) private const val KEYSTORE_PWD = "password" @Throws(IOException::class) private fun fullStream(fileName: String): InputStream { DataInputStream(FileInputStream(fileName)).use { dis -> val bytes = dis.readAllBytes() return ByteArrayInputStream(bytes) } } } }
apache-2.0
bf51fd3d4c9c7fcd3579074ba58c3ed8
35.731377
116
0.594211
4.584954
false
false
false
false
newbieandroid/AppBase
app/src/main/java/com/fuyoul/sanwenseller/listener/AppBarStateChangeListener.kt
1
1147
package com.fuyoul.sanwenseller.listener import android.support.design.widget.AppBarLayout /** * @author: chen * @CreatDate: 2017\11\13 0013 * @Desc: */ abstract class AppBarStateChangeListener : AppBarLayout.OnOffsetChangedListener { private var mCurrentState = State.IDLE enum class State { EXPANDED, COLLAPSED, IDLE; } abstract fun onStateChanged(appBarLayout: AppBarLayout?, state: State) override fun onOffsetChanged(appBarLayout: AppBarLayout?, i: Int) { if (i == 0) { if (mCurrentState != State.EXPANDED) { onStateChanged(appBarLayout, State.EXPANDED) } mCurrentState = State.EXPANDED } else if (Math.abs(i) >= appBarLayout!!.getTotalScrollRange()) { if (mCurrentState != State.COLLAPSED) { onStateChanged(appBarLayout, State.COLLAPSED) } mCurrentState = State.COLLAPSED } else { if (mCurrentState != State.IDLE) { onStateChanged(appBarLayout, State.IDLE) } mCurrentState = State.IDLE } } }
apache-2.0
7b80dbb977ea7ca5660de4e5d0d64941
27
81
0.602441
4.965368
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/helloworld/10.FunctionExample.kt
1
1836
package com.zj.example.kotlin.helloworld /** * 函数的声明 * CreateTime: 17/9/6 15:10 * @author 郑炯 */ fun main(args: Array<String>) { //会输出9 println(getDefaultValue()) //会输出say zhengjiong println(say3()) //会输出true println(containEmpty("a", null)) } /** * 函数使用关键字fun声明,如下代码创建了一个名为say()的函数, * 它接受一个String类型的参数,并返回一个String类型的值 */ fun say1(args: String): String { return args } /** * 同时,在 Kotlin 中,如果像这种简单的函数,可以简写. * say1可以这样简写:say2 */ fun say2(args: String): String = args /** * 如果返回值是int类型, 那么你甚至连返回类型都可以不写,如下: */ fun getIntValue(args: Int) = args /** * 函数的默认参数 */ fun getDefaultValue(args: Int = 9) = args /** * 函数的默认参数 * 这时候你可以调用say(),来得到默认的字符串 "say zhengjiong",也可以自己传入参数say("world")来得到传入参数值。 */ fun say3(args: String = "say zhengjiong"): String = args /** * 可变参数 * 同 Java 的变长参数一样,Kotlin 也支持变长参数 * 在Kotlin中,使用关键字vararg来表示 */ fun containEmpty(vararg str: String?): Boolean{ for (s in str) { //s为空的时候会返回true s ?: return true } return false } /** 2.3.4 扩展函数 你可以给父类添加一个方法,这个方法将可以在所有子类中使用 例如,在 Android 开发中,我们常常使用这样的扩展函数: fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, message, duration).show() } 这样,我们就可以在每一个Activity中直接使用toast()函数了。 */
mit
66e5079df5bae2b5017f0f30fe30a0fd
15.21519
79
0.661719
2.55489
false
false
false
false
DreamTeamGDL/SkyNet
SkyNet/app/src/main/java/gdl/dreamteam/skynet/Activities/MainActivity.kt
1
3924
package gdl.dreamteam.skynet.Activities import android.content.Intent import android.databinding.DataBindingUtil import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.util.Patterns import android.view.View import android.widget.Button import android.widget.ProgressBar import gdl.dreamteam.skynet.Bindings.LoginBinding import gdl.dreamteam.skynet.Exceptions.ForbiddenException import gdl.dreamteam.skynet.Exceptions.InternalErrorException import gdl.dreamteam.skynet.Exceptions.UnauthorizedException import gdl.dreamteam.skynet.Extensions.longToast import gdl.dreamteam.skynet.Extensions.shortToast import gdl.dreamteam.skynet.Models.* import gdl.dreamteam.skynet.Others.IDataRepository import gdl.dreamteam.skynet.Others.LoginService import gdl.dreamteam.skynet.Others.RestRepository import gdl.dreamteam.skynet.R import gdl.dreamteam.skynet.databinding.MainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: MainBinding private lateinit var dataRepository: IDataRepository private lateinit var progressBar: ProgressBar private lateinit var loginButton: Button private val uiThread = Handler(Looper.getMainLooper()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) dataRepository = RestRepository() binding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.login = LoginBinding() progressBar = findViewById(R.id.progressBar) as ProgressBar loginButton = findViewById(R.id.loginButton) as Button } private fun parseZone(zone: Zone?) { val intent = Intent(this, ClientsActivity::class.java) val rawZone = RestRepository.gson.toJson(zone, Zone::class.java) intent.putExtra("zone", rawZone) uiThread.post { loginButton.isEnabled = true progressBar.visibility = View.INVISIBLE startActivity(intent) } } private fun validateForm(username: String?, password: String?): Boolean { if (username == "" || username == null) { longToast("Please put a username") return false } if (!Patterns.EMAIL_ADDRESS.matcher(username).matches()) { longToast("Invalid email address") return false } if (password == "" || password == null) { longToast("Please put a password") return false } return true } private fun handleExceptions(throwable: Throwable) { Log.wtf("Exception", throwable.cause.toString()) when(throwable.cause) { is UnauthorizedException, is ForbiddenException -> { uiThread.post { shortToast("Please introduce valid credentials") } } is InternalErrorException -> { uiThread.post { shortToast("Uups, that was a server error, try again in a few moments") } } } uiThread.post { loginButton.isEnabled = true progressBar.visibility = View.INVISIBLE } } fun onLoginPress(view: View) { val username: String? = binding.login.username val password: String? = binding.login.password if (!validateForm(username, password)) return LoginService.setup(applicationContext) progressBar.visibility = View.VISIBLE loginButton.isEnabled = false LoginService.login( username as String, password as String ) .thenApply { dataRepository.getZone("livingroom").get() } .thenApply { zone -> parseZone(zone)} .exceptionally { throwable -> handleExceptions(throwable)} } }
mit
fcf15b136a83a859eb637763ad188c58
35.333333
91
0.675841
4.744861
false
false
false
false
DVT/showcase-android
app/src/main/kotlin/za/co/dvt/android/showcase/repository/impl/FirebaseTrackingRepository.kt
1
2807
package za.co.dvt.android.showcase.repository.impl import android.os.Bundle import com.google.firebase.analytics.FirebaseAnalytics import za.co.dvt.android.showcase.model.AppModel import za.co.dvt.android.showcase.model.Office import za.co.dvt.android.showcase.repository.TrackingRepository /** * @author rebeccafranks * * * @since 2017/06/24. */ class FirebaseTrackingRepository(val firebaseAnalytics: FirebaseAnalytics) : TrackingRepository { private val APP_NAME_PARAM = "app_name" private val CLIENT_PARAM = "client" private val OFFICE_NAME_PARAM = "office_name" private val ERROR_MSG_PARAM = "error_msg" override fun trackInstallAppClicked(app: AppModel) { val bundle = Bundle() bundle.putString(APP_NAME_PARAM, app.name) firebaseAnalytics.logEvent("click_app_install", bundle) } override fun trackEmailOffice(office: Office) { val bundle = Bundle() bundle.putString(OFFICE_NAME_PARAM, office.name) firebaseAnalytics.logEvent("click_email_office", bundle) } override fun trackCallOffice(office: Office) { val bundle = Bundle() bundle.putString(OFFICE_NAME_PARAM, office.name) firebaseAnalytics.logEvent("click_call_office", bundle) } override fun trackNavigationOffice(office: Office) { val bundle = Bundle() bundle.putString(OFFICE_NAME_PARAM, office.name) firebaseAnalytics.logEvent("click_navigate_office", bundle) } override fun trackOpenWebsite() { firebaseAnalytics.logEvent("view_website", null) } override fun trackOpenTwitter() { firebaseAnalytics.logEvent("view_twitter", null) } override fun trackOpenFacebook() { firebaseAnalytics.logEvent("view_facebook", null) } override fun trackViewUserLogin() { firebaseAnalytics.logEvent("view_login", null) } override fun trackViewListApps() { firebaseAnalytics.logEvent("view_list_apps", null) } override fun trackViewAppDetail(appModel: AppModel) { val bundle = Bundle() bundle.putString(APP_NAME_PARAM, appModel.name) bundle.putString(CLIENT_PARAM, appModel.client) firebaseAnalytics.logEvent("view_app", bundle) } override fun trackViewContactUs() { firebaseAnalytics.logEvent("view_contact_us", null) } override fun trackViewAboutCompany() { firebaseAnalytics.logEvent("view_about_company", null) } override fun trackUserLoginSuccess() { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, null) } override fun trackUserLoginFailed(message: String?) { val bundle = Bundle() bundle.putString(ERROR_MSG_PARAM, message) firebaseAnalytics.logEvent("login_failed", bundle) } }
apache-2.0
e59fad573cb10a3741810cb22cb07c38
30.188889
97
0.692911
4.298622
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/view/datepicker/view/MyDatePicker.kt
1
7122
package at.cpickl.gadsu.view.datepicker.view import at.cpickl.gadsu.global.GadsuException import at.cpickl.gadsu.global.IS_OS_WIN import at.cpickl.gadsu.service.LOGUI import at.cpickl.gadsu.service.clearTime import at.cpickl.gadsu.service.formatDate import at.cpickl.gadsu.service.parseDate import at.cpickl.gadsu.service.toDateTime import at.cpickl.gadsu.view.components.panels.GridPanel import at.cpickl.gadsu.view.currentActiveJFrame import at.cpickl.gadsu.view.datepicker.UtilDateModel import at.cpickl.gadsu.view.logic.beep import at.cpickl.gadsu.view.swing.ClosableWindow import at.cpickl.gadsu.view.swing.Pad import at.cpickl.gadsu.view.swing.changeBackgroundForASec import at.cpickl.gadsu.view.swing.emptyBorderForDialogs import at.cpickl.gadsu.view.swing.registerCloseOnEscapeOrShortcutW import at.cpickl.gadsu.view.swing.transparent import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.awt.Color import java.awt.GridBagConstraints import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.Date import javax.swing.JButton import javax.swing.JDialog import javax.swing.JFormattedTextField import javax.swing.JTextField import javax.swing.SwingUtilities ///** // * @param navigateToDate defaults to current date // * @param preselectDate if true sets the textfield to the date (just as would have been selected manually) // */ //fun SwingFactory.newDatePicker(buttonViewName: String, // panelViewName: String, // textViewName: String, // navigateToDate: DateTime? = null //) = MyDatePicker.build(navigateToDate ?: clock.now(), buttonViewName, panelViewName, textViewName) class MyDatePicker(viewNamePrefix: String, panel: JDatePanel, val dateModel: UtilDateModel, formatter: JFormattedTextField.AbstractFormatter, textFieldAlignment: Int = JTextField.LEFT) : JDatePicker(panel, formatter) { companion object { private val LOG = LoggerFactory.getLogger(MyDatePicker::class.java) private val VIEWNAME_BUTTON_SUFFIX = ".OpenButton" private val VIEWNAME_TEXTFIELD_SUFFIX = ".TextField" private val VIEWNAME_PICKER_PANEL_SUFFIX = ".PickerPanel" private val VIEWNAME_POPUP_PANEL_SUFFIX = ".PopupPanel" fun viewNameButton(prefix: String) = prefix + VIEWNAME_BUTTON_SUFFIX fun viewNameText(prefix: String) = prefix + VIEWNAME_TEXTFIELD_SUFFIX fun viewNamePickerPanel(prefix: String) = prefix + VIEWNAME_PICKER_PANEL_SUFFIX fun viewNamePopupPanel(prefix: String) = prefix + VIEWNAME_POPUP_PANEL_SUFFIX fun build(initDate: DateTime?, viewNamePrefix: String, textFieldAlignment: Int = JTextField.LEFT): MyDatePicker { LOG.trace("build(initDate={}, ..)", initDate) val dateModel = UtilDateModel() // joda uses 1-12, java date uses 0-11 if (initDate != null) { dateModel.setDate(initDate.year, initDate.monthOfYear - 1, initDate.dayOfMonth) dateModel.isSelected = true // enter date in textfield by default } val panel = JDatePanel(dateModel) panel.name = viewNamePopupPanel(viewNamePrefix) return MyDatePicker(viewNamePrefix, panel, dateModel, DatePickerFormatter(), textFieldAlignment) } } private val log = LOGUI(javaClass, viewNamePrefix) init { name = viewNamePickerPanel(viewNamePrefix) transparent() button.name = viewNameButton(viewNamePrefix) formattedTextField.isFocusable = false formattedTextField.columns = if (IS_OS_WIN) 9 else 7 formattedTextField.horizontalAlignment = textFieldAlignment formattedTextField.name = viewNameText(viewNamePrefix) formattedTextField.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { log.trace("textfield clicked; displaying dialog to enter date manually via keyboard.") SwingUtilities.invokeLater { EnterDateByKeyboardDialog({ dateModel.value = it.toDate() }, dateModel.value?.toDateTime()).isVisible = true } } }) addChangeListener { log.trace("Value changed to (via textfield text listening): {}", selectedDate()) } } fun changeDate(newValue: DateTime?) { log.trace("changeDate(newValue={})", newValue) dateModel.value = newValue?.toDate() } fun selectedDate(): DateTime? { if (dateModel.value == null) { log.trace("Current datepicker value is not a date but: {}", dateModel.value?.javaClass?.name) return null } if (dateModel.value !is Date) { throw GadsuException("Expected the datepicker model value to be of type Date, but was: ${dateModel.value?.javaClass?.name}") } return DateTime(dateModel.value).clearTime() } fun addChangeListener(function: () -> Unit) { // so, after the popup opened, and something is selected, it is for sure the formatted textfield value has changed, so rely on that formattedTextField.addPropertyChangeListener("value", { function() }) } /** * Make it non nullable, if initial date was not null from beginning */ fun disableClear() { log.trace("disableClear()") datePanel.disableClear() } } private class EnterDateByKeyboardDialog( private val onSuccess: (DateTime) -> Unit, initialDate: DateTime? = null ) : JDialog(currentActiveJFrame(), "Datum eingeben", true), ClosableWindow { private val inpText = JTextField(10) init { registerCloseOnEscapeOrShortcutW() val panel = GridPanel() panel.emptyBorderForDialogs() inpText.addActionListener { confirmInput() } inpText.toolTipText = "Format: TT.MM.JJJJ"//DateFormats.DATE if (initialDate != null) { inpText.text = initialDate.formatDate() } else { inpText.text = "31.12.1985" inpText.requestFocus() inpText.selectAll() } val btnOkay = JButton("Okay") btnOkay.addActionListener { confirmInput() } with(panel) { c.weightx = 1.0 c.fill = GridBagConstraints.HORIZONTAL panel.add(inpText) c.weightx = 0.0 c.fill = GridBagConstraints.NONE c.gridx++ c.insets = Pad.LEFT panel.add(btnOkay) } add(panel) pack() setLocationRelativeTo(parent) isResizable = false } private fun confirmInput() { try { val dateEntered = inpText.text.parseDate() dispose() onSuccess(dateEntered) } catch (e: IllegalArgumentException) { inpText.changeBackgroundForASec(Color.RED) beep() } } override fun closeWindow() { dispose() } }
apache-2.0
09af848c2c35257ac249ce51e7c59772
34.969697
155
0.655574
4.44292
false
false
false
false
cypressious/learning-spaces
app/src/main/java/de/maxvogler/learningspaces/helpers/SequenceHelpers.kt
1
1007
package de.maxvogler.learningspaces.helpers import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Adapter import java.util.* fun Menu.itemsSequence(): Sequence<MenuItem> = MenuItemsSequence(this) private class MenuItemsSequence(private val menu: Menu) : Sequence<MenuItem> { override fun iterator(): Iterator<MenuItem> { return IndexBasedIterator(count = { menu.size() }, getItem = { menu.getItem(it) }) } } private class IndexBasedIterator<O>( private val count: () -> Int, private val getItem: (Int) -> O ) : Iterator<O> { private var index = 0 private val initialCount = count() override fun next(): O { if (!hasNext()) { throw NoSuchElementException() } return getItem(index++) } override fun hasNext(): Boolean { if (initialCount != count()) { throw ConcurrentModificationException() } return index < initialCount } }
gpl-2.0
6b13575825fff3f999c360069e7ef78d
24.175
90
0.648461
4.359307
false
false
false
false
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/features/bookmarks/list/BookmarkDiffUtilCallback.kt
1
727
package de.ph1b.audiobook.features.bookmarks.list import androidx.recyclerview.widget.DiffUtil import de.ph1b.audiobook.data.Bookmark2 /** * Calculates the diff between two bookmark lists. */ class BookmarkDiffUtilCallback( private val oldItems: List<Bookmark2>, private val newItems: List<Bookmark2> ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItems[oldItemPosition] == newItems[newItemPosition] } override fun getOldListSize() = oldItems.size override fun getNewListSize() = newItems.size override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = areItemsTheSame(oldItemPosition, newItemPosition) }
lgpl-3.0
97468f8dab23da651b1e25312658fc3a
29.291667
85
0.782669
4.660256
false
false
false
false
ze-pequeno/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/internal/http2/Http2Reader.kt
2
19929
/* * Copyright (C) 2011 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 okhttp3.internal.http2 import java.io.Closeable import java.io.EOFException import java.io.IOException import java.util.logging.Level.FINE import java.util.logging.Logger import okhttp3.internal.and import okhttp3.internal.format import okhttp3.internal.http2.Http2.CONNECTION_PREFACE import okhttp3.internal.http2.Http2.FLAG_ACK import okhttp3.internal.http2.Http2.FLAG_COMPRESSED import okhttp3.internal.http2.Http2.FLAG_END_HEADERS import okhttp3.internal.http2.Http2.FLAG_END_STREAM import okhttp3.internal.http2.Http2.FLAG_PADDED import okhttp3.internal.http2.Http2.FLAG_PRIORITY import okhttp3.internal.http2.Http2.INITIAL_MAX_FRAME_SIZE import okhttp3.internal.http2.Http2.TYPE_CONTINUATION import okhttp3.internal.http2.Http2.TYPE_DATA import okhttp3.internal.http2.Http2.TYPE_GOAWAY import okhttp3.internal.http2.Http2.TYPE_HEADERS import okhttp3.internal.http2.Http2.TYPE_PING import okhttp3.internal.http2.Http2.TYPE_PRIORITY import okhttp3.internal.http2.Http2.TYPE_PUSH_PROMISE import okhttp3.internal.http2.Http2.TYPE_RST_STREAM import okhttp3.internal.http2.Http2.TYPE_SETTINGS import okhttp3.internal.http2.Http2.TYPE_WINDOW_UPDATE import okhttp3.internal.http2.Http2.formattedType import okhttp3.internal.http2.Http2.frameLog import okhttp3.internal.http2.Http2.frameLogWindowUpdate import okhttp3.internal.readMedium import okio.Buffer import okio.BufferedSource import okio.ByteString import okio.Source import okio.Timeout /** * Reads HTTP/2 transport frames. * * This implementation assumes we do not send an increased [frame][Settings.getMaxFrameSize] to the * peer. Hence, we expect all frames to have a max length of [Http2.INITIAL_MAX_FRAME_SIZE]. */ class Http2Reader( /** Creates a frame reader with max header table size of 4096. */ private val source: BufferedSource, private val client: Boolean ) : Closeable { private val continuation: ContinuationSource = ContinuationSource(this.source) private val hpackReader: Hpack.Reader = Hpack.Reader( source = continuation, headerTableSizeSetting = 4096 ) @Throws(IOException::class) fun readConnectionPreface(handler: Handler) { if (client) { // The client reads the initial SETTINGS frame. if (!nextFrame(true, handler)) { throw IOException("Required SETTINGS preface not received") } } else { // The server reads the CONNECTION_PREFACE byte string. val connectionPreface = source.readByteString(CONNECTION_PREFACE.size.toLong()) if (logger.isLoggable(FINE)) logger.fine(format("<< CONNECTION ${connectionPreface.hex()}")) if (CONNECTION_PREFACE != connectionPreface) { throw IOException("Expected a connection header but was ${connectionPreface.utf8()}") } } } @Throws(IOException::class) fun nextFrame(requireSettings: Boolean, handler: Handler): Boolean { try { source.require(9) // Frame header size. } catch (e: EOFException) { return false // This might be a normal socket close. } // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Length (24) | // +---------------+---------------+---------------+ // | Type (8) | Flags (8) | // +-+-+-----------+---------------+-------------------------------+ // |R| Stream Identifier (31) | // +=+=============================================================+ // | Frame Payload (0...) ... // +---------------------------------------------------------------+ val length = source.readMedium() if (length > INITIAL_MAX_FRAME_SIZE) { throw IOException("FRAME_SIZE_ERROR: $length") } val type = source.readByte() and 0xff val flags = source.readByte() and 0xff val streamId = source.readInt() and 0x7fffffff // Ignore reserved bit. if (type != TYPE_WINDOW_UPDATE && logger.isLoggable(FINE)) { logger.fine(frameLog(true, streamId, length, type, flags)) } if (requireSettings && type != TYPE_SETTINGS) { throw IOException("Expected a SETTINGS frame but was ${formattedType(type)}") } when (type) { TYPE_DATA -> readData(handler, length, flags, streamId) TYPE_HEADERS -> readHeaders(handler, length, flags, streamId) TYPE_PRIORITY -> readPriority(handler, length, flags, streamId) TYPE_RST_STREAM -> readRstStream(handler, length, flags, streamId) TYPE_SETTINGS -> readSettings(handler, length, flags, streamId) TYPE_PUSH_PROMISE -> readPushPromise(handler, length, flags, streamId) TYPE_PING -> readPing(handler, length, flags, streamId) TYPE_GOAWAY -> readGoAway(handler, length, flags, streamId) TYPE_WINDOW_UPDATE -> readWindowUpdate(handler, length, flags, streamId) else -> source.skip(length.toLong()) // Implementations MUST discard frames of unknown types. } return true } @Throws(IOException::class) private fun readHeaders(handler: Handler, length: Int, flags: Int, streamId: Int) { if (streamId == 0) throw IOException("PROTOCOL_ERROR: TYPE_HEADERS streamId == 0") val endStream = (flags and FLAG_END_STREAM) != 0 val padding = if (flags and FLAG_PADDED != 0) source.readByte() and 0xff else 0 var headerBlockLength = length if (flags and FLAG_PRIORITY != 0) { readPriority(handler, streamId) headerBlockLength -= 5 // account for above read. } headerBlockLength = lengthWithoutPadding(headerBlockLength, flags, padding) val headerBlock = readHeaderBlock(headerBlockLength, padding, flags, streamId) handler.headers(endStream, streamId, -1, headerBlock) } @Throws(IOException::class) private fun readHeaderBlock(length: Int, padding: Int, flags: Int, streamId: Int): List<Header> { continuation.left = length continuation.length = continuation.left continuation.padding = padding continuation.flags = flags continuation.streamId = streamId // TODO: Concat multi-value headers with 0x0, except COOKIE, which uses 0x3B, 0x20. // http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-8.1.2.5 hpackReader.readHeaders() return hpackReader.getAndResetHeaderList() } @Throws(IOException::class) private fun readData(handler: Handler, length: Int, flags: Int, streamId: Int) { if (streamId == 0) throw IOException("PROTOCOL_ERROR: TYPE_DATA streamId == 0") // TODO: checkState open or half-closed (local) or raise STREAM_CLOSED val inFinished = flags and FLAG_END_STREAM != 0 val gzipped = flags and FLAG_COMPRESSED != 0 if (gzipped) { throw IOException("PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA") } val padding = if (flags and FLAG_PADDED != 0) source.readByte() and 0xff else 0 val dataLength = lengthWithoutPadding(length, flags, padding) handler.data(inFinished, streamId, source, dataLength) source.skip(padding.toLong()) } @Throws(IOException::class) private fun readPriority(handler: Handler, length: Int, flags: Int, streamId: Int) { if (length != 5) throw IOException("TYPE_PRIORITY length: $length != 5") if (streamId == 0) throw IOException("TYPE_PRIORITY streamId == 0") readPriority(handler, streamId) } @Throws(IOException::class) private fun readPriority(handler: Handler, streamId: Int) { val w1 = source.readInt() val exclusive = w1 and 0x80000000.toInt() != 0 val streamDependency = w1 and 0x7fffffff val weight = (source.readByte() and 0xff) + 1 handler.priority(streamId, streamDependency, weight, exclusive) } @Throws(IOException::class) private fun readRstStream(handler: Handler, length: Int, flags: Int, streamId: Int) { if (length != 4) throw IOException("TYPE_RST_STREAM length: $length != 4") if (streamId == 0) throw IOException("TYPE_RST_STREAM streamId == 0") val errorCodeInt = source.readInt() val errorCode = ErrorCode.fromHttp2(errorCodeInt) ?: throw IOException( "TYPE_RST_STREAM unexpected error code: $errorCodeInt") handler.rstStream(streamId, errorCode) } @Throws(IOException::class) private fun readSettings(handler: Handler, length: Int, flags: Int, streamId: Int) { if (streamId != 0) throw IOException("TYPE_SETTINGS streamId != 0") if (flags and FLAG_ACK != 0) { if (length != 0) throw IOException("FRAME_SIZE_ERROR ack frame should be empty!") handler.ackSettings() return } if (length % 6 != 0) throw IOException("TYPE_SETTINGS length % 6 != 0: $length") val settings = Settings() for (i in 0 until length step 6) { var id = source.readShort() and 0xffff val value = source.readInt() when (id) { // SETTINGS_HEADER_TABLE_SIZE 1 -> { } // SETTINGS_ENABLE_PUSH 2 -> { if (value != 0 && value != 1) { throw IOException("PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1") } } // SETTINGS_MAX_CONCURRENT_STREAMS 3 -> id = 4 // Renumbered in draft 10. // SETTINGS_INITIAL_WINDOW_SIZE 4 -> { id = 7 // Renumbered in draft 10. if (value < 0) { throw IOException("PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1") } } // SETTINGS_MAX_FRAME_SIZE 5 -> { if (value < INITIAL_MAX_FRAME_SIZE || value > 16777215) { throw IOException("PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: $value") } } // SETTINGS_MAX_HEADER_LIST_SIZE 6 -> { // Advisory only, so ignored. } // Must ignore setting with unknown id. else -> { } } settings[id] = value } handler.settings(false, settings) } @Throws(IOException::class) private fun readPushPromise(handler: Handler, length: Int, flags: Int, streamId: Int) { if (streamId == 0) { throw IOException("PROTOCOL_ERROR: TYPE_PUSH_PROMISE streamId == 0") } val padding = if (flags and FLAG_PADDED != 0) source.readByte() and 0xff else 0 val promisedStreamId = source.readInt() and 0x7fffffff val headerBlockLength = lengthWithoutPadding(length - 4, flags, padding) // - 4 for readInt(). val headerBlock = readHeaderBlock(headerBlockLength, padding, flags, streamId) handler.pushPromise(streamId, promisedStreamId, headerBlock) } @Throws(IOException::class) private fun readPing(handler: Handler, length: Int, flags: Int, streamId: Int) { if (length != 8) throw IOException("TYPE_PING length != 8: $length") if (streamId != 0) throw IOException("TYPE_PING streamId != 0") val payload1 = source.readInt() val payload2 = source.readInt() val ack = flags and FLAG_ACK != 0 handler.ping(ack, payload1, payload2) } @Throws(IOException::class) private fun readGoAway(handler: Handler, length: Int, flags: Int, streamId: Int) { if (length < 8) throw IOException("TYPE_GOAWAY length < 8: $length") if (streamId != 0) throw IOException("TYPE_GOAWAY streamId != 0") val lastStreamId = source.readInt() val errorCodeInt = source.readInt() val opaqueDataLength = length - 8 val errorCode = ErrorCode.fromHttp2(errorCodeInt) ?: throw IOException( "TYPE_GOAWAY unexpected error code: $errorCodeInt") var debugData = ByteString.EMPTY if (opaqueDataLength > 0) { // Must read debug data in order to not corrupt the connection. debugData = source.readByteString(opaqueDataLength.toLong()) } handler.goAway(lastStreamId, errorCode, debugData) } /** Unlike other `readXxx()` functions, this one must log the frame before returning. */ @Throws(IOException::class) private fun readWindowUpdate(handler: Handler, length: Int, flags: Int, streamId: Int) { val increment: Long try { if (length != 4) throw IOException("TYPE_WINDOW_UPDATE length !=4: $length") increment = source.readInt() and 0x7fffffffL if (increment == 0L) throw IOException("windowSizeIncrement was 0") } catch (e: Exception) { logger.fine(frameLog(true, streamId, length, TYPE_WINDOW_UPDATE, flags)) throw e } if (logger.isLoggable(FINE)) { logger.fine(frameLogWindowUpdate( inbound = true, streamId = streamId, length = length, windowSizeIncrement = increment, )) } handler.windowUpdate(streamId, increment) } @Throws(IOException::class) override fun close() { source.close() } /** * Decompression of the header block occurs above the framing layer. This class lazily reads * continuation frames as they are needed by [Hpack.Reader.readHeaders]. */ internal class ContinuationSource( private val source: BufferedSource ) : Source { var length: Int = 0 var flags: Int = 0 var streamId: Int = 0 var left: Int = 0 var padding: Int = 0 @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { while (left == 0) { source.skip(padding.toLong()) padding = 0 if (flags and FLAG_END_HEADERS != 0) return -1L readContinuationHeader() // TODO: test case for empty continuation header? } val read = source.read(sink, minOf(byteCount, left.toLong())) if (read == -1L) return -1L left -= read.toInt() return read } override fun timeout(): Timeout = source.timeout() @Throws(IOException::class) override fun close() { } @Throws(IOException::class) private fun readContinuationHeader() { val previousStreamId = streamId left = source.readMedium() length = left val type = source.readByte() and 0xff flags = source.readByte() and 0xff if (logger.isLoggable(FINE)) logger.fine(frameLog(true, streamId, length, type, flags)) streamId = source.readInt() and 0x7fffffff if (type != TYPE_CONTINUATION) throw IOException("$type != TYPE_CONTINUATION") if (streamId != previousStreamId) throw IOException("TYPE_CONTINUATION streamId changed") } } interface Handler { @Throws(IOException::class) fun data(inFinished: Boolean, streamId: Int, source: BufferedSource, length: Int) /** * Create or update incoming headers, creating the corresponding streams if necessary. Frames * that trigger this are HEADERS and PUSH_PROMISE. * * @param inFinished true if the sender will not send further frames. * @param streamId the stream owning these headers. * @param associatedStreamId the stream that triggered the sender to create this stream. */ fun headers( inFinished: Boolean, streamId: Int, associatedStreamId: Int, headerBlock: List<Header> ) fun rstStream(streamId: Int, errorCode: ErrorCode) fun settings(clearPrevious: Boolean, settings: Settings) /** HTTP/2 only. */ fun ackSettings() /** * Read a connection-level ping from the peer. `ack` indicates this is a reply. The data * in `payload1` and `payload2` opaque binary, and there are no rules on the content. */ fun ping( ack: Boolean, payload1: Int, payload2: Int ) /** * The peer tells us to stop creating streams. It is safe to replay streams with * `ID > lastGoodStreamId` on a new connection. In- flight streams with * `ID <= lastGoodStreamId` can only be replayed on a new connection if they are idempotent. * * @param lastGoodStreamId the last stream ID the peer processed before sending this message. If * [lastGoodStreamId] is zero, the peer processed no frames. * @param errorCode reason for closing the connection. * @param debugData only valid for HTTP/2; opaque debug data to send. */ fun goAway( lastGoodStreamId: Int, errorCode: ErrorCode, debugData: ByteString ) /** * Notifies that an additional `windowSizeIncrement` bytes can be sent on `streamId`, or the * connection if `streamId` is zero. */ fun windowUpdate( streamId: Int, windowSizeIncrement: Long ) /** * Called when reading a headers or priority frame. This may be used to change the stream's * weight from the default (16) to a new value. * * @param streamId stream which has a priority change. * @param streamDependency the stream ID this stream is dependent on. * @param weight relative proportion of priority in `[1..256]`. * @param exclusive inserts this stream ID as the sole child of `streamDependency`. */ fun priority( streamId: Int, streamDependency: Int, weight: Int, exclusive: Boolean ) /** * HTTP/2 only. Receive a push promise header block. * * A push promise contains all the headers that pertain to a server-initiated request, and a * `promisedStreamId` to which response frames will be delivered. Push promise frames are sent * as a part of the response to `streamId`. * * @param streamId client-initiated stream ID. Must be an odd number. * @param promisedStreamId server-initiated stream ID. Must be an even number. * @param requestHeaders minimally includes `:method`, `:scheme`, `:authority`, and `:path`. */ @Throws(IOException::class) fun pushPromise( streamId: Int, promisedStreamId: Int, requestHeaders: List<Header> ) /** * HTTP/2 only. Expresses that resources for the connection or a client- initiated stream are * available from a different network location or protocol configuration. * * See [alt-svc][alt_svc]. * * [alt_svc]: http://tools.ietf.org/html/draft-ietf-httpbis-alt-svc-01 * * @param streamId when a client-initiated stream ID (odd number), the origin of this alternate * service is the origin of the stream. When zero, the origin is specified in the `origin` * parameter. * @param origin when present, the [origin](http://tools.ietf.org/html/rfc6454) is typically * represented as a combination of scheme, host and port. When empty, the origin is that of * the `streamId`. * @param protocol an ALPN protocol, such as `h2`. * @param host an IP address or hostname. * @param port the IP port associated with the service. * @param maxAge time in seconds that this alternative is considered fresh. */ fun alternateService( streamId: Int, origin: String, protocol: ByteString, host: String, port: Int, maxAge: Long ) } companion object { val logger: Logger = Logger.getLogger(Http2::class.java.name) @Throws(IOException::class) fun lengthWithoutPadding(length: Int, flags: Int, padding: Int): Int { var result = length if (flags and FLAG_PADDED != 0) result-- // Account for reading the padding length. if (padding > result) { throw IOException("PROTOCOL_ERROR padding $padding > remaining length $result") } result -= padding return result } } }
apache-2.0
d1750d0e132b3f683e2af68d90cd8c3b
36.815939
100
0.657534
4.109072
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/cargo/toolchain/impl/CargoMetadata.kt
1
6782
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain.impl import com.google.gson.Gson import com.google.gson.JsonObject import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtil import org.rust.cargo.project.workspace.CargoWorkspace.TargetKind import org.rust.cargo.project.workspace.CargoWorkspaceData import org.rust.cargo.project.workspace.PackageId import org.rust.cargo.project.workspace.PackageOrigin import org.rust.openapiext.findFileByMaybeRelativePath /** * Classes mirroring JSON output of `cargo metadata`. * Attribute names and snake_case are crucial. * * Some information available in JSON is not represented here */ object CargoMetadata { data class Project( /** * All packages, including dependencies */ val packages: List<Package>, /** * A graph of dependencies */ val resolve: Resolve, /** * Version of the format (currently 1) */ val version: Int, /** * Ids of packages that are members of the cargo workspace */ val workspace_members: List<String>?, /** * Path to workspace root folder. Can be null for old cargo version */ // BACKCOMPAT: Rust 1.23: use not nullable type here val workspace_root: String? ) data class Package( val name: String, /** * SemVer version */ val version: String, /** * Where did this package comes from? Local file system, crates.io, github repository. * * Will be `null` for the root package and path dependencies. */ val source: String?, /** * A unique id. * There may be several packages with the same name, but different version/source. * The triple (name, version, source) is unique. */ val id: PackageId, /** * Path to Cargo.toml */ val manifest_path: String, /** * Artifacts that can be build from this package. * This is a list of crates that can be build from the package. */ val targets: List<Target> ) data class Target( /** * Kind of a target. Can be a singleton list ["bin"], * ["example], ["test"], ["example"], ["custom-build"], ["bench"]. * * Can also be a list of one or more of "lib", "rlib", "dylib", "staticlib" */ val kind: List<String>, /** * Name */ val name: String, /** * Path to the root module of the crate (aka crate root) */ val src_path: String, /** * List of crate types * * See [linkage](https://doc.rust-lang.org/reference/linkage.html) */ val crate_types: List<String> ) { val cleanKind: TargetKind get() = when (kind.singleOrNull()) { "bin" -> TargetKind.BIN "example" -> TargetKind.EXAMPLE "test" -> TargetKind.TEST "bench" -> TargetKind.BENCH "proc-macro" -> TargetKind.LIB else -> if (kind.any { it.endsWith("lib") }) TargetKind.LIB else TargetKind.UNKNOWN } val cleanCrateTypes: List<CrateType> get() = crate_types.map { when (it) { "bin" -> CrateType.BIN "lib" -> CrateType.LIB "dylib" -> CrateType.DYLIB "staticlib" -> CrateType.STATICLIB "cdylib" -> CrateType.CDYLIB "rlib" -> CrateType.RLIB "proc-macro" -> CrateType.PROC_MACRO else -> CrateType.UNKNOWN } } } /** * Represents possible variants of generated artifact binary * corresponded to `--crate-type` compiler attribute * * See [linkage](https://doc.rust-lang.org/reference/linkage.html) */ enum class CrateType { BIN, LIB, DYLIB, STATICLIB, CDYLIB, RLIB, PROC_MACRO, UNKNOWN } /** * A rooted graph of dependencies, represented as adjacency list */ data class Resolve( val nodes: List<ResolveNode> ) data class ResolveNode( val id: PackageId, /** * id's of dependent packages */ val dependencies: List<PackageId> ) // The next two things do not belong here, // see `machine_message` in Cargo. data class Artifact( val target: Target, val profile: Profile, val filenames: List<String> ) { companion object { fun fromJson(json: JsonObject): Artifact? { if (json.getAsJsonPrimitive("reason").asString != "compiler-artifact") { return null } return Gson().fromJson(json, Artifact::class.java) } } } data class Profile( val test: Boolean ) fun clean(project: Project): CargoWorkspaceData { val fs = LocalFileSystem.getInstance() val members = project.workspace_members ?: error("No `members` key in the `cargo metadata` output.\n" + "Your version of Cargo is no longer supported, please upgrade Cargo.") return CargoWorkspaceData( project.packages.mapNotNull { it.clean(fs, it.id in members) }, project.resolve.nodes.associate { (id, dependencies) -> id to dependencies.toSet() }, project.workspace_root ) } private fun Package.clean(fs: LocalFileSystem, isWorkspaceMember: Boolean): CargoWorkspaceData.Package? { val root = checkNotNull(fs.refreshAndFindFileByPath(PathUtil.getParentPath(manifest_path))) { "`cargo metadata` reported a package which does not exist at `$manifest_path`" } return CargoWorkspaceData.Package( id, root.url, name, version, targets.mapNotNull { it.clean(root) }, source, origin = if (isWorkspaceMember) PackageOrigin.WORKSPACE else PackageOrigin.TRANSITIVE_DEPENDENCY ) } private fun Target.clean(root: VirtualFile): CargoWorkspaceData.Target? { val mainFile = root.findFileByMaybeRelativePath(src_path) return mainFile?.let { CargoWorkspaceData.Target(it.url, name, cleanKind) } } }
mit
b70de855b71f9b01f31e6bcec3332279
28.615721
109
0.557653
4.645205
false
false
false
false
sensefly-sa/dynamodb-to-s3
src/main/kotlin/io/sensefly/dynamodbtos3/commandline/BackupCommand.kt
1
2148
package io.sensefly.dynamodbtos3.commandline import com.beust.jcommander.Parameter import com.beust.jcommander.ParameterException import com.beust.jcommander.Parameters import io.sensefly.dynamodbtos3.BackupTable @Parameters(commandDescription = "Backup DynamoDB tables to S3 bucket.") class BackupCommand { @Parameter(names = ["-t", "--table"], description = "Table to backup to S3. Comma-separated list to backup multiple tables or repeat this param.", required = true, order = 0) var tables: List<String> = arrayListOf() @Parameter(names = ["-b", "--bucket"], description = "Destination S3 bucket.", required = true, order = 1) var bucket: String = "" @Parameter(names = ["-c", "--cron"], description = "Cron pattern. (http://www.manpagez.com/man/5/crontab/)", order = 2) var cron: String? = null @Parameter(names = ["--read-percentage"], description = "Read percentage based on current table capacity. Cannot be used with '--read-capacity'.", order = 3) var readPercentage: Double? = null @Parameter(names = ["--read-capacity"], description = "Read capacity (useful if auto scaling enabled). Cannot be used with '--read-percentage'.", order = 4) var readCapacity: Int? = null @Parameter(names = ["-p", "--pattern"], description = "Destination file path pattern.", order = 5) var pattern: String = BackupTable.DEFAULT_PATTERN @Parameter(names = ["-n", "--namespace"], description = "Cloudwatch namespace to send metrics.", order = 6) var cloudwatchNamespace: String? = null @Parameter(names = ["--jvmMetrics"], description = "Collect JVM metrics") var jvmMetrics = false fun parseTables(): List<String> { return tables.map { it.split(",") } .flatten() .filter { it.isNotBlank() } .map { it.trim() } } fun validate() { if (readPercentage == null && readCapacity == null) { throw ParameterException("Missing read configuration. Use '--read-percentage' or '--read-capacity' parameter.") } if (readPercentage != null && readCapacity != null) { throw ParameterException("Cannot use '--read-percentage' and '--read-capacity' together.") } } }
bsd-3-clause
97e45362bb4ed599eb58de2952988944
41.137255
176
0.683426
4.014953
false
false
false
false
google/horologist
media-data/src/main/java/com/google/android/horologist/media/data/mapper/PlaylistMapper.kt
1
1500
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.android.horologist.media.data.mapper import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi import com.google.android.horologist.media.data.database.model.PopulatedPlaylist import com.google.android.horologist.media.model.Playlist /** * Functions to map models from other layers and / or packages into a [Playlist]. */ @ExperimentalHorologistMediaDataApi public class PlaylistMapper( private val mediaMapper: MediaMapper ) { /** * Maps from a [PopulatedPlaylist]. */ public fun map(populatedPlaylist: PopulatedPlaylist): Playlist = Playlist( id = populatedPlaylist.playlist.playlistId, name = populatedPlaylist.playlist.name, artworkUri = populatedPlaylist.playlist.artworkUri, mediaList = populatedPlaylist.mediaList.map(mediaMapper::map) ) }
apache-2.0
7254c1f38e8ea315a6c7bee62545d444
35.585366
82
0.738667
4.491018
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/permalink/pathtypes/SlugPathType.kt
1
1233
package com.eden.orchid.posts.permalink.pathtypes import com.eden.common.util.EdenUtils import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.api.theme.permalinks.PermalinkPathType import com.eden.orchid.posts.PostsGenerator import com.eden.orchid.posts.pages.PostPage import com.eden.orchid.posts.utils.PostsUtils import javax.inject.Inject class SlugPathType @Inject constructor() : PermalinkPathType(100) { override fun acceptsKey(page: OrchidPage, key: String): Boolean { return key == "slug" && page is PostPage } override fun format(page: OrchidPage, key: String): String? { if (page is PostPage) { val baseCategoryPath: String if (EdenUtils.isEmpty(page.categoryModel.key)) { baseCategoryPath = "posts" } else { baseCategoryPath = "posts/" + page.categoryModel.path } val formattedFilename = PostsUtils.getPostFilename(page.resource, baseCategoryPath) val matcher = PostsGenerator.pageTitleRegex.matcher(formattedFilename) if (matcher.matches()) { return matcher.group(4) } } return null } }
mit
a7240e98760640df4c3ab6ace233b0bb
27.674419
95
0.658556
4.193878
false
false
false
false
emufog/emufog
src/main/kotlin/emufog/graph/Node.kt
1
3023
/* * MIT License * * Copyright (c) 2018 emufog contributors * * 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 emufog.graph /** * Represents a general node of the graph with the basic functionality. Can connect to other nodes via edges. Can also * hold an [EmulationNode] if that node should be emulated by a container. * * @property id unique identifier of the node * @property system the autonomous system this node belongs to * @property emulationNode emulation configuration of the node, can be not set * @property edges list of edges connected to this node * @property degree the edge degree of the node. Is based on the number of nodes this node is connected to via edges * @property type the type of this node */ abstract class Node internal constructor( val id: Int, val system: AS, edges: List<Edge>, emulationNode: EmulationNode? ) { private val edgesMutable: MutableList<Edge> = edges.toMutableList() val edges: List<Edge> get() = edgesMutable val degree: Int get() = edges.size open val emulationNode: EmulationNode? get() = emulationNodeMutable private var emulationNodeMutable: EmulationNode? = emulationNode abstract val type: NodeType /** * Returns whether this node is associated with an emulation configuration. */ fun hasEmulationSettings(): Boolean = emulationNode != null /** * Set an [EmulationNode] or `null` for this instance. */ internal fun setEmulationNode(emulationNode: EmulationNode?) { emulationNodeMutable = emulationNode } /** * Adds an [Edge] instance to the list of edges [edges]. */ internal fun addEdge(edge: Edge) { edgesMutable.add(edge) } override fun equals(other: Any?): Boolean { if (other !is Node) { return false } return id == other.id } override fun hashCode(): Int = id override fun toString(): String = "Node: $id" }
mit
3fad32863413a40750701ecfd4e205e1
32.966292
118
0.704598
4.478519
false
false
false
false
Kotlin/dokka
core/src/main/kotlin/DokkaGenerator.kt
1
2652
@file:Suppress("SameParameterValue") package org.jetbrains.dokka import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import org.jetbrains.dokka.generation.GracefulGenerationExit import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.DokkaPlugin import org.jetbrains.dokka.utilities.DokkaLogger /** * DokkaGenerator is the main entry point for generating documentation * * [generate] method has been split into submethods for test reasons */ class DokkaGenerator( private val configuration: DokkaConfiguration, private val logger: DokkaLogger ) { fun generate() = timed(logger) { report("Initializing plugins") val context = initializePlugins(configuration, logger) runCatching { context.single(CoreExtensions.generation).run { logger.progress("Dokka is performing: $generationName") generate() } }.exceptionOrNull()?.let { e -> finalizeCoroutines() throw e } finalizeCoroutines() }.dump("\n\n === TIME MEASUREMENT ===\n") fun initializePlugins( configuration: DokkaConfiguration, logger: DokkaLogger, additionalPlugins: List<DokkaPlugin> = emptyList() ) = DokkaContext.create(configuration, logger, additionalPlugins) @OptIn(DelicateCoroutinesApi::class) private fun finalizeCoroutines() { if (configuration.finalizeCoroutines) { Dispatchers.shutdown() } } } class Timer internal constructor(startTime: Long, private val logger: DokkaLogger?) { private val steps = mutableListOf("" to startTime) fun report(name: String) { logger?.progress(name) steps += (name to System.currentTimeMillis()) } fun dump(prefix: String = "") { logger?.info(prefix) val namePad = steps.map { it.first.length }.maxOrNull() ?: 0 val timePad = steps.windowed(2).map { (p1, p2) -> p2.second - p1.second }.maxOrNull()?.toString()?.length ?: 0 steps.windowed(2).forEach { (p1, p2) -> if (p1.first.isNotBlank()) { logger?.info("${p1.first.padStart(namePad)}: ${(p2.second - p1.second).toString().padStart(timePad)}") } } } } private fun timed(logger: DokkaLogger? = null, block: Timer.() -> Unit): Timer = Timer(System.currentTimeMillis(), logger).apply { try { block() } catch (exit: GracefulGenerationExit) { report("Exiting Generation: ${exit.reason}") } finally { report("") } }
apache-2.0
659ef77bd5ac718fbf50d6340d04dd84
30.951807
118
0.63914
4.548885
false
true
false
false
toastkidjp/Yobidashi_kt
image/src/main/java/jp/toastkid/image/view/ImageListUi.kt
1
8585
/* * Copyright (c) 2022 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.image.view import android.Manifest import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import coil.compose.AsyncImage import coil.request.ImageRequest import jp.toastkid.image.Image import jp.toastkid.image.R import jp.toastkid.image.list.BucketLoader import jp.toastkid.image.list.ImageFilterUseCase import jp.toastkid.image.list.ImageLoader import jp.toastkid.image.list.ImageLoaderUseCase import jp.toastkid.image.preview.ImagePreviewUi import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.lib.viewmodel.PageSearcherViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @Composable fun ImageListUi() { val context = LocalContext.current val contentResolver = context.contentResolver ?: return val preferenceApplier = PreferenceApplier(context) val preview = remember { mutableStateOf(false) } val images = remember { mutableStateListOf<Image>() } val backHandlerState = remember { mutableStateOf(false) } val imageLoader = ImageLoader(contentResolver) val imageLoaderUseCase = remember { ImageLoaderUseCase( preferenceApplier, { images.clear() images.addAll(it) }, BucketLoader(contentResolver), imageLoader, backHandlerState, { } ) } val imageFilterUseCase = remember { ImageFilterUseCase( preferenceApplier, { images.clear() images.addAll(it) }, imageLoaderUseCase, imageLoader, { } ) } val contentViewModel = (context as? ViewModelStoreOwner)?.let { viewModelStoreOwner -> ViewModelProvider(viewModelStoreOwner).get(ContentViewModel::class.java) } val requestPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { if (it) { imageLoaderUseCase() return@rememberLauncherForActivityResult } contentViewModel?.snackShort(R.string.message_audio_file_is_not_found) } (context as? ViewModelStoreOwner)?.let { ViewModelProvider(it).get(PageSearcherViewModel::class.java) .also { viewModel -> val keyword = viewModel.find.observeAsState().value?.getContentIfNotHandled() if (keyword.isNullOrBlank()) { return@also } imageFilterUseCase(keyword) } } if (preview.value.not()) { LaunchedEffect(key1 = "first_launch") { requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } } val index = remember { mutableStateOf(-1) } val listState = rememberLazyGridState() if (preview.value) { ImagePreviewUi(images, index.value) } else { ImageListUi( imageLoaderUseCase, images, listState ) { index.value = it preview.value = true backHandlerState.value = true } } BackHandler(backHandlerState.value) { if (index.value != -1) { index.value = -1 preview.value = false } else { imageLoaderUseCase.back {} } } } @OptIn(ExperimentalFoundationApi::class) @Composable internal fun ImageListUi( imageLoaderUseCase: ImageLoaderUseCase, images: List<Image>, listState: LazyGridState, showPreview: (Int) -> Unit ) { val preferenceApplier = PreferenceApplier(LocalContext.current) LazyVerticalGrid( state = listState, columns = GridCells.Fixed(2), contentPadding = PaddingValues(8.dp) ) { items(images, { it.path }) { image -> Surface( elevation = 4.dp, modifier = Modifier .padding(4.dp) .animateItemPlacement() ) { Column( modifier = Modifier .combinedClickable( true, onClick = { if (image.isBucket) { CoroutineScope(Dispatchers.IO).launch { imageLoaderUseCase(image.name) } } else { showPreview(images.indexOf(image)) } }, onLongClick = { preferenceApplier.addExcludeItem(image.path) imageLoaderUseCase() } ) .padding(4.dp) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(image.path) .crossfade(true) .placeholder(R.drawable.ic_image) .build(), contentDescription = image.name, contentScale = ContentScale.Crop, modifier = Modifier.height(152.dp) ) Text( text = image.makeDisplayName(), fontSize = 14.sp, maxLines = 2, modifier = Modifier.padding(4.dp) ) } } } } val lifecycleOwner = LocalLifecycleOwner.current val coroutineScope = rememberCoroutineScope() val contentViewModel = (LocalContext.current as? ViewModelStoreOwner)?.let { ViewModelProvider(it).get(ContentViewModel::class.java) } contentViewModel?.toTop?.observe(lifecycleOwner, { it?.getContentIfNotHandled() ?: return@observe coroutineScope.launch { listState.scrollToItem(0) } }) contentViewModel?.toBottom?.observe(lifecycleOwner) { it?.getContentIfNotHandled() ?: return@observe coroutineScope.launch { listState.scrollToItem(listState.layoutInfo.totalItemsCount) } } DisposableEffect(key1 = lifecycleOwner, effect = { onDispose { contentViewModel?.toTop?.removeObservers(lifecycleOwner) contentViewModel?.toBottom?.removeObservers(lifecycleOwner) } }) }
epl-1.0
9369b976ccd64fa8f5650eb3ac6ea246
33.898374
93
0.618637
5.471638
false
false
false
false
sepatel/tekniq
tekniq-jdbc/src/test/kotlin/io/tekniq/jdbc/InlineFunctionReturnSpek.kt
1
1766
package io.tekniq.jdbc import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals object InlineFunctionReturnSpek : Spek({ val conn = TqSingleConnectionDataSource("jdbc:hsqldb:mem:tekniq", "sa", "").connection.apply { val stmt = createStatement() stmt.execute("DROP TABLE dataone IF EXISTS") stmt.execute("CREATE TABLE dataone(id INTEGER, s VARCHAR(20))") stmt.execute("INSERT INTO dataone VALUES(1, 'Pi')") stmt.execute("INSERT INTO dataone VALUES(2, NULL)") stmt.execute("INSERT INTO dataone VALUES(3, 'Light')") stmt.execute("DROP TABLE dataoption IF EXISTS") stmt.execute("CREATE TABLE dataoption(dataone_id INTEGER, color VARCHAR(20))") stmt.execute("INSERT INTO dataoption VALUES(1, 'Transparent')") stmt.execute("INSERT INTO dataoption VALUES(3, 'Darkness')") stmt.close() } describe("failure within nested selects") { it("breaks correct within the nesting") { var answer = "wrong" conn.select("SELECT * from (VALUES(0))") outerLoop@{ conn.select("SELECT id, s FROM dataone") { val s = getString("s") conn.select("SELECT color FROM dataoption WHERE dataone_id=?", getInt("id")) { if (getString("color") == "Transparent") { answer = s return@outerLoop } answer = "reallyWrong" } answer = "awesomeWrong" } answer = "howSoWrong" } assertEquals("Pi", answer) } } })
mit
ad02bff6b0ab48b023190cfa9ec47d11
40.069767
98
0.564553
4.623037
false
false
false
false
italoag/qksms
domain/src/main/java/com/moez/QKSMS/model/Recipient.kt
3
1379
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS 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. * * QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.model import android.telephony.PhoneNumberUtils import io.realm.RealmObject import io.realm.annotations.PrimaryKey import java.util.* open class Recipient( @PrimaryKey var id: Long = 0, var address: String = "", var contact: Contact? = null, var lastUpdate: Long = 0 ) : RealmObject() { /** * Return a string that can be displayed to represent the name of this contact */ fun getDisplayName(): String = contact?.name?.takeIf { it.isNotBlank() } ?: PhoneNumberUtils.formatNumber(address, Locale.getDefault().country) // TODO: Use our own PhoneNumberUtils ?: address }
gpl-3.0
2dec5e675f6c5ab3d3c4fa4de614101e
33.475
120
0.708484
4.166163
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/util/MutableLinkMovementMethod.kt
1
2138
package com.geckour.egret.util import android.net.Uri import android.text.Spannable import android.text.method.LinkMovementMethod import android.view.MotionEvent import android.widget.TextView import android.text.Selection import android.text.style.URLSpan import android.text.style.ClickableSpan class MutableLinkMovementMethod(private val listener: OnUrlClickListener) : LinkMovementMethod() { interface OnUrlClickListener { fun onUrlClick(view: TextView?, uri: Uri) } override fun onTouchEvent(widget: TextView?, buffer: Spannable?, event: MotionEvent?): Boolean { val action = event?.action if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { var x: Int = event.x.toInt() var y: Int = event.y.toInt() widget?.let { x -= it.totalPaddingLeft y -= it.totalPaddingTop x += it.scrollX y += it.scrollY } val layout = widget?.layout val link = if (layout == null) null else { val line = layout.getLineForVertical(y) val offset = layout.getOffsetForHorizontal(line, x.toFloat()) buffer?.getSpans(offset, offset, ClickableSpan::class.java) } if (link != null && link.isNotEmpty()) { if (action == MotionEvent.ACTION_UP) { if (link[0] is URLSpan) { val uri = Uri.parse((link[0] as URLSpan).url) listener.onUrlClick(widget, uri) } else { link[0].onClick(widget) } } else if (action == MotionEvent.ACTION_DOWN && buffer != null) { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])) } return true } else { Selection.removeSelection(buffer) } } return super.onTouchEvent(widget, buffer, event) } }
gpl-3.0
7ba67f4292ed38ffb3ec54c0a8ea3ef2
32.421875
100
0.548176
4.926267
false
false
false
false
mbuhot/eskotlin
src/main/kotlin/mbuhot/eskotlin/query/fulltext/MatchPhrasePrefix.kt
1
1273
/* * Copyright (c) 2016. Ryan Murfitt [email protected] */ package mbuhot.eskotlin.query.fulltext import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder /** * match_phrase_prefix */ class MatchPhrasePrefixBlock { @Deprecated(message = "Use invoke operator instead.", replaceWith = ReplaceWith("invoke(init)")) infix fun String.to(init: MatchPhrasePrefixData.() -> Unit) = this.invoke(init) operator fun String.invoke(init: MatchPhrasePrefixData.() -> Unit) = MatchPhrasePrefixData(name = this).apply(init) infix fun String.to(query: Any) = MatchPhrasePrefixData(name = this, query = query) data class MatchPhrasePrefixData( var name: String, var query: Any? = null, var analyzer: String? = null, var slop: Int? = null, var max_expansions: Int? = null) } fun match_phrase_prefix(init: MatchPhrasePrefixBlock.() -> MatchPhrasePrefixBlock.MatchPhrasePrefixData): MatchPhrasePrefixQueryBuilder { val params = MatchPhrasePrefixBlock().init() return MatchPhrasePrefixQueryBuilder(params.name, params.query).apply { params.analyzer?.let { analyzer(it) } params.slop?.let { slop(it) } params.max_expansions?.let { maxExpansions(it) } } }
mit
e127b93252617c346fa9a1a1ec6b3156
32.5
137
0.689709
3.881098
false
false
false
false
Nandi/http
src/main/kotlin/com/headlessideas/http/util/StatusCodes.kt
1
402
package com.headlessideas.http.util import com.headlessideas.http.StatusCode val ok = StatusCode(200, "OK") val forbidden = StatusCode(403, "Forbidden") val notFound = StatusCode(404, "Not Found") val methodNotAllowed = StatusCode(405, "Method Not Allowed") val internalServerError = StatusCode(500, "Internal Server Error") val httpVersionNotSupported = StatusCode(505, "HTTP Version Not Supported")
mit
3587e67a9d87fb091739beedc2feb29a
39.3
75
0.788557
4.102041
false
false
false
false
TangHao1987/intellij-community
platform/testFramework/testSrc/com/intellij/testFramework/TemporaryDirectory.kt
2
3034
/* * 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 com.intellij.testFramework import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import java.io.File import java.io.IOException public class TemporaryDirectory : ExternalResource() { private val files = SmartList<File>() private var sanitizedName: String? = null override fun apply(base: Statement, description: Description): Statement { sanitizedName = FileUtil.sanitizeName(description.getMethodName()) return super.apply(base, description) } override fun after() { for (file in files) { FileUtil.delete(file) } files.clear() } /** * Directory is not created. */ public fun newDirectory(directoryName: String? = null): File { val file = generatePath(directoryName) val fs = LocalFileSystem.getInstance() if (fs != null) { // If a temp directory is reused from some previous test run, there might be cached children in its VFS. Ensure they're removed. val virtualFile = fs.findFileByIoFile(file) if (virtualFile != null) { VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) } } return file } public fun generatePath(suffix: String?): File { var fileName = sanitizedName!! if (suffix != null) { fileName += "_$suffix" } var file = generateTemporaryPath(fileName) files.add(file) return file } public fun newVirtualDirectory(directoryName: String? = null): VirtualFile { val file = generatePath(directoryName) if (!file.mkdirs()) { throw AssertionError("Cannot create directory") } val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file) VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) return virtualFile!! } } public fun generateTemporaryPath(fileName: String?): File { val tempDirectory = FileUtilRt.getTempDirectory() var file = File(tempDirectory, fileName) var i = 0 while (file.exists() && i < 9) { file = File(tempDirectory, "${fileName}_$i") i++ } if (file.exists()) { throw IOException("Cannot generate unique random path") } return file }
apache-2.0
c16a51cb9e2bea1ab7f35e05899d0ab7
29.656566
134
0.716546
4.359195
false
false
false
false
bertilxi/Chilly_Willy_Delivery
mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/model/Location.kt
1
1321
package dam.isi.frsf.utn.edu.ar.delivery.model import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class Location( @SerializedName("latitude") @Expose var latitude: Double? = 0.0, @SerializedName("longitude") @Expose var longitude: Double? = 0.0 ) : Parcelable { fun withLatitude(latitude: Double?): Location { this.latitude = latitude return this } fun withLongitude(longitude: Double?): Location { this.longitude = longitude return this } companion object { @JvmField val CREATOR: Parcelable.Creator<Location> = object : Parcelable.Creator<Location> { override fun createFromParcel(source: Parcel): Location = Location(source) override fun newArray(size: Int): Array<Location?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readValue(Double::class.java.classLoader) as Double?, source.readValue(Double::class.java.classLoader) as Double? ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeValue(latitude) dest.writeValue(longitude) } }
mit
0ec8e98d3fc2aec19908a00038d4aeba
29.045455
101
0.658592
4.447811
false
false
false
false
yoelglus/notes
app/src/main/java/com/yoelglus/notes/presentation/activity/NoteListActivity.kt
1
4323
package com.yoelglus.notes.presentation.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.TextView import com.yoelglus.notes.R import com.yoelglus.notes.domain.Note import com.yoelglus.notes.presentation.fragment.NoteDetailFragment import com.yoelglus.notes.presentation.presenter.NotesListPresenter import com.yoelglus.notes.presentation.presenter.PresenterFactory import kotlinx.android.synthetic.main.activity_note_list.* class NoteListActivity : AppCompatActivity(), NotesListPresenter.View { private val ADD_NOTE_REQUEST = 123 private var twoPane: Boolean = false private val presenter: NotesListPresenter by lazy { PresenterFactory.createNotesListPresenter(this) } private val adapter = SimpleItemRecyclerViewAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) presenter.takeView(this) setContentView(R.layout.activity_note_list) setSupportActionBar(toolbar) toolbar.title = title addNoteButton.setOnClickListener { view -> startActivityForResult(Intent(view.context, AddNoteActivity::class.java), ADD_NOTE_REQUEST) } findViewById<RecyclerView>(R.id.note_list).adapter = adapter if (findViewById<FrameLayout>(R.id.note_detail_container) != null) { twoPane = true } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == ADD_NOTE_REQUEST && resultCode == Activity.RESULT_OK) { presenter.refreshData() } } override fun onDestroy() { super.onDestroy() presenter.dropView() } override fun showNotes(notes: List<Note>) { adapter.values.clear() adapter.values.addAll(notes) adapter.notifyDataSetChanged() } override fun showError(message: String) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } inner class SimpleItemRecyclerViewAdapter : RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder>() { val values: MutableList<Note> = mutableListOf() override fun getItemCount(): Int { return values.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.note_list_content, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.item = values[position] holder.idView.text = values[position].title holder.contentView.text = values[position].text holder.mView.setOnClickListener { v -> if (twoPane) { val arguments = Bundle() arguments.putInt(NoteDetailFragment.ARG_ITEM_ID, holder.item.id) val fragment = NoteDetailFragment() fragment.arguments = arguments supportFragmentManager.beginTransaction() .replace(R.id.note_detail_container, fragment) .commit() } else { val context = v.context val intent = Intent(context, NoteDetailActivity::class.java) intent.putExtra(NoteDetailFragment.ARG_ITEM_ID, holder.item.id) context.startActivity(intent) } } } inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) { val idView: TextView = mView.findViewById(R.id.id) val contentView: TextView = mView.findViewById(R.id.content) lateinit var item: Note override fun toString(): String { return super.toString() + " '" + contentView.text + "'" } } } }
apache-2.0
f82ecc97176f20cbcbff5a2d8f4fb5b1
33.862903
114
0.652325
4.974684
false
false
false
false
pdvrieze/ProcessManager
java-common/src/commonMain/kotlin/_NumberUtil.kt
1
2031
/* * Copyright (c) 2018. * * 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.util /** * Determine whether the value is between the two bounds. The bounds can be in any order (either [bound1] or [bound2] * can be smaller. Both bounds are inclusive */ fun Double.isBetween(bound1:Double, bound2: Double) = when { bound1<bound2 -> this >= bound1 && this<=bound2 else -> this >= bound2 && this<=bound1 } /** * Determine whether the value is between the two bounds. The bounds can be in any order (either [bound1] or [bound2] * can be smaller. Both bounds are inclusive */ fun Float.isBetween(bound1:Float, bound2: Float) = when { bound1<bound2 -> this >= bound1 && this<=bound2 else -> this >= bound2 && this<=bound1 } /** * Determine whether the value is between the two bounds. The bounds can be in any order (either [bound1] or [bound2] * can be smaller. Both bounds are inclusive */ fun Int.isBetween(bound1:Int, bound2: Int) = when { bound1<bound2 -> this >= bound1 && this<=bound2 else -> this >= bound2 && this<=bound1 } /** * Determine whether the value is between the two bounds. The bounds can be in any order (either [bound1] or [bound2] * can be smaller. Both bounds are inclusive */ fun Long.isBetween(bound1:Long, bound2: Long) = when { bound1<bound2 -> this >= bound1 && this<=bound2 else -> this >= bound2 && this<=bound1 }
lgpl-3.0
2f90a0a0fc076e1bb563b755d4a944b5
38.057692
118
0.697686
3.726606
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/models/AnimeCharacter.kt
1
1046
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.github.jasminb.jsonapi.Links import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.RelationshipLinks import com.github.jasminb.jsonapi.annotations.Type @Type("animeCharacters") @JsonIgnoreProperties(ignoreUnknown = true) class AnimeCharacter : BaseJsonModel(JsonType("animeCharacters")) { companion object FieldNames { val ROLE = "role" val ANIME = "anime" val CHARACTER = "character" val CASTINGS = "castings" } var role: String? = null @Relationship("anime") var anime: Anime? = null @RelationshipLinks("anime") var animeLinks: Links? = null @Relationship("character") var character: Character? = null @RelationshipLinks("character") var characterLinks: Links? = null @Relationship("castings") var casting: Casting? = null @RelationshipLinks("castings") var castingLinks: Links? = null }
gpl-3.0
375f28d12dbbd0d4ad366c00520eb779
25.846154
68
0.717973
4.376569
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/concerns/ViewModelBinding.kt
1
3532
package io.rover.sdk.experiences.ui.concerns import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import android.view.View import org.reactivestreams.Subscription import kotlin.reflect.KProperty /** * Use this Kotlin delegated property to manage binding of a view model to a View. * * When rebinding to a new view model, it will unsubscribe/cancel any existing subscriptions * to asynchronous events. * * @param binding Pass in a closure that will set up your view as per the view model's direction. It * will provide you with a callback you can call for whenever a subscription for a subscriber you * created becomes ready. */ internal class ViewModelBinding<VM : Any>( view: View? = null, private val rebindingAllowed: Boolean = true, private val cancellationBlock:(() -> Unit)? = null, private val binding: (viewModel: VM?, subscriptionCallback: (Subscription) -> Unit) -> Unit ) { private var outstandingSubscriptions: List<Subscription>? = null private var viewState: ViewState<VM> = ViewState(true, null) set(value) { val oldValue = field field = value when { value.foregrounded && value.viewModel != null && oldValue != value -> invokeBinding(value.viewModel) !value.foregrounded || value.viewModel == null && oldValue != value -> cancelSubscriptions() } } init { setupViewLifecycleObserver(view) } /** * Called when a view model bound */ operator fun setValue(thisRef: Any, property: KProperty<*>, value: VM?) { if (viewState.viewModel != null && !rebindingAllowed) throw RuntimeException("This view does not support being re-bound to a new view model.") viewState = viewState.setVM(null) viewState = viewState.setVM(value) } operator fun getValue(thisRef: Any, property: KProperty<*>) = viewState.viewModel private fun cancelSubscriptions() { // cancel any existing async subscriptions. outstandingSubscriptions?.forEach { subscription -> subscription.cancel() } outstandingSubscriptions = null cancellationBlock?.invoke() } private fun invokeBinding(value: VM?) { binding(value) { subscription: Subscription -> if (viewState.viewModel == value) { // a subscription has come alive for currently active view model! outstandingSubscriptions = listOf(subscription) + (outstandingSubscriptions ?: listOf()) } else { // subscription for a stale view model has come up. cancel it immediately. subscription.cancel() } } } val subscription: Subscription? = null private fun setupViewLifecycleObserver(view: View?) { ((view?.context) as? LifecycleOwner)?.lifecycle?.addObserver(object: LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun paused() { viewState = viewState.setForeground(false) } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun resumed() { viewState = viewState.setForeground(true) } }) } } data class ViewState<VM : Any>(val foregrounded: Boolean, val viewModel: VM?) { fun setForeground(foregrounded: Boolean) = copy(foregrounded = foregrounded) fun setVM(viewModel: VM?) = copy(viewModel = viewModel) }
apache-2.0
692a7e311737b6e4890d8f074925ebf4
36.978495
150
0.666761
4.885201
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/inspections/latex/probablebugs/packages/LatexUndefinedCommandInspection.kt
1
4370
package nl.hannahsten.texifyidea.inspections.latex.probablebugs.packages import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.indexing.FileBasedIndex import nl.hannahsten.texifyidea.index.file.LatexExternalCommandIndex import nl.hannahsten.texifyidea.inspections.InsightGroup import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.lang.commands.LatexRegularCommand import nl.hannahsten.texifyidea.util.definedCommandName import nl.hannahsten.texifyidea.util.files.commandsInFile import nl.hannahsten.texifyidea.util.files.definitionsInFileSet import nl.hannahsten.texifyidea.util.includedPackages import nl.hannahsten.texifyidea.util.insertUsepackage import nl.hannahsten.texifyidea.util.magic.CommandMagic import nl.hannahsten.texifyidea.util.magic.cmd /** * Warn when the user uses a command that is not defined in any included packages or LaTeX base. * This is an extension of [LatexMissingImportInspection], however, because this also * complains about commands that are not hardcoded in TeXiFy but come from any package, * and this index of commands is far from complete, it has to be disabled by default, * and thus cannot be included in the mentioned inspection. * * @author Thomas */ class LatexUndefinedCommandInspection : TexifyInspectionBase() { override val inspectionGroup = InsightGroup.LATEX override val inspectionId = "UndefinedCommand" override fun getDisplayName() = "Command is not defined" override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> { val includedPackages = file.includedPackages().toSet().plus(LatexPackage.DEFAULT) val commandsInFile = file.commandsInFile() val commandNamesInFile = commandsInFile.map { it.name } // The number of indexed commands can be quite large (50k+) so we filter the large set based on the small one (in this file). val indexedCommands = FileBasedIndex.getInstance().getAllKeys(LatexExternalCommandIndex.id, file.project) .filter { it in commandNamesInFile } .associateWith { command -> val containingPackages = FileBasedIndex.getInstance().getContainingFiles(LatexExternalCommandIndex.id, command, GlobalSearchScope.everythingScope(file.project)) .map { LatexPackage.create(it) } .toSet() containingPackages } val magicCommands = LatexRegularCommand.ALL.associate { Pair(it.cmd, setOf(it.dependency)) } val userDefinedCommands = file.definitionsInFileSet().filter { it.name in CommandMagic.commandDefinitions } .map { it.definedCommandName() } .associateWith { setOf(LatexPackage.DEFAULT) } // Join all the maps, map command name (with backslash) to all packages it is defined in val allKnownCommands = (indexedCommands.keys + magicCommands.keys + userDefinedCommands.keys).associateWith { indexedCommands.getOrDefault(it, setOf()) + magicCommands.getOrDefault(it, setOf()) + userDefinedCommands.getOrDefault(it, setOf()) } return commandsInFile.filter { allKnownCommands.getOrDefault(it.name, emptyList()).intersect(includedPackages).isEmpty() } .map { command -> manager.createProblemDescriptor( command, "Command ${command.name} is not defined", allKnownCommands.getOrDefault(command.name, emptyList()).map { ImportPackageFix(it) }.toTypedArray(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOntheFly, false ) } } private class ImportPackageFix(val dependency: LatexPackage) : LocalQuickFix { override fun getFamilyName() = "Add import for package ${dependency.name}" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { descriptor.psiElement.containingFile.insertUsepackage(dependency) } } }
mit
e38e14f030a873864236c1cc6e1d9905
51.662651
176
0.743249
4.915636
false
false
false
false
Mauin/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/TooManyFunctionsSpec.kt
1
3482
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.rules.Case import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it /** * @author Artur Bosch */ class TooManyFunctionsSpec : Spek({ describe("a simple test") { val rule = TooManyFunctions() it("should find one file with too many functions") { assertThat(rule.lint(Case.TooManyFunctions.path())).hasSize(1) } it("should find one file with too many top level functions") { assertThat(rule.lint(Case.TooManyFunctionsTopLevel.path())).hasSize(1) } } describe("different declarations with one function as threshold") { val rule = TooManyFunctions(TestConfig(mapOf( TooManyFunctions.THRESHOLD_IN_CLASSES to "1", TooManyFunctions.THRESHOLD_IN_ENUMS to "1", TooManyFunctions.THRESHOLD_IN_FILES to "1", TooManyFunctions.THRESHOLD_IN_INTERFACES to "1", TooManyFunctions.THRESHOLD_IN_OBJECTS to "1" ))) it("finds one function in class") { val code = """ class A { fun a() = Unit } """ assertThat(rule.lint(code)).hasSize(1) } it("finds one function in object") { val code = """ object O { fun o() = Unit } """ assertThat(rule.lint(code)).hasSize(1) } it("finds one function in interface") { val code = """ interface I { fun i() } """ assertThat(rule.lint(code)).hasSize(1) } it("finds one function in enum") { val code = """ enum class E { fun E() } """ assertThat(rule.lint(code)).hasSize(1) } it("finds one function in file") { val code = "fun f = Unit" assertThat(rule.lint(code)).hasSize(1) } it("finds one function in file ignoring other declarations") { val code = """ fun f1 = Unit class C object O fun f2 = Unit interface I enum class E fun f3 = Unit """ assertThat(rule.lint(code)).hasSize(1) } it("finds one function in nested class") { val code = """ class A { class B { class C { fun a() = Unit } } } """ assertThat(rule.lint(code)).hasSize(1) } describe("different deprecated functions") { val code = """ @Deprecated fun f() { } class A { @Deprecated fun f() { } } """ it("finds all deprecated functions per default") { assertThat(rule.lint(code)).hasSize(2) } it("finds no deprecated functions") { val configuredRule = TooManyFunctions(TestConfig(mapOf( TooManyFunctions.THRESHOLD_IN_CLASSES to "1", TooManyFunctions.THRESHOLD_IN_FILES to "1", TooManyFunctions.IGNORE_DEPRECATED to "true" ))) assertThat(configuredRule.lint(code)).isEmpty() } } describe("different private functions") { val code = """ private fun f() { } class A { private fun f() { } } """ it("finds all private functions per default") { assertThat(rule.lint(code)).hasSize(2) } it("finds no private functions") { val configuredRule = TooManyFunctions(TestConfig(mapOf( TooManyFunctions.THRESHOLD_IN_CLASSES to "1", TooManyFunctions.THRESHOLD_IN_FILES to "1", TooManyFunctions.IGNORE_PRIVATE to "true" ))) assertThat(configuredRule.lint(code)).isEmpty() } } } })
apache-2.0
d3f29df10302af77dc6229880b3d1897
19.850299
73
0.633257
3.407045
false
false
false
false
if710/if710.github.io
2019-08-28/Threads/app/src/main/java/br/ufpe/cin/android/threads/ThreadANR.kt
1
1530
package br.ufpe.cin.android.threads import android.app.Activity import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import kotlinx.android.synthetic.main.threads.* class ThreadANR : Activity() { private var mBitmap: Bitmap? = null //aumentando o delay a gente gera ANR private val mDelay = 25000 internal var toasts = 0 public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.threads) loadButton.setOnClickListener { loadIcon() } otherButton.setOnClickListener { toasts++ contadorToasts.text = getString(R.string.contador_de_toasts) + toasts Toast.makeText(applicationContext, "Estou trabalhando... ($toasts)", Toast.LENGTH_SHORT).show() } } private fun loadIcon() { Thread(Runnable { try { Thread.sleep(mDelay.toLong()) } catch (e: InterruptedException) { Log.e(TAG, e.toString()) } mBitmap = BitmapFactory.decodeResource(resources, R.drawable.painter) // vai dar pau... imageView.setImageBitmap(mBitmap) }).start() } companion object { private val TAG = "SimpleThreading" } }
mit
d724f1d56e0e1a5e3aed743ab4e9b888
25.37931
107
0.648366
4.486804
false
false
false
false
Tapadoo/sputnik
sputnik/src/main/kotlin/com/tapadoo/sputnik/SputnikPluginExtensions.kt
1
2713
package com.tapadoo.sputnik import com.android.build.gradle.BaseExtension import com.tapadoo.sputnik.options.FileOutputOptions import com.tapadoo.sputnik.options.ProguardOptions import com.tapadoo.sputnik.options.VersionCodeOptions import com.tapadoo.sputnik.options.VersionNameOptions import groovy.lang.Closure import org.gradle.api.Project /** * Where the user interacts with this plugin. * * @author Elliot Tormey * @since 27/10/2016 */ open class SputnikPluginExtension(val project: Project) { private val android by lazy { project.extensions.getByName("android") as BaseExtension } val codeOptions: VersionCodeOptions by lazy { VersionCodeOptions(project) } val nameOptions: VersionNameOptions by lazy { VersionNameOptions(codeOptions) } val fileOptions: FileOutputOptions by lazy { FileOutputOptions(project) } val proguard: ProguardOptions by lazy { ProguardOptions(project, android) } // Quality check enabled by default. var enableQuality: Boolean = true fun versionName(closure: Closure<VersionNameOptions>) { project.configure(nameOptions, closure) } fun versionName(): String { return nameOptions.getVersionName() } fun versionName(baseValue: String) { nameOptions.baseValue = baseValue android.defaultConfig.versionName = nameOptions.getVersionName() } fun versionCode(closure: Closure<VersionCodeOptions>) { project.configure(codeOptions, closure) } fun versionCode(): Int { return codeOptions.getVersionCode() } fun versionCode(baseValue: Int) { codeOptions.baseValue = baseValue android.defaultConfig.versionCode = codeOptions.getVersionCode() } fun appName(appName: String) { fileOptions.appName = appName } fun apkName(closure: Closure<FileOutputOptions>) { project.configure(fileOptions, closure) } /** * Sets the APK naming format to use when generating an APK. See [@link FileOutputOptions] * * @param nameFormat The name format to use. */ fun apkName(nameFormat: String) { fileOptions.nameFormat = nameFormat fileOptions.generateOutputName() } /** * Enables or disables all quality checks when building a project with this plugin applied. * * @param enableQuality True to to enable checks, false otherwise. **/ fun enableQuality(enableQuality: Boolean) { this.enableQuality = enableQuality } fun proguard(vararg rules: String = emptyArray()) { proguard.applyProguard(rules.asList()) } fun proguard(closure: Closure<FileOutputOptions>) { project.configure(proguard, closure) } }
mit
d0d5a2f4cf94f8b24eb41ab1ff4a3618
30.183908
95
0.708809
4.361736
false
true
false
false
natanieljr/droidmate
project/pcComponents/core/src/test/kotlin/org/droidmate/device/datatypes/GuiStateTestHelper.kt
1
3644
// 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.device.datatypes class GuiStateTestHelper { // TODO Fix tests /*companion object { @JvmStatic @JvmOverloads @Suppress("unused") fun newEmptyGuiState(appPackageName: String = apkFixture_simple_packageName, id: String = ""): IGuiStatus = GuiStatus(appPackageName, id, ArrayList(), DeviceModel.buildDefault().getAndroidLauncherPackageName()) @JvmStatic @JvmOverloads fun newGuiStateWithTopLevelNodeOnly(appPackageName: String = apkFixture_simple_packageName, id: String = ""): IGuiStatus = GuiStatus(appPackageName, id, arrayListOf(newTopLevelWidget(appPackageName)), DeviceModel.buildDefault().getAndroidLauncherPackageName()) @JvmStatic fun newGuiStateWithDisabledWidgets(widgetCount: Int): IGuiStatus = newGuiStateWithWidgets(widgetCount, apkFixture_simple_packageName, false) @JvmStatic @JvmOverloads fun newGuiStateWithWidgets(widgetCount: Int, packageName: String = apkFixture_simple_packageName, enabled: Boolean = true, guiStateId: String = "", widgetIds: List<String> = ArrayList()): IGuiStatus { assert(widgetCount >= 0, { "OldWidget count cannot be zero. To create GUI state without widgets, call newEmptyGuiState()" }) assert(widgetIds.isEmpty() || widgetIds.size == widgetCount) val gs = GuiStatus(packageName, guiStateId, WidgetTestHelper.newWidgets( widgetCount, packageName, mapOf( "idsList" to widgetIds, "enabledList" to (0 until widgetCount).map { enabled } ), if (guiStateId.isEmpty()) guiStateId else getNextGuiStateName()), DeviceModel.buildDefault().getAndroidLauncherPackageName()) assert(gs.widgets.all { it.packageName == gs.topNodePackageName }) return gs } @JvmStatic fun newAppHasStoppedGuiState(): IGuiStatus = UiautomatorWindowDumpTestHelper.newAppHasStoppedDialogWindowDump().guiStatus @JvmStatic fun newCompleteActionUsingGuiState(): IGuiStatus = UiautomatorWindowDumpTestHelper.newCompleteActionUsingWindowDump().guiStatus @JvmStatic fun newHomeScreenGuiState(): IGuiStatus = UiautomatorWindowDumpTestHelper.newHomeScreenWindowDump().guiStatus @JvmStatic fun newOutOfAppScopeGuiState(): IGuiStatus = UiautomatorWindowDumpTestHelper.newAppOutOfScopeWindowDump().guiStatus @JvmStatic var nextGuiStateIndex = 0 @JvmStatic private fun getNextGuiStateName(): String { nextGuiStateIndex++ return "GS$nextGuiStateIndex" } }*/ }
gpl-3.0
00eb1fd2bc05d7987711ff53e34221ce
36.958333
144
0.722558
4.41697
false
true
false
false
soniccat/android-taskmanager
app_wordteacher/src/main/java/com/aglushkov/wordteacher/apiproviders/owlbot/service/OwlBotService.kt
1
2377
package com.aglushkov.wordteacher.apiproviders.owlbot.service import com.aglushkov.wordteacher.apiproviders.owlbot.model.OwlBotWord import com.aglushkov.wordteacher.apiproviders.owlbot.model.asWordTeacherWord import com.aglushkov.wordteacher.model.WordTeacherWord import com.aglushkov.wordteacher.repository.Config import com.aglushkov.wordteacher.repository.ConfigConnectParams import com.aglushkov.wordteacher.repository.ServiceMethodParams import com.aglushkov.wordteacher.service.WordTeacherWordService import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Path interface OwlBotService { companion object @GET("api/v4/dictionary/{word}") suspend fun definition(@Path("word") word: String): OwlBotWord } fun OwlBotService.Companion.createRetrofit(baseUrl: String, authInterceptor: Interceptor): Retrofit { val client = OkHttpClient.Builder().addInterceptor(authInterceptor).build() return Retrofit.Builder() .client(client) .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build() } fun OwlBotService.Companion.create(baseUrl: String, authInterceptor: Interceptor): OwlBotService = createRetrofit(baseUrl, authInterceptor).create(OwlBotService::class.java) fun OwlBotService.Companion.createWordTeacherWordService(aBaseUrl: String, aKey: String): WordTeacherWordService { return object : WordTeacherWordService { override var name = "OwlBot" override var key = aKey override var baseUrl = aBaseUrl override var methodParams = ServiceMethodParams(emptyMap()) private val authInterceptor = Interceptor { chain -> val newRequest: Request = chain.request().newBuilder() .addHeader("Authorization", "Token $key") .build() chain.proceed(newRequest) } private val service = OwlBotService.create(aBaseUrl, authInterceptor) override suspend fun define(word: String): List<WordTeacherWord> { return service.definition(word).asWordTeacherWord()?.let { listOf(it) } ?: emptyList() } } }
mit
ac8309d0e82fd64c01104f1618a78113
38.616667
101
0.716029
4.588803
false
false
false
false
arturbosch/detekt
detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/NullableToStringCall.kt
1
4778
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution import io.gitlab.arturbosch.detekt.rules.safeAs import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtStringTemplateEntry import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.types.isNullable /** * Turn on this rule to flag 'toString' calls with a nullable receiver that may return the string "null". * * <noncompliant> * fun foo(a: Any?): String { * return a.toString() * } * * fun bar(a: Any?): String { * return "$a" * } * </noncompliant> * * <compliant> * fun foo(a: Any?): String { * return a?.toString() ?: "-" * } * * fun bar(a: Any?): String { * return "${a ?: "-"}" * } * </compliant> */ @RequiresTypeResolution @Suppress("ReturnCount") class NullableToStringCall(config: Config = Config.empty) : Rule(config) { override val issue = Issue( javaClass.simpleName, Severity.Defect, "This call may return the string \"null\"", Debt.FIVE_MINS ) override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (bindingContext == BindingContext.EMPTY) return val simpleOrCallExpression = expression.parent.safeAs<KtCallExpression>() ?: expression val targetExpression = simpleOrCallExpression.targetExpression() ?: return if (simpleOrCallExpression.safeAs<KtCallExpression>()?.calleeExpression?.text == "toString" && simpleOrCallExpression.descriptor()?.fqNameOrNull() == toString ) { report(targetExpression) } else if (targetExpression.parent is KtStringTemplateEntry && targetExpression.isNullable()) { report(targetExpression.parent) } } private fun KtExpression.targetExpression(): KtExpression? { val qualifiedExpression = getStrictParentOfType<KtQualifiedExpression>() val targetExpression = if (qualifiedExpression != null) { qualifiedExpression.takeIf { it.selectorExpression == this } ?: return null } else { this } if (targetExpression.getStrictParentOfType<KtQualifiedExpression>() != null) return null return targetExpression } private fun KtExpression.isNullable(): Boolean { val safeAccessOperation = safeAs<KtSafeQualifiedExpression>()?.operationTokenNode?.safeAs<PsiElement>() if (safeAccessOperation != null) { return bindingContext.diagnostics.forElement(safeAccessOperation).none { it.factory == Errors.UNNECESSARY_SAFE_CALL } } val compilerResources = compilerResources ?: return false val descriptor = descriptor() ?: return false val originalType = descriptor.returnType ?.takeIf { it.isNullable() } ?: return false val dataFlowInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return false val dataFlowValue = compilerResources.dataFlowValueFactory.createDataFlowValue(this, originalType, bindingContext, descriptor) val dataFlowTypes = dataFlowInfo.getStableTypes(dataFlowValue, compilerResources.languageVersionSettings) return dataFlowTypes.all { it.isNullable() } } private fun report(element: PsiElement) { val codeSmell = CodeSmell( issue, Entity.from(element), "This call '${element.text}' may return the string \"null\"." ) report(codeSmell) } private fun KtExpression.descriptor(): CallableDescriptor? = getResolvedCall(bindingContext)?.resultingDescriptor companion object { val toString = FqName("kotlin.toString") } }
apache-2.0
ce39f109b2cb4f5c4c3c605e600606fa
38.487603
118
0.713897
4.87054
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/search/SearchEnginePreference.kt
1
1886
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.search import android.content.Context import android.content.SharedPreferences import androidx.preference.Preference import android.util.AttributeSet import org.mozilla.focus.R import org.mozilla.focus.ext.components import org.mozilla.focus.utils.Settings /** * Preference for setting the default search engine. */ class SearchEnginePreference : Preference, SharedPreferences.OnSharedPreferenceChangeListener { internal val context: Context constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { this.context = context } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { this.context = context } override fun onAttached() { summary = defaultSearchEngineName preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) super.onAttached() } override fun onPrepareForRemoval() { preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onPrepareForRemoval() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (key == context.resources.getString(R.string.pref_key_search_engine)) { summary = defaultSearchEngineName } } private val defaultSearchEngineName: String get() = context.components.searchEngineManager.getDefaultSearchEngine( getContext(), Settings.getInstance(context).defaultSearchEngineName).name }
mpl-2.0
4e4876c7823df089fc32f00597cab4a9
35.980392
113
0.730117
4.823529
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/BranchGraphQLIT.kt
1
15658
package net.nemerosa.ontrack.graphql import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.json.isNullOrNullNode import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.BranchFavouriteService import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.test.TestUtils.uid import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue class BranchGraphQLIT : AbstractQLKTITJUnit4Support() { @Autowired private lateinit var branchFavouriteService: BranchFavouriteService @Test fun `Creating a branch for a project name`() { asAdmin { project { val data = run(""" mutation { createBranch(input: {projectName: "$name", name: "main"}) { branch { id name } errors { message exception } } } """) // Checks the branch has been created assertNotNull(structureService.findBranchByName(name, "main").getOrNull(), "Branch has been created") { assertFalse(it.isDisabled, "Branch is not disabled") } // Checks the data val branch = data["createBranch"]["branch"] assertTrue(branch["id"].asInt() > 0, "ID is set") assertEquals("main", branch["name"].asText(), "Name is OK") assertTrue(data["createBranch"]["errors"].isNullOrNullNode(), "No error") } } } @Test fun `Creating a branch for a project ID`() { asAdmin { project { val data = run(""" mutation { createBranch(input: {projectId: ${id}, name: "main"}) { branch { id name } errors { message exception } } } """) // Checks the branch has been created assertNotNull(structureService.findBranchByName(name, "main").getOrNull(), "Branch has been created") { assertFalse(it.isDisabled, "Branch is not disabled") } // Checks the data val branch = data["createBranch"]["branch"] assertTrue(branch["id"].asInt() > 0, "ID is set") assertEquals("main", branch["name"].asText(), "Name is OK") assertTrue(data["createBranch"]["errors"].isNullOrNullNode(), "No error") } } } @Test fun `Creating a branch with missing project ID and name`() { asAdmin { project { val data = run(""" mutation { createBranch(input: {name: "main"}) { branch { id name } errors { message exception } } } """) // Checks the errors val error = data["createBranch"]["errors"][0] assertEquals("Project ID or name is required", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.ProjectIdOrNameMissingException", error["exception"].asText()) assertTrue(data["createBranch"]["branch"].isNullOrNullNode(), "Branch not returned") } } } @Test fun `Creating a branch with both project ID and name`() { asAdmin { project { val data = run(""" mutation { createBranch(input: {projectId: $id, projectName: "$name", name: "main"}) { branch { id name } errors { message exception } } } """) // Checks the errors val error = data["createBranch"]["errors"][0] assertEquals("Project ID or name is required, not both.", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.ProjectIdAndNameProvidedException", error["exception"].asText()) assertTrue(data["createBranch"]["branch"].isNullOrNullNode(), "Branch not returned") } } } @Test fun `Creating a branch for a project ID but name already exists`() { asAdmin { project { branch(name = "main") val data = run(""" mutation { createBranch(input: {projectId: ${id}, name: "main"}) { branch { id name } errors { message exception } } } """) // Checks the errors val error = data["createBranch"]["errors"][0] assertEquals("Branch name already exists: main", error["message"].asText()) assertEquals("net.nemerosa.ontrack.model.exceptions.BranchNameAlreadyDefinedException", error["exception"].asText()) assertTrue(data["createBranch"]["branch"].isNullOrNullNode(), "Branch not returned") } } } @Test fun `Creating a branch for a project ID but name is invalid`() { asAdmin { project { val data = run(""" mutation { createBranch(input: {projectId: ${id}, name: "main with space"}) { branch { id name } errors { message exception } } } """) // Checks the errors val error = data["createBranch"]["errors"][0] assertEquals("The name can only have letters, digits, dots (.), dashes (-) or underscores (_).", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.support.MutationInputValidationException", error["exception"].asText()) assertTrue(data["createBranch"]["branch"].isNullOrNullNode(), "Branch not returned") } } } @Test fun `Creating a branch in get mode from a project ID`() { asAdmin { project { val data = run( """ mutation { createBranchOrGet(input: {projectId: $id, name: "main"}) { branch { id name } errors { message exception } } } """ ) // Checks the errors assertNoUserError(data, "createBranchOrGet") val node = data["createBranchOrGet"]["branch"] assertEquals("main", node["name"].asText()) } } } @Test fun `Creating a branch in get mode from a project name`() { asAdmin { project { val data = run( """ mutation { createBranchOrGet(input: {projectName: "$name", name: "main"}) { branch { id name } errors { message exception } } } """ ) // Checks the errors assertNoUserError(data, "createBranchOrGet") val node = data["createBranchOrGet"]["branch"] assertEquals("main", node["name"].asText()) } } } @Test fun `Creating a branch in get mode for an existing branch from a project ID`() { asAdmin { project { val branch = branch(name = "main") val data = run( """ mutation { createBranchOrGet(input: {projectId: $id, name: "main"}) { branch { id name } errors { message exception } } } """ ) // Checks the errors assertNoUserError(data, "createBranchOrGet") val node = data["createBranchOrGet"]["branch"] assertEquals("main", node["name"].asText()) assertEquals(branch.id(), node["id"].asInt()) } } } @Test fun `Creating a branch in get mode for an existing branch from a project name`() { asAdmin { project { val branch = branch(name = "main") val data = run( """ mutation { createBranchOrGet(input: {projectName: "$name", name: "main"}) { branch { id name } errors { message exception } } } """ ) // Checks the errors assertNoUserError(data, "createBranchOrGet") val node = data["createBranchOrGet"]["branch"] assertEquals("main", node["name"].asText()) assertEquals(branch.id(), node["id"].asInt()) } } } @Test fun `All favourite branches`() { val account = doCreateAccount() val branch1 = project<Branch> { branch {} branch { asConfigurableAccount(account).withView(this).execute { branchFavouriteService.setBranchFavourite(this, true) } } } val branch2 = project<Branch> { branch {} branch { asConfigurableAccount(account).withView(this).execute { branchFavouriteService.setBranchFavourite(this, true) } } } // Gets ALL the favourite branches val data = asConfigurableAccount(account).withView(branch1).withView(branch2).call { run(""" { branches(favourite: true) { id } } """) } val branchIds: Set<Int> = data["branches"].map { it["id"].asInt() }.toSet() assertEquals( setOf(branch1.id(), branch2.id()), branchIds ) } @Test fun `Favourite branch on one project`() { val account = doCreateAccount() project { val fav = branch { asConfigurableAccount(account).withView(this).execute { branchFavouriteService.setBranchFavourite(this, true) } } branch {} // Gets the favourite branches val data = asConfigurableAccount(account).withView(this).call { run(""" { branches(project: "${this.name}", favourite: true) { id } } """) } val branchIds: Set<Int> = data["branches"].map { it["id"].asInt() }.toSet() assertEquals( setOf(fav.id()), branchIds ) } } @Test fun `Branch by name on two different projects`() { val name = uid("B") val p1 = doCreateProject() val b1 = doCreateBranch(p1, NameDescription.nd(name, "")) doCreateBranch(p1, NameDescription.nd("B2", "")) val p2 = doCreateProject() val b2 = doCreateBranch(p2, NameDescription.nd(name, "")) val data = run("""{branches (name: "$name") { id } }""") assertEquals( setOf(b1.id(), b2.id()), data["branches"].map { it["id"].asInt() }.toSet() ) } @Test fun `Last promotion run only`() { // Creates a branch val branch = doCreateBranch() // ... a promotion level val pl = doCreatePromotionLevel(branch, NameDescription.nd("COPPER", "")) // ... one build val build = doCreateBuild(branch, NameDescription.nd("1", "")) // ... and promotes it twice doPromote(build, pl, "Once") doPromote(build, pl, "Twice") // Asks for the promotion runs of the build val data = run("""{ |branches(id: ${branch.id}) { | builds { | promotionRuns(lastPerLevel: true) { | promotionLevel { | name | } | description | } | } |} |}""".trimMargin()) // Gets the first build val buildNode = data.path("branches").get(0).path("builds").get(0) // Gets the promotion runs val promotionRuns = buildNode.path("promotionRuns") assertEquals(1, promotionRuns.size()) val promotionRun = promotionRuns.get(0) assertEquals("Twice", promotionRun.path("description").asText()) assertEquals("COPPER", promotionRun.path("promotionLevel").path("name").asText()) } }
mit
a9125e142693daaec3087805808597cd
36.018913
139
0.406629
6.211027
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/processing/model/Repository.kt
1
1087
package net.nemerosa.ontrack.extension.github.ingestion.processing.model import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import net.nemerosa.ontrack.model.annotations.APIDescription @JsonIgnoreProperties(ignoreUnknown = true) data class Repository( @APIDescription("Name of the repository") val name: String, val description: String?, @APIDescription("Owner of the repository") val owner: Owner, @JsonProperty("html_url") @APIDescription("URL to the repository") val htmlUrl: String, ) { @JsonIgnore val fullName: String = "${owner.login}/$name" companion object { /** * Repository skeleton object from a owner and name */ fun stub(owner: String, name: String) = Repository( name = name, description = null, owner = Owner( login = owner, ), htmlUrl = "", ) } }
mit
d0b60658df0e1b2791951ed2fcfad72e
29.194444
72
0.631095
4.896396
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsCStringPointerInspection.kt
1
1185
package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import org.rust.lang.core.psi.RsCallExpr import org.rust.lang.core.psi.RsMethodCallExpr import org.rust.lang.core.psi.RsPathExpr import org.rust.lang.core.psi.RsVisitor class RsCStringPointerInspection : RsLocalInspectionTool() { override fun getDisplayName() = "Unsafe CString pointer" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitMethodCallExpr(expr: RsMethodCallExpr) { if (expr.identifier.text != "as_ptr") return val methodCallExpr = expr.expr if (methodCallExpr !is RsMethodCallExpr || methodCallExpr.identifier.text != "unwrap") return val callExpr = methodCallExpr.expr as? RsCallExpr ?: return val pathExpr = callExpr.expr if (pathExpr is RsPathExpr && pathExpr.path.identifier?.text == "new" && pathExpr.path.path?.identifier?.text == "CString") { holder.registerProblem(expr, displayName) } } } }
mit
0520f161858291e4e9ffb1f730bf07aa
39.862069
109
0.64135
4.74
false
false
false
false
olonho/carkot
translator/src/test/kotlin/tests/proto_repeated_zigzag/proto_repeated_zigzag.kt
1
17722
class MessageRepeatedZigZag private constructor (var int: IntArray, var long: LongArray) { //========== Properties =========== //repeated sint32 int = 1 //repeated sint64 long = 2 var errorCode: Int = 0 //========== Serialization methods =========== fun writeTo (output: CodedOutputStream) { //repeated sint32 int = 1 if (int.size > 0) { output.writeTag(1, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (int.size != 0) { do { var arraySize = 0 var i = 0 while (i < int.size) { arraySize += WireFormat.getSInt32SizeNoTag(int[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < int.size) { output.writeSInt32NoTag (int[i]) i += 1 } } while(false) } //repeated sint64 long = 2 if (long.size > 0) { output.writeTag(2, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (long.size != 0) { do { var arraySize = 0 var i = 0 while (i < long.size) { arraySize += WireFormat.getSInt64SizeNoTag(long[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < long.size) { output.writeSInt64NoTag (long[i]) i += 1 } } while(false) } } fun mergeWith (other: MessageRepeatedZigZag) { int = int.plus((other.int)) long = long.plus((other.long)) this.errorCode = other.errorCode } fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) { val builder = MessageRepeatedZigZag.BuilderMessageRepeatedZigZag(IntArray(0), LongArray(0)) mergeWith(builder.parseFromWithSize(input, expectedSize).build()) } fun mergeFrom (input: CodedInputStream) { val builder = MessageRepeatedZigZag.BuilderMessageRepeatedZigZag(IntArray(0), LongArray(0)) mergeWith(builder.parseFrom(input).build()) } //========== Size-related methods =========== fun getSize(fieldNumber: Int): Int { var size = 0 if (int.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < int.size) { arraySize += WireFormat.getSInt32SizeNoTag(int[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (long.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < long.size) { arraySize += WireFormat.getSInt64SizeNoTag(long[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED) return size } fun getSizeNoTag(): Int { var size = 0 if (int.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < int.size) { arraySize += WireFormat.getSInt32SizeNoTag(int[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (long.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < long.size) { arraySize += WireFormat.getSInt64SizeNoTag(long[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } return size } //========== Builder =========== class BuilderMessageRepeatedZigZag constructor (var int: IntArray, var long: LongArray) { //========== Properties =========== //repeated sint32 int = 1 fun setInt(value: IntArray): MessageRepeatedZigZag.BuilderMessageRepeatedZigZag { int = value return this } fun setintByIndex(index: Int, value: Int): MessageRepeatedZigZag.BuilderMessageRepeatedZigZag { int[index] = value return this } //repeated sint64 long = 2 fun setLong(value: LongArray): MessageRepeatedZigZag.BuilderMessageRepeatedZigZag { long = value return this } fun setlongByIndex(index: Int, value: Long): MessageRepeatedZigZag.BuilderMessageRepeatedZigZag { long[index] = value return this } var errorCode: Int = 0 //========== Serialization methods =========== fun writeTo (output: CodedOutputStream) { //repeated sint32 int = 1 if (int.size > 0) { output.writeTag(1, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (int.size != 0) { do { var arraySize = 0 var i = 0 while (i < int.size) { arraySize += WireFormat.getSInt32SizeNoTag(int[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < int.size) { output.writeSInt32NoTag (int[i]) i += 1 } } while(false) } //repeated sint64 long = 2 if (long.size > 0) { output.writeTag(2, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (long.size != 0) { do { var arraySize = 0 var i = 0 while (i < long.size) { arraySize += WireFormat.getSInt64SizeNoTag(long[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < long.size) { output.writeSInt64NoTag (long[i]) i += 1 } } while(false) } } //========== Mutating methods =========== fun build(): MessageRepeatedZigZag { val res = MessageRepeatedZigZag(int, long) res.errorCode = errorCode return res } fun parseFieldFrom(input: CodedInputStream): Boolean { if (input.isAtEnd()) { return false } val tag = input.readInt32NoTag() if (tag == 0) { return false } val fieldNumber = WireFormat.getTagFieldNumber(tag) val wireType = WireFormat.getTagWireType(tag) when(fieldNumber) { 1 -> { if (wireType.id != WireType.LENGTH_DELIMITED.id) { errorCode = 1 return false } val expectedByteSize = input.readInt32NoTag() var readSize = 0 var arraySize = 0 input.mark() do { var i = 0 while(readSize < expectedByteSize) { var tmp = 0 tmp = input.readSInt32NoTag() arraySize += 1 readSize += WireFormat.getSInt32SizeNoTag(tmp) } } while (false) val newArray = IntArray(arraySize) input.reset() do { var i = 0 while(i < arraySize) { newArray[i] = input.readSInt32NoTag() i += 1 } int = newArray } while (false) } 2 -> { if (wireType.id != WireType.LENGTH_DELIMITED.id) { errorCode = 1 return false } val expectedByteSize = input.readInt32NoTag() var readSize = 0 var arraySize = 0 input.mark() do { var i = 0 while(readSize < expectedByteSize) { var tmp = 0L tmp = input.readSInt64NoTag() arraySize += 1 readSize += WireFormat.getSInt64SizeNoTag(tmp) } } while (false) val newArray = LongArray(arraySize) input.reset() do { var i = 0 while(i < arraySize) { newArray[i] = input.readSInt64NoTag() i += 1 } long = newArray } while (false) } else -> errorCode = 4 } return true } fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): MessageRepeatedZigZag.BuilderMessageRepeatedZigZag { while(getSizeNoTag() < expectedSize) { parseFieldFrom(input) } if (getSizeNoTag() > expectedSize) { errorCode = 2 } return this } fun parseFrom(input: CodedInputStream): MessageRepeatedZigZag.BuilderMessageRepeatedZigZag { while(parseFieldFrom(input)) {} return this } //========== Size-related methods =========== fun getSize(fieldNumber: Int): Int { var size = 0 if (int.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < int.size) { arraySize += WireFormat.getSInt32SizeNoTag(int[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (long.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < long.size) { arraySize += WireFormat.getSInt64SizeNoTag(long[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED) return size } fun getSizeNoTag(): Int { var size = 0 if (int.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < int.size) { arraySize += WireFormat.getSInt32SizeNoTag(int[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (long.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < long.size) { arraySize += WireFormat.getSInt64SizeNoTag(long[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } return size } } } fun compareIntArrays(lhs: IntArray, rhs: IntArray): Boolean { if (lhs.size != rhs.size) { return false } var i = 0 while (i < lhs.size) { if (lhs[i] != rhs[i]) { return false } i += 1 } return true } fun compareLongArrays(lhs: LongArray, rhs: LongArray): Boolean { if (lhs.size != rhs.size) { return false } var i = 0 while (i < lhs.size) { if (lhs[i] != rhs[i]) { return false } i += 1 } return true } fun compareBooleanArrays(lhs: BooleanArray, rhs: BooleanArray): Boolean { if (lhs.size != rhs.size) { return false } var i = 0 while (i < lhs.size) { if (lhs[i] != rhs[i]) { return false } i += 1 } return true } fun compareRepeatedZigZags(kt1: MessageRepeatedZigZag, kt2: MessageRepeatedZigZag): Boolean { return compareIntArrays(kt1.int, kt2.int) and compareLongArrays(kt1.long, kt2.long) } fun checkRepZZSerializationIdentity(msg: MessageRepeatedZigZag): Int { val outs = CodedOutputStream(ByteArray(msg.getSizeNoTag())) msg.writeTo(outs) val ins = CodedInputStream(outs.buffer) val readMsg = MessageRepeatedZigZag.BuilderMessageRepeatedZigZag( IntArray(0), LongArray(0) ).parseFrom(ins).build() if (readMsg.errorCode != 0) { return 1 } if (compareRepeatedZigZags(msg, readMsg)) { return 0 } else { return 1 } } object Rng { var rngState = 0.6938893903907228 val point = 762939453125 fun rng(): Double { rngState *= point.toDouble() rngState -= rngState.toLong().toDouble() return rngState } } fun nextInt(minVal: Int, maxVal: Int): Int { return (Rng.rng() * (maxVal - minVal + 1).toDouble()).toInt() } fun nextLong(): Long { val lowerHalf = nextInt(-2147483647, 2147483647) val upperHalf = nextInt(-2147483647, 2147483647) return (upperHalf.toLong() shl 32) + lowerHalf.toLong() } fun generateIntArray(): IntArray { val size = nextInt(0, 10000) val arr = IntArray(size) var i = 0 while (i < size) { arr[i] = nextInt(-2147483647, 2147483647) i += 1 } return arr } fun generateLongArray(): LongArray { val size = nextInt(0, 10000) val arr = LongArray(size) var i = 0 while (i < size) { arr[i] = nextLong() i += 1 } return arr } fun generateRandomMessage(): MessageRepeatedZigZag { return MessageRepeatedZigZag.BuilderMessageRepeatedZigZag( generateIntArray(), generateLongArray() ).build() } fun testRepZigZag(): Int { var i = 0 val testRuns = 8 while (i < testRuns) { val msg = generateRandomMessage() if (checkRepZZSerializationIdentity(msg) == 1) { return 1 } i += 1 } return 0 } fun testArraysOfMinValues(): Int { val intArr = IntArray(100) var i = 0 while (i < 100) { intArr[i] = -2147483647 i += 1 } val longArr = LongArray(100) i = 0 while (i < 100) { longArr[i] = -9223372036854775807L i += 1 } val msg = MessageRepeatedZigZag.BuilderMessageRepeatedZigZag(intArr, longArr).build() return checkRepZZSerializationIdentity(msg) } fun testArraysOfMaxValues(): Int { val intArr = IntArray(100) var i = 0 while (i < 100) { intArr[i] = 2147483647 i += 1 } val longArr = LongArray(100) i = 0 while (i < 100) { longArr[i] = 9223372036854775807L i += 1 } val msg = MessageRepeatedZigZag.BuilderMessageRepeatedZigZag(intArr, longArr).build() return checkRepZZSerializationIdentity(msg) } fun testArraysOfDefaultValues(): Int { val intArr = IntArray(100) val longArr = LongArray(100) val msg = MessageRepeatedZigZag.BuilderMessageRepeatedZigZag(intArr, longArr).build() return checkRepZZSerializationIdentity(msg) }
mit
dec96c5e2d88d8087c50332c371abac0
30.257496
127
0.460388
4.8487
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/main/ChannelListFragment.kt
1
3509
package de.xikolo.controllers.main import android.os.Bundle import android.view.View import butterknife.BindView import de.xikolo.App import de.xikolo.R import de.xikolo.controllers.channels.ChannelDetailsActivityAutoBundle import de.xikolo.controllers.course.CourseActivityAutoBundle import de.xikolo.extensions.observe import de.xikolo.models.Channel import de.xikolo.models.Course import de.xikolo.viewmodels.main.ChannelListViewModel import de.xikolo.views.AutofitRecyclerView import de.xikolo.views.SpaceItemDecoration class ChannelListFragment : MainFragment<ChannelListViewModel>() { companion object { val TAG: String = ChannelListFragment::class.java.simpleName } @BindView(R.id.content_view) internal lateinit var recyclerView: AutofitRecyclerView private lateinit var channelListAdapter: ChannelListAdapter override val layoutResource = R.layout.fragment_channel_list override fun createViewModel(): ChannelListViewModel { return ChannelListViewModel() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) channelListAdapter = ChannelListAdapter(object : ChannelListAdapter.OnChannelCardClickListener { override fun onChannelClicked(channelId: String) { val intent = ChannelDetailsActivityAutoBundle .builder(channelId) .build(App.instance) startActivity(intent) } override fun onCourseClicked(course: Course) { val intent = CourseActivityAutoBundle .builder() .courseId(course.id) .build(App.instance) startActivity(intent) } override fun onMoreCoursesClicked(channelId: String, scrollPosition: Int) { val intent = ChannelDetailsActivityAutoBundle .builder(channelId) .scrollToCoursePosition(scrollPosition) .build(App.instance) startActivity(intent) } }) recyclerView.adapter = channelListAdapter recyclerView.addItemDecoration(SpaceItemDecoration( activity!!.resources.getDimensionPixelSize(R.dimen.card_horizontal_margin), activity!!.resources.getDimensionPixelSize(R.dimen.card_vertical_margin), false, object : SpaceItemDecoration.RecyclerViewInfo { override fun isHeader(position: Int): Boolean { return false } override val spanCount: Int get() = recyclerView.spanCount override val itemCount: Int get() = channelListAdapter.itemCount } )) viewModel.channels .observe(viewLifecycleOwner) { showChannelList( it, viewModel.buildCourseLists(it)) } } private fun showChannelList(channelList: List<Channel>, courseLists: List<List<Course>>) { channelListAdapter.update(channelList, courseLists) showContent() } override fun onStart() { super.onStart() activityCallback?.onFragmentAttached(R.id.navigation_channels) } }
bsd-3-clause
ab6fe133b161168859e4e9dbf84278c6
32.419048
104
0.644913
5.517296
false
false
false
false
groupdocs-comparison/GroupDocs.Comparison-for-Java
Demos/Compose/src/main/kotlin/com/groupdocs/ui/theme/Color.kt
1
573
package com.groupdocs.ui.theme import androidx.compose.ui.graphics.Color val BlueLight = Color(0xFF64a1ff) val Blue = Color(0xFF0873e5) val BlueDark = Color(0xFF0049b2) val GreenLight = Color(0xFF9afa59) val Green = Color(0xFF65c621) val GreenDark = Color(0xFF2a9400) val WhiteLight = Color(0xFFf2f2f2) val WhiteDark = Color(0xFFbfbfbf) val BlackLight = Color(0xFF2d2d2d) val BlackDark = Color(0xFF020202) val RedDark = Color(0xFFD70000) val RedLight = Color(0xFFF20000) val GrayLight = Color(0xFFe7e7e7) val Gray = Color(0xFF3e4e5a) val GrayDark = Color(0xFF222e35)
mit
c0865ec024a28f7ad747166ad298ce80
22.916667
41
0.787086
2.469828
false
false
false
false
Orchextra/orchextra-android-sdk
core/src/test/java/com/gigigo/orchextra/core/entities/TriggerTest.kt
1
2727
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.entities import com.gigigo.orchextra.core.domain.entities.Trigger import com.gigigo.orchextra.core.domain.entities.TriggerType.BEACON import com.gigigo.orchextra.core.domain.entities.TriggerType.BEACON_REGION import com.gigigo.orchextra.core.domain.entities.TriggerType.EDDYSTONE import com.gigigo.orchextra.core.domain.entities.TriggerType.EDDYSTONE_REGION import com.gigigo.orchextra.core.domain.entities.TriggerType.GEOFENCE import com.gigigo.orchextra.core.domain.entities.TriggerType.QR import com.gigigo.orchextra.core.domain.entities.TriggerType.VOID import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.junit.Test class TriggerTest { @Test fun shouldBeAVoidTrigger() { val trigger = Trigger(VOID, "") val isVoid = trigger.isVoid() isVoid.shouldBeTrue() } @Test fun beaconShouldBeABackgroundTrigger() { val trigger = BEACON withValue "test" val isBackgroundTrigger = trigger.isBackgroundTrigger() isBackgroundTrigger.shouldBeTrue() } @Test fun beaconRegionShouldBeABackgroundTrigger() { val trigger = BEACON_REGION withValue "test" val isBackgroundTrigger = trigger.isBackgroundTrigger() isBackgroundTrigger.shouldBeTrue() } @Test fun eddystoneShouldBeABackgroundTrigger() { val trigger = EDDYSTONE withValue "test" val isBackgroundTrigger = trigger.isBackgroundTrigger() isBackgroundTrigger.shouldBeTrue() } @Test fun eddystoneRegionShouldBeABackgroundTrigger() { val trigger = EDDYSTONE_REGION withValue "test" val isBackgroundTrigger = trigger.isBackgroundTrigger() isBackgroundTrigger.shouldBeTrue() } @Test fun geofenceShouldBeABackgroundTrigger() { val trigger = GEOFENCE withValue "test" val isBackgroundTrigger = trigger.isBackgroundTrigger() isBackgroundTrigger.shouldBeTrue() } @Test fun qrShouldNotBeABackgroundTrigger() { val trigger = QR withValue "test" val isBackgroundTrigger = trigger.isBackgroundTrigger() isBackgroundTrigger.shouldBeFalse() } }
apache-2.0
b0fad1a8a99c94fa2126fd588aeae6b1
27.123711
77
0.767143
4.241058
false
true
false
false
Jire/Abendigo
src/main/kotlin/org/abendigo/plugin/csgo/GlowModelsPlugin.kt
1
3454
package org.abendigo.plugin.csgo import org.abendigo.csgo.* import org.abendigo.csgo.Client.glowObject import org.abendigo.csgo.Client.glowObjectCount import org.abendigo.csgo.offsets.m_bDormant import org.jire.arrowhead.get object GlowModelsPlugin : InGamePlugin("Glow Models", duration = 4) { override val author = "Jire" override val description = "Outlines players with a special glow" private const val PLAYER_ALPHA = 0.8F private const val REDUCE_ALPHA_UNSPOTTED = 0.7F /* set to 1.0F to not reduce */ private const val SHOW_TEAM = true private const val SHOW_DORMANT = false private const val SHOW_BOMB = true private const val SHOW_WEAPONS = false // can crash game private const val SHOW_GRENADES = false // can crash game private const val SHOW_CHICKENS = false private const val CHANGE_MODEL_COLORS = true override fun cycle() { glow@ for (glIdx in 0..+glowObjectCount) { val glowAddress: Int = +glowObject + (glIdx * GLOW_OBJECT_SIZE) if (glowAddress <= 0) continue val entityAddress: Int = csgo[glowAddress] if (entityAddress <= 0) continue for ((i, p) in Client.players) { if (entityAddress != p.address || +p.dead) continue val dormant = +p.dormant if (!SHOW_DORMANT && dormant) continue var red = 255 var green = 0 var blue = 0 var alpha = PLAYER_ALPHA if (!+p.spotted) alpha *= REDUCE_ALPHA_UNSPOTTED val myTeam = +Me().team val pTeam = +p.team if (myTeam == pTeam) { if (!SHOW_TEAM) continue red = 0 blue = 255 } else if (SHOW_DORMANT && dormant) { blue = 255 green = 255 alpha = 0.75F } if (p.address == +Me.targetAddress) green = 215 else if (p.hasWeapon(Weapons.C4)) { blue = 255 green = 0 red = 255 alpha = 0.8F } glow(glowAddress, red, green, blue, alpha) if (CHANGE_MODEL_COLORS) modelColors(entityAddress, red.toByte(), green.toByte(), blue.toByte()) continue@glow } val type = EntityType.byEntityAddress(entityAddress) ?: continue if (SHOW_WEAPONS && type.weapon) glow(glowAddress, 0, 255, 0, 0.75F) else if (SHOW_GRENADES && (type.grenade || type == EntityType.CSpatialEntity || type == EntityType.CMovieDisplay || type == EntityType.CSpotlightEnd)) glow(glowAddress, 0, 255, 0) else if (SHOW_CHICKENS && type == EntityType.CChicken) { val dormant: Boolean = csgo[entityAddress + m_bDormant] if (!dormant) glow(glowAddress, 255, 0, 0) } else if (SHOW_BOMB && (type == EntityType.CC4 || type == EntityType.CPlantedC4 || type == EntityType.CTEPlantBomb || type == EntityType.CPlasma)) glow(glowAddress, 255, 0, 255) } } private fun glow(glowAddress: Int, red: Int, green: Int, blue: Int, alpha: Float = 1F, occluded: Boolean = true, unoccluded: Boolean = false, fullBloom: Boolean = false, special: Boolean = true) { csgo[glowAddress + 0x4] = red / 255F csgo[glowAddress + 0x8] = green / 255F csgo[glowAddress + 0xC] = blue / 255F csgo[glowAddress + 0x10] = alpha csgo[glowAddress + 0x24] = occluded csgo[glowAddress + 0x25] = unoccluded csgo[glowAddress + 0x26] = fullBloom csgo[glowAddress + 0x2C] = special } private fun modelColors(entityAddress: Int, red: Byte, green: Byte, blue: Byte, alpha: Byte = 255.toByte()) { csgo[entityAddress + 0x70] = red csgo[entityAddress + 0x71] = green csgo[entityAddress + 0x72] = blue csgo[entityAddress + 0x73] = alpha } }
gpl-3.0
e3cc1fde949bcb3febfd94c892fdb2ce
30.990741
127
0.670816
3.064774
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/controller/sudoku/hints/HintFormulator.kt
1
7185
package de.sudoq.controller.sudoku.hints import android.content.Context import android.content.pm.PackageManager import android.util.Log import androidx.core.content.pm.PackageInfoCompat import de.sudoq.R import de.sudoq.controller.menus.Utility import de.sudoq.controller.sudoku.SudokuActivity import de.sudoq.model.solverGenerator.solution.* import de.sudoq.model.solvingAssistant.HintTypes import de.sudoq.model.sudoku.getGroupShape import java.util.* /** * Created by timo on 04.10.16. */ object HintFormulator { private const val LOG_TAG = "HintFormulator" @JvmStatic fun getText(context: Context, sd: SolveDerivation): String { Log.d("HintForm", sd.type.toString()) return when (sd.type) { HintTypes.LastDigit -> lastDigitText(context, sd) HintTypes.LastCandidate -> lastCandidateText(context, sd) HintTypes.LeftoverNote -> leftoverNoteText(context, sd) HintTypes.NakedSingle -> nakedSingleText(context, sd) HintTypes.NakedPair, HintTypes.NakedTriple, HintTypes.NakedQuadruple, HintTypes.NakedQuintuple -> nakedMultiple(context, sd) HintTypes.HiddenSingle -> hiddenSingleText(context, sd) HintTypes.HiddenPair, HintTypes.HiddenTriple, HintTypes.HiddenQuadruple, HintTypes.HiddenQuintuple -> hiddenMultiple(context, sd) HintTypes.LockedCandidatesExternal -> lockedCandidates(context, sd) HintTypes.XWing -> xWing(context, sd) HintTypes.NoNotes -> { context.getString(R.string.hint_backtracking) + context.getString(R.string.hint_fill_out_notes) } HintTypes.Backtracking -> context.getString(R.string.hint_backtracking) else -> "We found a hint, but did not implement a representation yet. That's a bug! Please send us a screenshot so we can fix it!" } } private fun aCellIsEmpty(sActivity: SudokuActivity): Boolean { val sudoku = sActivity.game!!.sudoku return sudoku!!.any { it.isCompletelyEmpty } } private fun lastDigitText(context: Context, sd: SolveDerivation): String { val d = sd as LastDigitDerivation val cs = d.constraintShape val shapeString = Utility.constraintShapeAccDet2string(context, cs) val shapeGender = Utility.getGender(context, cs) val shapeDeterminer = Utility.gender2AccDeterminer(context, shapeGender) val highlightSuffix = Utility.gender2AccSufix(context, shapeGender) return context.getString(R.string.hint_lastdigit) .replace("{shape}", shapeString!!) .replace("{determiner}", shapeDeterminer!!) .replace("{suffix}", highlightSuffix!!) } private fun lastCandidateText(context: Context, sd: SolveDerivation): String { return context.getString(R.string.hint_lastcandidate) } private fun leftoverNoteText(context: Context, sd: SolveDerivation): String { val d = sd as LeftoverNoteDerivation val cs = d.constraintShape val shapeString = Utility.constraintShapeAccDet2string(context, cs) val shapeGender = Utility.getGender(context, cs) val shapeDeterminer = Utility.gender2AccDeterminer(context, shapeGender) val highlightSuffix = Utility.gender2AccSufix(context, shapeGender) var versionNumber = -1 try { val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) val longVersionCode = PackageInfoCompat.getLongVersionCode(pInfo) versionNumber = longVersionCode.toInt() //versionNumber = pinfo.versionCode; } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } Log.d(LOG_TAG, "leftovernotetext is called. and versionNumber is: $versionNumber") return context.getString(R.string.hint_leftovernote) .replace("{note}", (d.note + 1).toString()) .replace("{shape}", shapeString!!) .replace("{determiner}", shapeDeterminer!!) .replace("{suffix}", highlightSuffix!!) } private fun nakedSingleText(context: Context, sd: SolveDerivation): String { val d = sd as NakedSetDerivation val bs = d.getSubsetMembers()[0].relevantCandidates val note = bs.nextSetBit(0) + 1 val sb = StringBuilder() sb.append(context.getString(R.string.hint_nakedsingle_look)) sb.append(' ') sb.append( context.getString(R.string.hint_nakedsingle_note) .replace("{note}", note.toString() + "") ) sb.append(' ') val shapeString = Utility.constraintShapeGenDet2string(context, getGroupShape(d.constraint!!)) val shapePrepDet = Utility.getGender(context, getGroupShape(d.constraint!!)) val prepDet = Utility.gender2inThe(context, shapePrepDet!!) sb.append( context.getString(R.string.hint_nakedsingle_remove) .replace("{prep det}", prepDet!!) .replace("{shape}", shapeString!!) ) return sb.toString() } private fun nakedMultiple(context: Context, sd: SolveDerivation): String { val bs: BitSet = (sd as NakedSetDerivation).subsetCandidates!! val symbols: MutableList<Int> = mutableListOf() //collect all set bits, we assume there will never be an overflow var i = bs.nextSetBit(0) while (i >= 0) { symbols.add(i) i = bs.nextSetBit(i + 1) } val symbolsString = symbols .map { +1 } //add one for user representation .joinToString(", ", "{", "}", transform = { it.toString() }) return context.getString(R.string.hint_nakedset).replace("{symbols}", symbolsString) } private fun hiddenSingleText( context: Context, sd: SolveDerivation ): String { //TODO this should never be used but already be taken by a special hit that just says: Look at this cell, only one left can go; val bs = (sd as HiddenSetDerivation).getSubsetMembers()[0].relevantCandidates val note = (bs.nextSetBit(0) + 1).toString() return context.getString(R.string.hint_hiddensingle).replace("{note}", note) } private fun hiddenMultiple(context: Context, sd: SolveDerivation): String { val bs = (sd as HiddenSetDerivation).subsetCandidates val hiddenMultiples = bs!!.setBits .map { +1 } .joinToString(", ", "{", "}", transform = { it.toString() }) return context.getString(R.string.hint_hiddenset).replace("{symbols}", hiddenMultiples) } private fun lockedCandidates(context: Context, sd: SolveDerivation): String { val note = (sd as LockedCandidatesDerivation).getNote().toString() return context.getString(R.string.hint_lockedcandidates).replace("{note}", note) } private fun xWing(context: Context, sd: SolveDerivation): String { //int note = ((XWingDerivation) sd).getNote(); return context.getString(R.string.hint_xWing) } }
gpl-3.0
a53ab85f61ec20412555925943d1558a
42.551515
143
0.651775
4.292115
false
false
false
false
AndroidX/androidx
compose/runtime/runtime/src/jvmMain/kotlin/androidx/compose/runtime/ActualJvm.jvm.kt
3
3833
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime import androidx.compose.runtime.internal.ThreadMap import androidx.compose.runtime.internal.emptyThreadMap import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.runtime.snapshots.SnapshotContextElement import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.ThreadContextElement internal actual typealias AtomicReference<V> = java.util.concurrent.atomic.AtomicReference<V> internal actual open class ThreadLocal<T> actual constructor( private val initialValue: () -> T ) : java.lang.ThreadLocal<T>() { @Suppress("UNCHECKED_CAST") actual override fun get(): T { return super.get() as T } actual override fun set(value: T) { super.set(value) } override fun initialValue(): T? { return initialValue.invoke() } actual override fun remove() { super.remove() } } internal actual class SnapshotThreadLocal<T> { private val map = AtomicReference<ThreadMap>(emptyThreadMap) private val writeMutex = Any() @Suppress("UNCHECKED_CAST") actual fun get(): T? = map.get().get(Thread.currentThread().id) as T? actual fun set(value: T?) { val key = Thread.currentThread().id synchronized(writeMutex) { val current = map.get() if (current.trySet(key, value)) return map.set(current.newWith(key, value)) } } } internal actual fun identityHashCode(instance: Any?): Int = System.identityHashCode(instance) @PublishedApi internal actual inline fun <R> synchronized(lock: Any, block: () -> R): R { return kotlin.synchronized(lock, block) } internal actual typealias TestOnly = org.jetbrains.annotations.TestOnly internal actual fun invokeComposable(composer: Composer, composable: @Composable () -> Unit) { @Suppress("UNCHECKED_CAST") val realFn = composable as Function2<Composer, Int, Unit> realFn(composer, 1) } internal actual fun <T> invokeComposableForResult( composer: Composer, composable: @Composable () -> T ): T { @Suppress("UNCHECKED_CAST") val realFn = composable as Function2<Composer, Int, T> return realFn(composer, 1) } internal actual class AtomicInt actual constructor(value: Int) { val delegate = java.util.concurrent.atomic.AtomicInteger(value) actual fun get(): Int = delegate.get() actual fun set(value: Int) = delegate.set(value) actual fun add(amount: Int): Int = delegate.addAndGet(amount) } internal actual fun ensureMutable(it: Any) { /* NOTHING */ } /** * Implementation of [SnapshotContextElement] that enters a single given snapshot when updating * the thread context of a resumed coroutine. */ @ExperimentalComposeApi internal actual class SnapshotContextElementImpl actual constructor( private val snapshot: Snapshot ) : SnapshotContextElement, ThreadContextElement<Snapshot?> { override val key: CoroutineContext.Key<*> get() = SnapshotContextElement override fun updateThreadContext(context: CoroutineContext): Snapshot? = snapshot.unsafeEnter() override fun restoreThreadContext(context: CoroutineContext, oldState: Snapshot?) { snapshot.unsafeLeave(oldState) } }
apache-2.0
78f3851ed41302f55831dc50e0c9f71a
32.051724
95
0.719802
4.331073
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/timeTracker/TimeTrackingConfigurator.kt
1
4792
package com.github.jk1.ytplugin.timeTracker import com.github.jk1.ytplugin.ComponentAware import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.logger import com.github.jk1.ytplugin.rest.AdminRestClient import com.github.jk1.ytplugin.rest.MulticatchException.Companion.multicatchException import com.github.jk1.ytplugin.rest.TimeTrackerRestClient import com.github.jk1.ytplugin.setup.SetupDialog import com.github.jk1.ytplugin.tasks.NoActiveYouTrackTaskException import com.github.jk1.ytplugin.tasks.YouTrackServer import com.github.jk1.ytplugin.timeTracker.actions.StartTrackerAction import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager import org.apache.http.conn.HttpHostConnectException import java.net.SocketException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.util.concurrent.Callable import java.util.concurrent.Future import java.util.concurrent.TimeUnit class TimeTrackingConfigurator { fun getTypesInCallable(repo: YouTrackServer): List<String> { val future = ApplicationManager.getApplication().executeOnPooledThread( Callable { getAvailableWorkItemsTypes(repo) }) return future.get() } fun getAvailableWorkItemsTypes(repo: YouTrackServer): List<String> { return TimeTrackerRestClient(repo).getAvailableWorkItemTypes().keys.toList() } private fun configureTimerForTracking(timeTrackingDialog: SetupDialog, project: Project) { val timer = ComponentAware.of(project).timeTrackerComponent val inactivityTime = TimeUnit.HOURS.toMillis(timeTrackingDialog.inactivityHours.toLong()) + TimeUnit.MINUTES.toMillis(timeTrackingDialog.inactivityMinutes.toLong()) logger.debug("Manual mode is selected: ${timeTrackingDialog.manualModeCheckbox.isSelected}") logger.debug("Auto mode is selected: ${timeTrackingDialog.autoTrackingEnabledCheckBox.isSelected}") timer.setupTimerProperties(timeTrackingDialog.autoTrackingEnabledCheckBox.isSelected, timeTrackingDialog.manualModeCheckbox.isSelected, inactivityTime) timer.timeInMills = 0 timer.pausedTime = 0 timer.isAutoTrackingTemporaryDisabled = false } fun setupTimeTracking(timeTrackingDialog: SetupDialog, project: Project) { val timer = ComponentAware.of(project).timeTrackerComponent configureTimerForTracking(timeTrackingDialog, project) try { if (ComponentAware.of(project).taskManagerComponent.getActiveTask().isDefault && (timer.isManualTrackingEnabled || timer.isAutoTrackingEnabled)) { notifySelectTask() } else { if (timer.isAutoTrackingEnabled) { try { ComponentAware.of(project).taskManagerComponent.getActiveYouTrackTask() StartTrackerAction().startAutomatedTracking(project, timer) } catch (e: NoActiveYouTrackTaskException) { notifySelectTask() } } else { val bar = project.let { it1 -> WindowManager.getInstance().getStatusBar(it1) } bar?.removeWidget("Time Tracking Clock") timer.activityTracker?.dispose() } } } catch (e: NoActiveYouTrackTaskException) { notifySelectTask() } } fun checkIfTrackingIsEnabledForIssue(repo: YouTrackServer, selectedIssueIndex: Int, ids: List<Issue>): Future<*> { return ApplicationManager.getApplication().executeOnPooledThread( Callable { try { if (selectedIssueIndex != -1) AdminRestClient(repo).checkIfTrackingIsEnabled(ids[selectedIssueIndex].projectName) else false } catch (e: Exception) { e.multicatchException(HttpHostConnectException::class.java, SocketException::class.java, UnknownHostException::class.java, SocketTimeoutException::class.java) { logger.warn("Exception in manual time tracker: ${e.message}") } } }) } private fun notifySelectTask() { val note = "To start using time tracking please select active task on the toolbar" + " or by pressing Shift + Alt + T" val trackerNote = TrackerNotification() trackerNote.notifyWithHelper(note, NotificationType.INFORMATION, OpenActiveTaskSelection()) } }
apache-2.0
c039d2253aade84c7bc1dce436420c8e
41.04386
118
0.683639
4.981289
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/ComponentAware.kt
1
2695
package com.github.jk1.ytplugin import com.github.jk1.ytplugin.commands.CommandService import com.github.jk1.ytplugin.commands.ICommandService import com.github.jk1.ytplugin.issues.IssueStoreUpdaterService import com.github.jk1.ytplugin.issues.PersistentIssueStore import com.github.jk1.ytplugin.navigator.SourceNavigatorService import com.github.jk1.ytplugin.setup.CredentialsChecker import com.github.jk1.ytplugin.tasks.TaskManagerProxyService import com.github.jk1.ytplugin.timeTracker.IssueWorkItemsStoreUpdaterService import com.github.jk1.ytplugin.timeTracker.PersistentIssueWorkItemsStore import com.github.jk1.ytplugin.timeTracker.SpentTimePerTaskStorage import com.github.jk1.ytplugin.timeTracker.TimeTracker import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project interface ComponentAware { val project: Project companion object { fun of(aProject: Project): ComponentAware = object : ComponentAware { override val project: Project = aProject } fun <T> of(aProject: Project, closure: ComponentAware.() -> T): T = with(of(aProject)) { closure.invoke(this) } } val taskManagerComponent: TaskManagerProxyService get() = project.getService(TaskManagerProxyService::class.java)!! val commandComponent: ICommandService get() = project.getService(CommandService::class.java)!! val sourceNavigatorComponent: SourceNavigatorService get() = project.getService(SourceNavigatorService::class.java)!! val issueWorkItemsStoreComponent: PersistentIssueWorkItemsStore get() = ApplicationManager.getApplication().getService(PersistentIssueWorkItemsStore::class.java)!! val issueWorkItemsUpdaterComponent: IssueWorkItemsStoreUpdaterService get() = project.getService(IssueWorkItemsStoreUpdaterService::class.java)!! val issueStoreComponent: PersistentIssueStore get() = ApplicationManager.getApplication().getService(PersistentIssueStore::class.java)!! val issueUpdaterComponent: IssueStoreUpdaterService get() = project.getService(IssueStoreUpdaterService::class.java)!! val pluginApiComponent: YouTrackPluginApiService get() = project.getService(YouTrackPluginApiService::class.java) as YouTrackPluginApiService val timeTrackerComponent: TimeTracker get() = project.getService(TimeTracker::class.java)!! val credentialsCheckerComponent: CredentialsChecker get() = project.getService(CredentialsChecker::class.java)!! val spentTimePerTaskStorage: SpentTimePerTaskStorage get() = project.getService(SpentTimePerTaskStorage::class.java)!! }
apache-2.0
0186fc0ec721d338009c2ea9577d5c3c
38.647059
107
0.779592
4.686957
false
false
false
false
ryan652/EasyCrypt
appKotlin/src/main/java/com/pvryan/easycryptsample/action/FragmentSymmetricFile.kt
1
4519
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycryptsample.action import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.pvryan.easycrypt.ECResultListener import com.pvryan.easycrypt.symmetric.ECSymmetric import com.pvryan.easycryptsample.R import com.pvryan.easycryptsample.extensions.hide import com.pvryan.easycryptsample.extensions.show import com.pvryan.easycryptsample.extensions.snackLong import com.pvryan.easycryptsample.extensions.snackShort import kotlinx.android.synthetic.main.fragment_symmetric_file.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.support.v4.onUiThread import java.io.File class FragmentSymmetricFile : Fragment(), AnkoLogger, ECResultListener { private val _rCEncrypt = 2 private val _rCDecrypt = 3 private val eCryptSymmetric = ECSymmetric() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_symmetric_file, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) buttonSelectEncryptF.setOnClickListener { if (edPasswordF.text.toString() != "") selectFile(_rCEncrypt) else view.snackShort("Password cannot be empty!") } buttonSelectDecryptF.setOnClickListener { if (edPasswordF.text.toString() != "") selectFile(_rCDecrypt) else view.snackShort("Password cannot be empty!") } } private fun selectFile(requestCode: Int) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "*/*" startActivityForResult(intent, requestCode) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { val fis = context?.contentResolver?.openInputStream(data?.data) progressBarF.show() when (requestCode) { _rCEncrypt -> { tvStatus.text = resources.getString(R.string.tv_status_encrypting) eCryptSymmetric.encrypt(fis, edPasswordF.text.toString(), this) } _rCDecrypt -> { tvStatus.text = resources.getString(R.string.tv_status_decrypting) eCryptSymmetric.decrypt(fis, edPasswordF.text.toString(), this) } } } } private var maxSet = false override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) { if (totalBytes > -1) { onUiThread { if (!maxSet) { progressBarF.isIndeterminate = false progressBarF.max = (totalBytes / 1024).toInt() maxSet = true } progressBarF.progress = (bytesProcessed / 1024).toInt() } } } override fun <T> onSuccess(result: T) { onUiThread { progressBarF.hide() tvStatus.text = getString(R.string.tv_status_idle) tvResultF.text = resources.getString( R.string.success_result_to_file, (result as File).absolutePath) } } override fun onFailure(message: String, e: Exception) { e.printStackTrace() onUiThread { progressBarF.hide() tvStatus.text = getString(R.string.tv_status_idle) llContentSFile.snackLong("Error: $message") } } companion object { fun newInstance(): Fragment = FragmentSymmetricFile() } }
apache-2.0
ef7a9682ca116344dd283d761ceee808
34.582677
90
0.64771
4.569262
false
false
false
false
charleskorn/batect
app/src/main/kotlin/batect/cli/commands/HelpCommand.kt
1
3556
/* Copyright 2017-2020 Charles Korn. 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 batect.cli.commands import batect.cli.CommandLineOptionsParser import batect.cli.options.OptionDefinition import batect.cli.options.OptionGroup import batect.ui.ConsoleDimensions import batect.utils.breakAt import java.io.PrintStream class HelpCommand( val optionsParser: CommandLineOptionsParser, val outputStream: PrintStream, val consoleDimensions: ConsoleDimensions ) : Command { private val consoleWidth: Int = consoleDimensions.current?.width ?: Int.MAX_VALUE override fun run(): Int { outputStream.println("Usage: batect [options] task [-- additional arguments to pass to task]") outputStream.println() val options = optionsParser.optionParser.getOptions().associateWith { nameFor(it) } val alignToColumn = determineColumnSize(options.values) val lines = options.map { (option, name) -> OptionLine(option.group, option.longName, formatInColumn(name, option.descriptionForHelp, alignToColumn)) } lines .sortedBy { it.group.name } .groupBy { it.group } .forEach { (group, options) -> outputStream.println(group.name + ":") options.sortedBy { it.longName }.forEach { outputStream.print(it.text) } outputStream.println() } outputStream.println(CommandLineOptionsParser.helpBlurb) outputStream.println() return 1 } private fun nameFor(option: OptionDefinition): String { val longNamePart = if (option.acceptsValue) "${option.longOption}=${option.valueFormatForHelp}" else option.longOption return when { option.shortName == null -> " $longNamePart" else -> "${option.shortOption}, $longNamePart" } } private fun determineColumnSize(optionNames: Iterable<String>): Int = optionNames.map { it.length }.max() ?: 0 private fun formatInColumn(first: String, second: String, alignToColumn: Int): String { val firstLineIndentationCount = 4 + alignToColumn - first.length val firstLineIndentation = " ".repeat(firstLineIndentationCount) val secondLineIndentationCount = 6 + alignToColumn val secondLineIndentation = " ".repeat(secondLineIndentationCount) val secondColumnWidth = consoleWidth - secondLineIndentationCount val secondColumnLines = second.breakAt(secondColumnWidth).lines() val secondColumn = alternate(secondColumnLines, secondLineIndentation) return " $first$firstLineIndentation$secondColumn" } private fun alternate(lines: List<String>, separator: String): String { val builder = StringBuilder() builder.appendln(lines.first()) lines.drop(1).forEach { builder.append(separator) builder.appendln(it) } return builder.toString() } data class OptionLine(val group: OptionGroup, val longName: String, val text: String) }
apache-2.0
8a82bb4dca4ccd6f692650cd0529d508
36.041667
159
0.692632
4.703704
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/leaderboard/MemberViewHolder.kt
1
2007
/* * Copyright 2020 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 * * 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.app.playhvz.screens.leaderboard import android.view.View import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.RecyclerView import com.app.playhvz.R import com.app.playhvz.common.UserAvatarPresenter import com.app.playhvz.firebase.classmodels.Player class MemberViewHolder(val view: View, private val viewProfile: ((playerId: String) -> Unit)?) : RecyclerView.ViewHolder(view) { private val avatarView = view.findViewById<ConstraintLayout>(R.id.player_avatar_container)!! private val nameView = view.findViewById<TextView>(R.id.player_name)!! private val allegianceView = view.findViewById<TextView>(R.id.player_allegiance)!! private val pointView = view.findViewById<TextView>(R.id.player_points)!! private var player: Player? = null fun onBind(player: Player?) { this.player = player updateDisplayedPlayerData(player!!) if (viewProfile != null) { view.setOnClickListener { viewProfile.invoke(player.id!!) } } } private fun updateDisplayedPlayerData(player: Player) { val userAvatarPresenter = UserAvatarPresenter(avatarView, R.dimen.avatar_large) userAvatarPresenter.renderAvatar(player) nameView.text = player.name allegianceView.text = player.allegiance pointView.text = player.points.toString() } }
apache-2.0
d99ca49b1badcc839b33107b7bbb2893
37.615385
96
0.737419
4.270213
false
false
false
false
googlecodelabs/wear-tiles
start/src/main/java/com/example/wear/tiles/messaging/tile/Images.kt
2
2692
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.wear.tiles.messaging.tile import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import androidx.wear.tiles.RequestBuilders import coil.ImageLoader import coil.request.ImageRequest import coil.transform.CircleCropTransformation import com.example.wear.tiles.messaging.Contact import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope /** * Each contact in the tile state could have an avatar (represented by image url). * * If the image resources are requested (the ID is in [requestParams] or no IDs were specified), * then we fetch them from the network in this suspending function, returning the resulting bitmaps. */ internal suspend fun ImageLoader.fetchAvatarsFromNetwork( context: Context, requestParams: RequestBuilders.ResourcesRequest, tileState: MessagingTileState, ): Map<Contact, Bitmap> { val requestedAvatars: List<Contact> = if (requestParams.resourceIds.isEmpty()) { tileState.contacts } else { tileState.contacts.filter { contact -> requestParams.resourceIds.contains(contact.imageResourceId()) } } val images = coroutineScope { requestedAvatars.map { contact -> async { val image = loadAvatar(context, contact) image?.let { contact to it } } } }.awaitAll().filterNotNull().toMap() return images } internal fun Contact.imageResourceId() = "contact:$id" private suspend fun ImageLoader.loadAvatar( context: Context, contact: Contact, size: Int? = 64 ): Bitmap? { val request = ImageRequest.Builder(context) .data(contact.avatarUrl) .apply { if (size != null) { size(size) } } .allowRgb565(true) .transformations(CircleCropTransformation()) .allowHardware(false) .build() val response = execute(request) return (response.drawable as? BitmapDrawable)?.bitmap }
apache-2.0
8058bc55c2fb143094ce87ae0a765b8d
32.234568
100
0.70208
4.578231
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/handlers/injectionPoint/LoadInjectionPoint.kt
1
13366
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint import com.demonwav.mcdev.platform.mixin.handlers.ModifyVariableInfo import com.demonwav.mcdev.platform.mixin.reference.MixinSelector import com.demonwav.mcdev.platform.mixin.util.AsmDfaUtil import com.demonwav.mcdev.platform.mixin.util.LocalVariables import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MODIFY_VARIABLE import com.demonwav.mcdev.util.constantValue import com.demonwav.mcdev.util.findModule import com.demonwav.mcdev.util.isErasureEquivalentTo import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.module.Module import com.intellij.psi.JavaPsiFacade import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAssignmentExpression import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpressionStatement import com.intellij.psi.PsiForeachStatement import com.intellij.psi.PsiParameter import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.PsiThisExpression import com.intellij.psi.PsiType import com.intellij.psi.PsiUnaryExpression import com.intellij.psi.PsiVariable import com.intellij.psi.util.PsiUtil import com.intellij.psi.util.parentOfType import org.objectweb.asm.Opcodes import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodNode import org.objectweb.asm.tree.VarInsnNode abstract class AbstractLoadInjectionPoint(private val store: Boolean) : InjectionPoint<PsiElement>() { private fun getModifyVariableInfo(at: PsiAnnotation, mode: CollectVisitor.Mode?): ModifyVariableInfo? { val modifyVariable = at.parentOfType<PsiAnnotation>() ?: return null if (!modifyVariable.hasQualifiedName(MODIFY_VARIABLE)) { return null } return ModifyVariableInfo.getModifyVariableInfo(modifyVariable, mode) } override fun createNavigationVisitor( at: PsiAnnotation, target: MixinSelector?, targetClass: PsiClass ): NavigationVisitor? { val info = getModifyVariableInfo(at, null) ?: return null return MyNavigationVisitor(info, store) } override fun doCreateCollectVisitor( at: PsiAnnotation, target: MixinSelector?, targetClass: ClassNode, mode: CollectVisitor.Mode ): CollectVisitor<PsiElement>? { val module = at.findModule() ?: return null val info = getModifyVariableInfo(at, mode) ?: return null return MyCollectVisitor(module, targetClass, mode, info, store) } override fun createLookup( targetClass: ClassNode, result: CollectVisitor.Result<PsiElement> ): LookupElementBuilder? { return null } override fun addOrdinalFilter(at: PsiAnnotation, targetClass: ClassNode, collectVisitor: CollectVisitor<*>) { val ordinal = at.findDeclaredAttributeValue("ordinal")?.constantValue as? Int ?: return if (ordinal < 0) return // Replace the ordinal filter with one that takes into account the type of the local variable being modified. // Fixes otherwise incorrect results for completion. val project = at.project val ordinals = mutableMapOf<String, Int>() collectVisitor.addResultFilter("ordinal") { result, method -> result.originalInsn as? VarInsnNode ?: throw IllegalStateException("AbstractLoadInjectionPoint returned non-var insn") val localInsn = if (store) { result.originalInsn.next } else { result.originalInsn } val localType = AsmDfaUtil.getLocalVariableType( project, targetClass, method, localInsn, result.originalInsn.`var` ) ?: return@addResultFilter true val desc = localType.descriptor val ord = ordinals[desc] ?: 0 ordinals[desc] = ord + 1 ord == ordinal } } private class MyNavigationVisitor( private val info: ModifyVariableInfo, private val store: Boolean ) : NavigationVisitor() { override fun visitThisExpression(expression: PsiThisExpression) { super.visitThisExpression(expression) if (!store && expression.qualifier == null) { addLocalUsage(expression, "this") } } override fun visitVariable(variable: PsiVariable) { super.visitVariable(variable) if (store && variable.initializer != null) { val name = variable.name if (name != null) { addLocalUsage(variable, name) } } } override fun visitReferenceExpression(expression: PsiReferenceExpression) { super.visitReferenceExpression(expression) val referenceName = expression.referenceName ?: return if (expression.qualifierExpression == null) { val isCorrectAccessType = if (store) { PsiUtil.isAccessedForWriting(expression) } else { PsiUtil.isAccessedForReading(expression) } if (!isCorrectAccessType) { return } val resolved = expression.resolve() as? PsiVariable ?: return val type = resolved.type if (type is PsiPrimitiveType && type != PsiType.FLOAT && type != PsiType.DOUBLE && type != PsiType.LONG && type != PsiType.BOOLEAN ) { // ModifyVariable currently cannot handle iinc val parentExpr = PsiUtil.skipParenthesizedExprUp(expression.parent) val isIincUnary = parentExpr is PsiUnaryExpression && ( parentExpr.operationSign.tokenType == JavaTokenType.PLUSPLUS || parentExpr.operationSign.tokenType == JavaTokenType.MINUSMINUS ) val isIincAssignment = parentExpr is PsiAssignmentExpression && ( parentExpr.operationSign.tokenType == JavaTokenType.PLUSEQ || parentExpr.operationSign.tokenType == JavaTokenType.MINUSEQ ) && PsiUtil.isConstantExpression(parentExpr.rExpression) && (parentExpr.rExpression?.constantValue as? Number)?.toInt() ?.let { it >= Short.MIN_VALUE && it <= Short.MAX_VALUE } == true val isIinc = isIincUnary || isIincAssignment if (isIinc) { if (store) { return } val parentParent = PsiUtil.skipParenthesizedExprUp(parentExpr.parent) if (parentParent is PsiExpressionStatement) { return } } } if (!info.argsOnly || resolved is PsiParameter) { addLocalUsage(expression, referenceName) } } } override fun visitForeachStatement(statement: PsiForeachStatement) { checkImplicitLocalsPre(statement) if (store) { addLocalUsage(statement.iterationParameter, statement.iterationParameter.name) } super.visitForeachStatement(statement) checkImplicitLocalsPost(statement) } private fun checkImplicitLocalsPre(location: PsiElement) { val localsHere = LocalVariables.guessLocalsAt(location, info.argsOnly, true) val localIndex = LocalVariables.guessLocalVariableIndex(location) ?: return val localCount = LocalVariables.getLocalVariableSize(location) for (i in localIndex until (localIndex + localCount)) { val local = localsHere.firstOrNull { it.index == i } ?: continue if (store) { repeat(local.implicitStoreCountBefore) { addLocalUsage(location, local.name, localsHere) } } else { repeat(local.implicitLoadCountBefore) { addLocalUsage(location, local.name, localsHere) } } } } private fun checkImplicitLocalsPost(location: PsiElement) { val localsHere = LocalVariables.guessLocalsAt(location, info.argsOnly, false) val localIndex = LocalVariables.guessLocalVariableIndex(location) ?: return val localCount = LocalVariables.getLocalVariableSize(location) for (i in localIndex until (localIndex + localCount)) { val local = localsHere.firstOrNull { it.index == i } ?: continue if (store) { repeat(local.implicitStoreCountAfter) { addLocalUsage(location, local.name, localsHere) } } else { repeat(local.implicitLoadCountAfter) { addLocalUsage(location, local.name, localsHere) } } } } private fun addLocalUsage(location: PsiElement, name: String) { val localsHere = LocalVariables.guessLocalsAt(location, info.argsOnly, !store) addLocalUsage(location, name, localsHere) } private fun addLocalUsage( location: PsiElement, name: String, localsHere: List<LocalVariables.SourceLocalVariable> ) { if (info.ordinal != null) { val local = localsHere.asSequence().filter { it.type.isErasureEquivalentTo(info.type) }.drop(info.ordinal).firstOrNull() if (name == local?.name) { addResult(location) } return } if (info.index != null) { val local = localsHere.getOrNull(info.index) if (name == local?.name) { addResult(location) } return } if (info.names.isNotEmpty()) { val matchingLocals = localsHere.filter { info.names.contains(it.mixinName) } for (local in matchingLocals) { if (local.name == name) { addResult(location) } } return } // implicit mode val local = localsHere.singleOrNull { it.type.isErasureEquivalentTo(info.type) } if (local != null && local.name == name) { addResult(location) } } } private class MyCollectVisitor( private val module: Module, private val targetClass: ClassNode, mode: Mode, private val info: ModifyVariableInfo, private val store: Boolean ) : CollectVisitor<PsiElement>(mode) { override fun accept(methodNode: MethodNode) { var opcode = when (info.type) { null -> null !is PsiPrimitiveType -> Opcodes.ALOAD PsiType.LONG -> Opcodes.LLOAD PsiType.FLOAT -> Opcodes.FLOAD PsiType.DOUBLE -> Opcodes.DLOAD else -> Opcodes.ILOAD } if (store && opcode != null) { opcode += (Opcodes.ISTORE - Opcodes.ILOAD) } for (insn in methodNode.instructions) { if (insn !is VarInsnNode) { continue } if (opcode != null) { if (opcode != insn.opcode) { continue } } else { if (store) { if (insn.opcode < Opcodes.ISTORE || insn.opcode > Opcodes.ASTORE) { continue } } else { if (insn.opcode < Opcodes.ILOAD || insn.opcode > Opcodes.ALOAD) { continue } } } val localLocation = if (store) insn.next ?: insn else insn val locals = info.getLocals(module, targetClass, methodNode, localLocation) ?: continue val elementFactory = JavaPsiFacade.getElementFactory(module.project) for (result in info.matchLocals(locals, mode)) { addResult(insn, elementFactory.createExpressionFromText(result.name, null)) } } } } } class LoadInjectionPoint : AbstractLoadInjectionPoint(false) class StoreInjectionPoint : AbstractLoadInjectionPoint(true)
mit
0bf9651fea20efca7168aafae7c7b98b
39.75
117
0.570702
5.387344
false
false
false
false
kilel/jotter
snt-dao-starter/src/main/kotlin/org/github/snt/dao/api/entity/Note.kt
1
1587
/* * Copyright 2018 Kislitsyn Ilya * * 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.github.snt.dao.api.entity import java.util.* import javax.persistence.* /** * Represents user note, which contains some data. * @constructor By default crete with no arguments. */ @Entity @Table(name = "SN_NOTES") class Note constructor() : AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column override var id: Long? = null @Column(name = "id_hi") var parentId: Long? = null @Column(name = "code") var code = "unknown" @Column(name = "dscr") var description = "" @Column(name = "data") var data: ByteArray = ByteArray(0) @Column(name = "schema_id") var schemaId: Long = DataSchemaType.DEFAULT.id @Temporal(TemporalType.TIMESTAMP) @Column(name = "update_dt") var updateDate: Date = Date() /** * Constructor to create note with name but without data * @param code Note name */ constructor(code: String) : this() { this.code = code } }
apache-2.0
6f20dd30eba60d751e3d0c036f00de40
25.032787
75
0.673598
3.889706
false
false
false
false
ZieIony/Carbon
component/src/main/java/carbon/component/IconSearchItem.kt
1
1282
package carbon.component import android.content.Context import android.graphics.drawable.Drawable import android.view.ViewGroup import carbon.component.databinding.CarbonRowIconsearchBinding import carbon.widget.* import java.io.Serializable interface IconSearchItem : Serializable { val icon: Drawable val query: String? val hint: String? } class DefaultIconSearchItem : IconSearchItem { override var icon: Drawable override var query: String? = null override var hint: String? = null constructor(context: Context) { icon = context.resources.getDrawable(R.drawable.carbon_search) } constructor(context: Context, query: String, hint: String) : this(context) { this.query = query this.hint = hint } } class IconSearchRow<Type : IconSearchItem>( parent: ViewGroup, val adapter: SearchAdapter<*>, val listener: SearchEditText.OnFilterListener<*> ) : LayoutComponent<Type>(parent, R.layout.carbon_row_iconsearch) { private val binding = CarbonRowIconsearchBinding.bind(view) override fun bind(data: Type) { binding.carbonIcon.setImageDrawable(data.icon) binding.carbonQuery.setDataProvider(adapter) binding.carbonQuery.setOnFilterListener(listener) } }
apache-2.0
9fe94fa24771b485c8a355844f1b1e85
27.488889
80
0.724649
4.302013
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/utils/Context.kt
1
687
package com.reactnativenavigation.utils import android.content.Context import android.content.res.Configuration import android.content.res.Configuration.UI_MODE_NIGHT_YES import com.facebook.react.ReactApplication import com.reactnativenavigation.NavigationApplication fun Context.isDebug(): Boolean { return (applicationContext as ReactApplication).reactNativeHost.useDeveloperSupport } fun isDarkMode() = NavigationApplication.instance.isDarkMode() fun Context.isDarkMode(): Boolean = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES fun Configuration.isDarkMode() = (uiMode and Configuration.UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES
mit
5bd2a24233bb8ed5b036a14a950bcfd9
44.866667
99
0.825328
4.267081
false
true
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2295.kt
1
542
package leetcode /** * https://leetcode.com/problems/replace-elements-in-an-array/ */ class Problem2295 { fun arrayChange(nums: IntArray, operations: Array<IntArray>): IntArray { val map = mutableMapOf<Int, Int>() for ((index, num) in nums.withIndex()) { map[num] = index } for ((from, to) in operations) { val index = map[from] if (index != null) { nums[index] = to map[to] = index } } return nums } }
mit
9507c71f0b7b1ed16f074247a71dea33
24.809524
76
0.50738
3.985294
false
false
false
false
grueni75/GeoDiscoverer
Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/activity/ViewMap.kt
1
18778
//============================================================================ // Name : ViewMap2.kt // Author : Matthias Gruenewald // Copyright : Copyright 2010-2021 Matthias Gruenewald // // This file is part of GeoDiscoverer. // // GeoDiscoverer 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. // // GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>. // //============================================================================ package com.untouchableapps.android.geodiscoverer.ui.activity import android.annotation.SuppressLint import android.app.ActivityManager import android.content.* import android.content.pm.PackageManager import android.content.res.Configuration import android.hardware.Sensor import android.hardware.SensorManager import android.net.Uri import android.os.* import android.view.WindowManager import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.* import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.icons.Icons import androidx.compose.material3.* import androidx.compose.ui.tooling.preview.Preview import com.untouchableapps.android.geodiscoverer.R import com.untouchableapps.android.geodiscoverer.ui.theme.AndroidTheme import androidx.compose.material.icons.outlined.* import androidx.compose.runtime.* import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.graphics.ExperimentalGraphicsApi import androidx.core.content.FileProvider import com.untouchableapps.android.geodiscoverer.GDApplication import com.untouchableapps.android.geodiscoverer.core.GDCore import com.untouchableapps.android.geodiscoverer.logic.GDBackgroundTask import com.untouchableapps.android.geodiscoverer.logic.GDBackgroundTask.AddressPointItem import com.untouchableapps.android.geodiscoverer.logic.GDService import com.untouchableapps.android.geodiscoverer.ui.activity.viewmap.* import com.untouchableapps.android.geodiscoverer.ui.component.GDDialog import kotlinx.coroutines.* import org.mapsforge.core.model.LatLong import java.io.File import java.lang.Exception import java.net.URI @ExperimentalGraphicsApi @ExperimentalMaterialApi @ExperimentalMaterial3Api @ExperimentalAnimationApi @ExperimentalComposeUiApi class ViewMap : ComponentActivity(), CoroutineScope by MainScope() { // Callback when a called activity finishes val startPreferencesForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> // Did the activity change prefs? if (result.resultCode == 1) { restartCore(false) } } // View model for jetpack compose communication val viewModel = ViewModel(this) // Reference to the core object and it's view var coreObject: GDCore? = null // The dialog handler val dialogHandler = GDDialog( showSnackbar = { message -> viewModel.showSnackbar(message) }, showDialog = viewModel::setDialog ) // The intent handler val intentHandler = IntentHandler(this) // Activity content val viewContent = ViewContent(this) // Prefs var prefs: SharedPreferences? = null // Flags var compassWatchStarted = false var exitRequested = false var restartRequested = false var doubleBackToExitPressedOnce = false // Managers var sensorManager: SensorManager? = null // Sets the screen time out @SuppressLint("Wakelock") fun updateWakeLock() { if (coreObject != null) { val state = coreObject!!.executeCoreCommand("getWakeLock") if (state == "true") { GDApplication.addMessage(GDApplication.DEBUG_MSG, "GDApp", "wake lock enabled") window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { GDApplication.addMessage(GDApplication.DEBUG_MSG, "GDApp", "wake lock disabled") window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } } // Start listening for compass bearing @Synchronized fun startWatchingCompass() { if (coreObject != null && !compassWatchStarted) { sensorManager?.registerListener( coreObject, sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL ) sensorManager?.registerListener( coreObject, sensorManager?.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL ) compassWatchStarted = true } } // Stop listening for compass bearing @Synchronized fun stopWatchingCompass() { if (compassWatchStarted) { sensorManager?.unregisterListener(coreObject) compassWatchStarted = false } } // Sets the exit busy text fun setExitBusyText() { viewModel.busyText = getString(R.string.stopping_core_object) } // Shows the splash screen fun setSplashVisibility(isVisible: Boolean) { if (isVisible) { viewModel.splashVisible = true viewModel.messagesVisible = true if (coreObject != null) coreObject?.setSplashIsVisible(true) } else { viewModel.splashVisible = false viewModel.messagesVisible = false viewModel.busyText = getString(R.string.starting_core_object) } } // Exits the app fun exitApp() { setExitBusyText() val m = Message.obtain(coreObject!!.messageHandler) m.what = GDCore.STOP_CORE coreObject!!.messageHandler.sendMessage(m) } // Restarts the core fun restartCore(resetConfig: Boolean = false) { restartRequested = true viewModel.busyText = getString(R.string.restarting_core_object) val m = Message.obtain(coreObject!!.messageHandler) m.what = GDCore.RESTART_CORE val b = Bundle() b.putBoolean("resetConfig", resetConfig) m.data = b coreObject!!.messageHandler.sendMessage(m) } // Called when a configuration change (e.g., caused by a screen rotation) has occured override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) viewModel.closeQuestion() } // Ensure that double back press quits the app override fun onBackPressed() { if (doubleBackToExitPressedOnce) { //super.onBackPressed(); exitApp() return } doubleBackToExitPressedOnce = true viewModel.showSnackbar(getString(R.string.back_button)) launch() { delay(2000) doubleBackToExitPressedOnce = false } } // Adds a map download job fun addMapDownloadJob( estimate: Boolean, routeName: String, selectedMapLayers: List<String>, ) { val args = arrayOfNulls<String>(selectedMapLayers.size + 2) args[0] = if (estimate) "1" else "0" args[1] = routeName for (i in selectedMapLayers.indices) { args[i + 2] = selectedMapLayers[i] } coreObject?.executeCoreCommand("addDownloadJob", *args) } // Shows the legend with the given name fun showMapLegend(name: String) { val legendPath = coreObject!!.executeCoreCommand("getMapLegendPath", name) val legendFile = File(legendPath) if (!legendFile.exists()) { dialogHandler.errorDialog( getString( R.string.map_has_no_legend, coreObject?.executeCoreCommand("getMapFolder") ) ) } else { val legendUri = FileProvider.getUriForFile( applicationContext, "com.untouchableapps.android.geodiscoverer.fileprovider", legendFile ) val intent = Intent() intent.action = Intent.ACTION_VIEW intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) if (legendPath.endsWith(".png")) intent.setDataAndType(legendUri, "image/*") if (legendPath.endsWith(".pdf")) intent.setDataAndType(legendUri, "application/pdf") GDApplication.addMessage( GDApplication.DEBUG_MSG, "GDApp", "Viewing $legendPath" ) startActivity(intent) } } // Communication with the native core var coreMessageHandler = CoreMessageHandler(this) // Creates the activity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GDApplication.addMessage(GDApplication.DEBUG_MSG,"GDApp","ViewMap activity started") // Check for OpenGL ES 2.00 val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager val configurationInfo = activityManager.deviceConfigurationInfo val supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000 || Build.FINGERPRINT.startsWith("generic") if (!supportsEs2) { Toast.makeText(this, getString(R.string.opengles20_required), Toast.LENGTH_LONG) finish(); return } // Get important handles sensorManager = this.getSystemService(SENSOR_SERVICE) as SensorManager if (sensorManager == null) { Toast.makeText(this, getString(R.string.missing_system_service), Toast.LENGTH_LONG) finish(); return } // Get the core object coreObject = GDApplication.coreObject if (coreObject == null) { finish() return } (application as GDApplication).setActivity(this, coreMessageHandler) // Init the child objects intentHandler.onCreate() if (coreObject!!.coreEarlyInitComplete) { viewModel.onCoreEarlyInitComplete() } // Create the content for the navigation drawer val navigationItems = arrayOf( ViewContentNavigationDrawer.NavigationItem(null, getString(R.string.map), { }), ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Article, getString(R.string.show_legend)) { if (coreObject!=null) { val namesString = coreObject!!.executeCoreCommand("getMapLegendNames") val names = namesString.split(",".toRegex()).toList() if (names.size != 1) { viewModel.askForMapLegend(names) { name -> showMapLegend(name) } } else { showMapLegend(names[0]) } } }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Download, getString(R.string.download_map)) { viewModel.askForMapDownloadType( dismissHandler = { coreObject?.executeAppCommand("askForMapDownloadDetails(\"\")") }, confirmHandler = { coreObject?.executeCoreCommand("downloadActiveRoute") } ) }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.CleaningServices, getString(R.string.cleanup_map)) { if (coreObject!=null) { viewModel.askForMapCleanup( confirmHandler = { coreObject?.executeCoreCommand( "forceMapRedownload", "1" ) }, dismissHandler = { coreObject?.executeCoreCommand( "forceMapRedownload", "0" ) } ) } }, ViewContentNavigationDrawer.NavigationItem(null, getString(R.string.routes), { }), ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.AddCircle, getString(R.string.add_tracks_as_routes)) { viewModel.askForTracksAsRoutes() { selectedTracks -> if (selectedTracks.isNotEmpty()) { GDApplication.backgroundTask.copyTracksToRoutes(this,selectedTracks,this) } } }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.RemoveCircle, getString(R.string.remove_routes)) { viewModel.askForRemoveRoutes() { selectedRoutes -> if (selectedRoutes.isNotEmpty()) { GDApplication.backgroundTask.removeRoutes(this,selectedRoutes,this) } } }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.SendToMobile, getString(R.string.export_selected_route)) { if (coreObject!=null) { coreObject?.executeCoreCommand("exportActiveRoute") } }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Directions, getString(R.string.brouter)) { // Hand over all currently available address points val t=coreObject!!.executeCoreCommand("getMapPos") GDApplication.addMessage(GDApplication.DEBUG_MSG, "GDApp", "t=$t") val currentPos=t.split(",") val zoomLevel=coreObject!!.executeCoreCommand("getMapServerZoomLevel") var path = "http://localhost:8383/brouter-web/index.html#map=${zoomLevel}/${currentPos[0]}/${currentPos[1]}/GeoDiscoverer" var pois = "" val addressPoints = GDApplication.backgroundTask.fillAddressPoints() for (ap in addressPoints) { if (pois != "") pois += ";" pois += "${ap.longitude},${ap.latitude},${Uri.encode(ap.nameUniquified)}" } if (pois != "") { path += "&pois=$pois" } GDApplication.addMessage(GDApplication.DEBUG_MSG, "GDApp", "path=$path") // Load the brouter val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(path) startActivity(i) }, ViewContentNavigationDrawer.NavigationItem(null, getString(R.string.general), { }), ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Help, getString(R.string.help)) { intent = Intent(applicationContext, ShowHelp::class.java) startActivity(intent) }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Settings, getString(R.string.preferences)) { val myIntent = Intent(applicationContext, Preferences::class.java) startPreferencesForResult.launch(myIntent) }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Replay, getString(R.string.restart)) { restartCore(false) }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Logout, getString(R.string.exit)) { exitApp() }, ViewContentNavigationDrawer.NavigationItem(null, getString(R.string.debug), { }), ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Message, getString(R.string.toggle_messages)) { viewModel.toggleMessagesVisibility() }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.UploadFile, getString(R.string.send_logs)) { viewModel.askForSendLogs() { selectedLogs -> if (selectedLogs.isNotEmpty()) { GDApplication.backgroundTask.sendLogs(selectedLogs,this) } } }, ViewContentNavigationDrawer.NavigationItem(Icons.Outlined.Clear, getString(R.string.reset)) { viewModel.askForConfigReset() { restartCore(true) } }, ) // Get the app version val packageManager = packageManager val appVersion: String appVersion = try { "Version " + packageManager.getPackageInfo(packageName, 0).versionName } catch (e: PackageManager.NameNotFoundException) { "Version ?" } // Create the activity content setContent { AndroidTheme { viewContent.content(viewModel, appVersion, navigationItems.toList()) } } // Restore the last processed intent from the prefs prefs = application.getSharedPreferences("viewMap", MODE_PRIVATE) if (prefs!!.contains("processIntent")) { val processIntent: Boolean = prefs!!.getBoolean("processIntent", true) if (!processIntent) { getIntent().addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) } val prefsEditor: SharedPreferences.Editor = prefs!!.edit() prefsEditor.putBoolean("processIntent", true) prefsEditor.commit() } } // Destroys the activity @SuppressLint("Wakelock") override fun onDestroy() { super.onDestroy() GDApplication.addMessage( GDApplication.DEBUG_MSG, "GDApp", "onDestroy called by " + Thread.currentThread().name ) cancel() // Stop all coroutines (application as GDApplication).setActivity(null, null) intentHandler.onDestroy() //if (downloadCompleteReceiver != null) unregisterReceiver(downloadCompleteReceiver) if (exitRequested) System.exit(0) if (restartRequested) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { val intent = Intent(applicationContext, ViewMap::class.java) startActivity(intent) } } } // Called when a new intent is available override fun onNewIntent(intent: Intent) { setIntent(intent) GDApplication.addMessage( GDApplication.DEBUG_MSG, "GDApp", "onNewIntent: $intent" ) } override fun onPause() { super.onPause() GDApplication.addMessage( GDApplication.DEBUG_MSG, "GDApp", "onPause called by " + Thread.currentThread().name ) viewModel.fixSurfaceViewBug = true stopWatchingCompass() if (!exitRequested && !restartRequested) { val intent = Intent(this, GDService::class.java) intent.action = "activityPaused" startService(intent) } } override fun onResume() { super.onResume() GDApplication.addMessage( GDApplication.DEBUG_MSG, "GDApp", "onResume called by " + Thread.currentThread().name ) // Bug fix: Somehow the emulator calls onResume before onCreate // But the code relies on the fact that onCreate is called before // Do nothing if onCreate has not yet initialized the objects if (coreObject == null) return // If we shall restart or exit, don't init anything here if (exitRequested || restartRequested) return // Resume all components only if a exit or restart is not requested startWatchingCompass() val intent = Intent(this, GDService::class.java) intent.action = "activityResumed" startService(intent) // Synchronize google bookmarks GDApplication.coreObject.executeCoreCommand("updateGoogleBookmarks"); // Check for outdated routes if (coreObject!!.coreInitialized) { GDApplication.backgroundTask.checkForOutdatedRoutes(this) } // Process intent only if geo discoverer is initialized if (coreObject!!.coreLateInitComplete) intentHandler.processIntent() } @ExperimentalMaterial3Api @Preview(showBackground = true) @Composable fun preview() { AndroidTheme { } } }
gpl-3.0
55e815898d7624b6f1ce0c66019b37ee
33.83859
130
0.688998
4.417314
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/user/GroupedLinksAdapter.kt
1
4452
package de.westnordost.streetcomplete.user import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isGone import androidx.recyclerview.widget.RecyclerView import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.user.achievements.Link import de.westnordost.streetcomplete.data.user.achievements.LinkCategory import kotlinx.android.synthetic.main.card_link_item.view.* import kotlinx.android.synthetic.main.row_link_category_item.view.* /** Adapter for a list of links, grouped by category */ class GroupedLinksAdapter(links: List<Link>, private val onClickLink: (url: String) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val groupedLinks: List<Item> = links .groupBy { it.category } .flatMap { entry -> val category = entry.key val linksInCategory = entry.value listOf(CategoryItem(category)) + linksInCategory.map { LinkItem(it) } } private val itemCount = groupedLinks.size override fun getItemCount(): Int = itemCount override fun getItemViewType(position: Int): Int = when (groupedLinks[position]) { is CategoryItem -> CATEGORY is LinkItem -> LINK } fun shouldItemSpanFullWidth(position: Int): Boolean = groupedLinks[position] is CategoryItem override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return when(viewType) { CATEGORY -> CategoryViewHolder(inflater.inflate(R.layout.row_link_category_item, parent, false)) LINK -> LinkViewHolder(inflater.inflate(R.layout.card_link_item, parent, false)) else -> throw IllegalStateException("Unexpected viewType $viewType") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (val item = groupedLinks[position]) { is CategoryItem -> (holder as CategoryViewHolder).onBind(item.category) is LinkItem -> (holder as LinkViewHolder).onBind(item.link) } } inner class LinkViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun onBind(with: Link) { if (with.icon != null) { itemView.linkIconImageView.setImageResource(with.icon) } else { itemView.linkIconImageView.setImageDrawable(null) } itemView.linkTitleTextView.text = with.title if (with.description != null) { itemView.linkDescriptionTextView.setText(with.description) } else { itemView.linkDescriptionTextView.text = "" } itemView.setOnClickListener { onClickLink(with.url) } } } inner class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun onBind(with: LinkCategory) { itemView.linkCategoryTitleTextView.setText(with.title) val description = with.description itemView.linkCategoryDescriptionTextView.isGone = description == null if (description != null) { itemView.linkCategoryDescriptionTextView.setText(description) } else { itemView.linkCategoryDescriptionTextView.text = "" } } } companion object { private const val LINK = 0 private const val CATEGORY = 1 } } private sealed class Item private data class CategoryItem(val category: LinkCategory) : Item() private data class LinkItem(val link: Link) : Item() private val LinkCategory.title: Int get() = when(this) { LinkCategory.INTRO -> R.string.link_category_intro_title LinkCategory.EDITORS -> R.string.link_category_editors_title LinkCategory.MAPS -> R.string.link_category_maps_title LinkCategory.SHOWCASE -> R.string.link_category_showcase_title LinkCategory.GOODIES -> R.string.link_category_goodies_title } private val LinkCategory.description: Int? get() = when(this) { LinkCategory.INTRO -> R.string.link_category_intro_description LinkCategory.EDITORS -> R.string.link_category_editors_description LinkCategory.SHOWCASE -> R.string.link_category_showcase_description LinkCategory.MAPS -> R.string.link_category_maps_description LinkCategory.GOODIES -> R.string.link_category_goodies_description }
gpl-3.0
04b925f14b6ebba3f683f03da8d0eae8
40.222222
108
0.689353
4.492432
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/jsMain/kotlin/org/koin/core/context/GlobalContext.kt
1
2370
/* * Copyright 2017-2021 the original author or authors. * * 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.koin.core.context import org.koin.core.Koin import org.koin.core.KoinApplication import org.koin.core.error.KoinAppAlreadyStartedException import org.koin.core.module.Module import org.koin.dsl.KoinAppDeclaration /** * Global context - current Koin Application available globally * * Support to help inject automatically instances once KoinApp has been started * * @author Arnaud Giuliani */ object GlobalContext : KoinContext { private var _koin: Koin? = null override fun get(): Koin = _koin ?: error("KoinApplication has not been started") override fun getOrNull(): Koin? = _koin private fun register(koinApplication: KoinApplication) { if (_koin != null) { throw KoinAppAlreadyStartedException("A Koin Application has already been started") } _koin = koinApplication.koin } override fun stopKoin() { _koin?.close() _koin = null } override fun startKoin(koinApplication: KoinApplication): KoinApplication { register(koinApplication) return koinApplication } override fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication { val koinApplication = KoinApplication.init() register(koinApplication) appDeclaration(koinApplication) return koinApplication } override fun loadKoinModules(module: Module) { get().loadModules(listOf(module)) } override fun loadKoinModules(modules: List<Module>) { get().loadModules(modules) } override fun unloadKoinModules(module: Module) { get().unloadModules(listOf(module)) } override fun unloadKoinModules(modules: List<Module>) { get().unloadModules(modules) } }
apache-2.0
ca5dc54eb405179b00ccd048a4225e3e
29
95
0.703797
4.647059
false
false
false
false
InsertKoinIO/koin
examples/androidx-samples/src/main/java/org/koin/sample/androidx/navigation/NavFragmentB.kt
1
1173
package org.koin.sample.androidx.navigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.navigation.fragment.findNavController import org.koin.androidx.navigation.koinNavGraphViewModel import org.koin.sample.android.R class NavFragmentB : Fragment() { val mainViewModel: NavViewModel by koinNavGraphViewModel(R.id.main) lateinit var button: Button override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.nav_fragment_b, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) button = requireView().findViewById(R.id.a_button) button.setOnClickListener { findNavController().popBackStack() } ID = mainViewModel.id assert(ID == NavFragmentA.ID) println("vm id: $ID") } companion object { var ID = "" } }
apache-2.0
6d07d24f9142025a32c093320eb052fd
25.681818
74
0.710997
4.511538
false
false
false
false
kesmarag/megaptera
src/main/org/kesmarag/megaptera/linear/ColumnVector.kt
1
2378
package org.kesmarag.megaptera.linear import org.kesmarag.megaptera.utils.* import org.kesmarag.megaptera.utils.toColumnVector import org.kesmarag.megaptera.utils.toRowVector class ColumnVector(_dimension: Int) : Vector(_dimension) { override fun t(): RowVector { val tmpVector = RowVector(dimension) for (i in 0..dimension - 1) { tmpVector[i] = this[i] } return tmpVector } override val type = VectorType.COLUMN_VECTOR override fun toString(): String { var str: String = ".:: ColumnVector[${this.dimension}] ::.\n[" for (i in 0..this.dimension-2){ str = str + this[i].toString() + " \n" } str+= "${this[this.dimension-1]}]\n" return str } override fun clone(): ColumnVector { val cloned = this.elements.toColumnVector() return cloned } operator fun plus(other: ColumnVector): ColumnVector { if (this.dimension != other.dimension) { throw IllegalArgumentException("vectors with different dimensions") } val tmpVector = this.clone() for (i in 0..this.dimension - 1) { tmpVector[i] += other[i] } return tmpVector } operator fun plus(other: RowVector): ColumnVector { if (this.dimension != other.dimension) { throw IllegalArgumentException("vectors with different dimensions") } val tmpVector = this.clone() for (i in 0..this.dimension - 1) { tmpVector[i] += other[i] } return tmpVector } operator fun minus(other: ColumnVector): ColumnVector { if (this.dimension != other.dimension) { throw IllegalArgumentException("vectors with different dimensions") } return this + other * (-1.0) } operator fun times(num: Double): ColumnVector { val tmpVector = this.clone() for (i in 0..this.dimension - 1) { tmpVector[i] *= num } return tmpVector } operator fun times(num: Int): ColumnVector { val tmpVector = this.clone() for (i in 0..this.dimension - 1) { tmpVector[i] *= num.toDouble() } return tmpVector } public fun fill(a: Double): Unit{ for (i in 0..dimension-1){ elements[i] = a } } }
apache-2.0
a545d52378c00ea11f4f1d53d046779d
27.309524
79
0.574853
4.051107
false
false
false
false
CarlosEsco/tachiyomi
core/src/main/java/eu/kanade/tachiyomi/network/Requests.kt
1
1880
package eu.kanade.tachiyomi.network import okhttp3.CacheControl import okhttp3.FormBody import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.Request import okhttp3.RequestBody import java.util.concurrent.TimeUnit.MINUTES private val DEFAULT_CACHE_CONTROL = CacheControl.Builder().maxAge(10, MINUTES).build() private val DEFAULT_HEADERS = Headers.Builder().build() private val DEFAULT_BODY: RequestBody = FormBody.Builder().build() fun GET( url: String, headers: Headers = DEFAULT_HEADERS, cache: CacheControl = DEFAULT_CACHE_CONTROL, ): Request { return GET(url.toHttpUrl(), headers, cache) } /** * @since extensions-lib 1.4 */ fun GET( url: HttpUrl, headers: Headers = DEFAULT_HEADERS, cache: CacheControl = DEFAULT_CACHE_CONTROL, ): Request { return Request.Builder() .url(url) .headers(headers) .cacheControl(cache) .build() } fun POST( url: String, headers: Headers = DEFAULT_HEADERS, body: RequestBody = DEFAULT_BODY, cache: CacheControl = DEFAULT_CACHE_CONTROL, ): Request { return Request.Builder() .url(url) .post(body) .headers(headers) .cacheControl(cache) .build() } fun PUT( url: String, headers: Headers = DEFAULT_HEADERS, body: RequestBody = DEFAULT_BODY, cache: CacheControl = DEFAULT_CACHE_CONTROL, ): Request { return Request.Builder() .url(url) .put(body) .headers(headers) .cacheControl(cache) .build() } fun DELETE( url: String, headers: Headers = DEFAULT_HEADERS, body: RequestBody = DEFAULT_BODY, cache: CacheControl = DEFAULT_CACHE_CONTROL, ): Request { return Request.Builder() .url(url) .delete(body) .headers(headers) .cacheControl(cache) .build() }
apache-2.0
11910d2466f52c3f64ad2414389b7581
22.797468
86
0.659574
3.916667
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt
1
60477
package info.nightscout.androidaps.plugins.general.overview import android.annotation.SuppressLint import android.app.NotificationManager import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.graphics.Paint import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.AnimationDrawable import android.os.Build import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.util.DisplayMetrics import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.View.OnLongClickListener import android.view.ViewGroup import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import androidx.core.text.toSpanned import androidx.recyclerview.widget.LinearLayoutManager import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector import dagger.android.support.DaggerFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.interfaces.end import info.nightscout.androidaps.databinding.OverviewFragmentBinding import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.events.* import info.nightscout.androidaps.extensions.directionToIcon import info.nightscout.androidaps.extensions.runOnUiThread import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.extensions.valueToUnitsString import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.constraints.bgQualityCheck.BgQualityCheckPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewCalcProgress import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewGraph import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewIobCob import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewSensitivity import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.source.DexcomPlugin import info.nightscout.androidaps.plugins.source.XdripPlugin import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.TrendCalculator import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.SingleClickButton import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.androidaps.utils.wizard.QuickWizard import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.weardata.EventData import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject import kotlin.math.abs import kotlin.math.min class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickListener { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var nsDeviceStatus: NSDeviceStatus @Inject lateinit var loop: Loop @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var dexcomMediator: DexcomPlugin.DexcomMediator @Inject lateinit var xdripPlugin: XdripPlugin @Inject lateinit var notificationStore: NotificationStore @Inject lateinit var quickWizard: QuickWizard @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var overviewMenus: OverviewMenus @Inject lateinit var skinProvider: SkinProvider @Inject lateinit var trendCalculator: TrendCalculator @Inject lateinit var config: Config @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider @Inject lateinit var overviewData: OverviewData @Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var bgQualityCheckPlugin: BgQualityCheckPlugin private val disposable = CompositeDisposable() private var smallWidth = false private var smallHeight = false private lateinit var dm: DisplayMetrics private var axisWidth: Int = 0 private lateinit var refreshLoop: Runnable private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private val secondaryGraphs = ArrayList<GraphView>() private val secondaryGraphsLabel = ArrayList<TextView>() private var carbAnimation: AnimationDrawable? = null private var _binding: OverviewFragmentBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = OverviewFragmentBinding.inflate(inflater, container, false).also { _binding = it //check screen width dm = DisplayMetrics() @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) activity?.display?.getRealMetrics(dm) else activity?.windowManager?.defaultDisplay?.getMetrics(dm) }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // pre-process landscape mode val screenWidth = dm.widthPixels val screenHeight = dm.heightPixels smallWidth = screenWidth <= Constants.SMALL_WIDTH smallHeight = screenHeight <= Constants.SMALL_HEIGHT val landscape = screenHeight < screenWidth skinProvider.activeSkin().preProcessLandscapeOverviewLayout(dm, binding, landscape, rh.gb(R.bool.isTablet), smallHeight) binding.nsclientCard.visibility = config.NSCLIENT.toVisibility() binding.notifications.setHasFixedSize(false) binding.notifications.layoutManager = LinearLayoutManager(view.context) axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80 binding.graphsLayout.bgGraph.gridLabelRenderer?.gridColor = rh.gac(context, R.attr.graphGrid) binding.graphsLayout.bgGraph.gridLabelRenderer?.reloadStyles() binding.graphsLayout.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth binding.graphsLayout.bgGraph.layoutParams?.height = rh.dpToPx(skinProvider.activeSkin().mainGraphHeight) carbAnimation = binding.infoLayout.carbsIcon.background as AnimationDrawable? carbAnimation?.setEnterFadeDuration(1200) carbAnimation?.setExitFadeDuration(1200) binding.graphsLayout.bgGraph.setOnLongClickListener { overviewData.rangeToDisplay += 6 overviewData.rangeToDisplay = if (overviewData.rangeToDisplay > 24) 6 else overviewData.rangeToDisplay sp.putInt(R.string.key_rangetodisplay, overviewData.rangeToDisplay) rxBus.send(EventPreferenceChange(rh, R.string.key_rangetodisplay)) sp.putBoolean(R.string.key_objectiveusescale, true) false } prepareGraphsIfNeeded(overviewMenus.setting.size) context?.let { overviewMenus.setupChartMenu(it, binding.graphsLayout.chartMenuButton) } binding.activeProfile.setOnClickListener(this) binding.activeProfile.setOnLongClickListener(this) binding.tempTarget.setOnClickListener(this) binding.tempTarget.setOnLongClickListener(this) binding.buttonsLayout.acceptTempButton.setOnClickListener(this) binding.buttonsLayout.treatmentButton.setOnClickListener(this) binding.buttonsLayout.wizardButton.setOnClickListener(this) binding.buttonsLayout.calibrationButton.setOnClickListener(this) binding.buttonsLayout.cgmButton.setOnClickListener(this) binding.buttonsLayout.insulinButton.setOnClickListener(this) binding.buttonsLayout.carbsButton.setOnClickListener(this) binding.buttonsLayout.quickWizardButton.setOnClickListener(this) binding.buttonsLayout.quickWizardButton.setOnLongClickListener(this) binding.infoLayout.apsMode.setOnClickListener(this) binding.infoLayout.apsMode.setOnLongClickListener(this) binding.activeProfile.setOnLongClickListener(this) } @Synchronized override fun onPause() { super.onPause() disposable.clear() handler.removeCallbacksAndMessages(null) } @Synchronized override fun onResume() { super.onResume() disposable += activePlugin.activeOverview.overviewBus .toObservable(EventUpdateOverviewCalcProgress::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateCalcProgress() }, fabricPrivacy::logException) disposable += activePlugin.activeOverview.overviewBus .toObservable(EventUpdateOverviewIobCob::class.java) .debounce(1L, TimeUnit.SECONDS) .observeOn(aapsSchedulers.io) .subscribe({ updateIobCob() }, fabricPrivacy::logException) disposable += activePlugin.activeOverview.overviewBus .toObservable(EventUpdateOverviewSensitivity::class.java) .debounce(1L, TimeUnit.SECONDS) .observeOn(aapsSchedulers.main) .subscribe({ updateSensitivity() }, fabricPrivacy::logException) disposable += activePlugin.activeOverview.overviewBus .toObservable(EventUpdateOverviewGraph::class.java) .debounce(1L, TimeUnit.SECONDS) .observeOn(aapsSchedulers.main) .subscribe({ updateGraph() }, fabricPrivacy::logException) disposable += activePlugin.activeOverview.overviewBus .toObservable(EventUpdateOverviewNotification::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateNotification() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventScale::class.java) .observeOn(aapsSchedulers.main) .subscribe({ overviewData.rangeToDisplay = it.hours sp.putInt(R.string.key_rangetodisplay, it.hours) rxBus.send(EventPreferenceChange(rh, R.string.key_rangetodisplay)) sp.putBoolean(R.string.key_objectiveusescale, true) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNewBG::class.java) .debounce(1L, TimeUnit.SECONDS) .observeOn(aapsSchedulers.io) .subscribe({ updateBg() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventRefreshOverview::class.java) .observeOn(aapsSchedulers.io) .subscribe({ if (it.now) refreshAll() else scheduleUpdateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAcceptOpenLoopChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ scheduleUpdateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ scheduleUpdateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNewOpenLoopNotification::class.java) .observeOn(aapsSchedulers.io) .subscribe({ scheduleUpdateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) .delay(30, TimeUnit.MILLISECONDS, aapsSchedulers.main) .subscribe({ overviewData.pumpStatus = it.getStatus(rh) updatePumpStatus() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventEffectiveProfileSwitchChanged::class.java) .observeOn(aapsSchedulers.io) .subscribe({ updateProfile() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempTargetChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ updateTemporaryTarget() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ updateExtendedBolus() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ updateTemporaryBasal() }, fabricPrivacy::logException) refreshLoop = Runnable { refreshAll() handler.postDelayed(refreshLoop, 60 * 1000L) } handler.postDelayed(refreshLoop, 60 * 1000L) handler.post { refreshAll() } updatePumpStatus() updateCalcProgress() } fun refreshAll() { runOnUiThread { _binding ?: return@runOnUiThread updateTime() updateSensitivity() updateGraph() updateNotification() } updateBg() updateTemporaryBasal() updateExtendedBolus() updateIobCob() processButtonsVisibility() processAps() updateProfile() updateTemporaryTarget() } @Synchronized override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onClick(v: View) { // try to fix https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days // https://stackoverflow.com/questions/14860239/checking-if-state-is-saved-before-committing-a-fragmenttransaction if (childFragmentManager.isStateSaved) return activity?.let { activity -> when (v.id) { R.id.treatment_button -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) TreatmentDialog().show(childFragmentManager, "Overview") }) R.id.wizard_button -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) WizardDialog().show(childFragmentManager, "Overview") }) R.id.insulin_button -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) InsulinDialog().show(childFragmentManager, "Overview") }) R.id.quick_wizard_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) onClickQuickWizard() }) R.id.carbs_button -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) CarbsDialog().show(childFragmentManager, "Overview") }) R.id.temp_target -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) TempTargetDialog().show(childFragmentManager, "Overview") }) R.id.active_profile -> { ProfileViewerDialog().also { pvd -> pvd.arguments = Bundle().also { it.putLong("time", dateUtil.now()) it.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) } }.show(childFragmentManager, "ProfileViewDialog") } R.id.cgm_button -> { if (xdripPlugin.isEnabled()) openCgmApp("com.eveningoutpost.dexdrip") else if (dexcomPlugin.isEnabled()) { dexcomMediator.findDexcomPackageName()?.let { openCgmApp(it) } ?: ToastUtils.showToastInUiThread(activity, rh.gs(R.string.dexcom_app_not_installed)) } } R.id.calibration_button -> { if (xdripPlugin.isEnabled()) { CalibrationDialog().show(childFragmentManager, "CalibrationDialog") } else if (dexcomPlugin.isEnabled()) { try { dexcomMediator.findDexcomPackageName()?.let { startActivity( Intent("com.dexcom.cgm.activities.MeterEntryActivity") .setPackage(it) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) ) } ?: ToastUtils.showToastInUiThread(activity, rh.gs(R.string.dexcom_app_not_installed)) } catch (e: ActivityNotFoundException) { ToastUtils.showToastInUiThread(activity, rh.gs(R.string.g5appnotdetected)) } } } R.id.accept_temp_button -> { profileFunction.getProfile() ?: return if ((loop as PluginBase).isEnabled()) { handler.post { val lastRun = loop.lastRun loop.invoke("Accept temp button", false) if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) { protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) OKDialog.showConfirmation(activity, rh.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned() ?: "".toSpanned(), { uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview) (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?)?.cancel(Constants.notificationID) rxBus.send(EventMobileToWear(EventData.CancelNotification(dateUtil.now()))) Thread { loop.acceptChangeRequest() }.start() binding.buttonsLayout.acceptTempButton.visibility = View.GONE }) }) } } } } R.id.aps_mode -> { protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) LoopDialog().also { dialog -> dialog.arguments = Bundle().also { it.putInt("showOkCancel", 1) } }.show(childFragmentManager, "Overview") }) } } } } private fun openCgmApp(packageName: String) { context?.let { val packageManager = it.packageManager try { val intent = packageManager.getLaunchIntentForPackage(packageName) ?: throw ActivityNotFoundException() intent.addCategory(Intent.CATEGORY_LAUNCHER) it.startActivity(intent) } catch (e: ActivityNotFoundException) { OKDialog.show(it, "", rh.gs(R.string.error_starting_cgm)) } } } override fun onLongClick(v: View): Boolean { when (v.id) { R.id.quick_wizard_button -> { startActivity(Intent(v.context, QuickWizardListActivity::class.java)) return true } R.id.aps_mode -> { activity?.let { activity -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { LoopDialog().also { dialog -> dialog.arguments = Bundle().also { it.putInt("showOkCancel", 0) } }.show(childFragmentManager, "Overview") }) } } R.id.temp_target -> v.performClick() R.id.active_profile -> activity?.let { activity -> if (loop.isDisconnected) OKDialog.show(activity, rh.gs(R.string.not_available_full), rh.gs(R.string.smscommunicator_pumpdisconnected)) else protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { ProfileSwitchDialog().show(childFragmentManager, "ProfileSwitchDialog") }) } } return false } private fun onClickQuickWizard() { val actualBg = iobCobCalculator.ads.actualBg() val profile = profileFunction.getProfile() val profileName = profileFunction.getProfileName() val pump = activePlugin.activePump val quickWizardEntry = quickWizard.getActive() if (quickWizardEntry != null && actualBg != null && profile != null) { binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE val wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true) if (wizard.calculatedTotalInsulin > 0.0 && quickWizardEntry.carbs() > 0.0) { val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() activity?.let { if (abs(wizard.insulinAfterConstraints - wizard.calculatedTotalInsulin) >= pump.pumpDescription.pumpType.determineCorrectBolusStepSize(wizard.insulinAfterConstraints) || carbsAfterConstraints != quickWizardEntry.carbs()) { OKDialog.show(it, rh.gs(R.string.treatmentdeliveryerror), rh.gs(R.string.constraints_violation) + "\n" + rh.gs(R.string.changeyourinput)) return } wizard.confirmAndExecute(it) } } } } @SuppressLint("SetTextI18n") private fun processButtonsVisibility() { val lastBG = iobCobCalculator.ads.lastBg() val pump = activePlugin.activePump val profile = profileFunction.getProfile() val profileName = profileFunction.getProfileName() val actualBG = iobCobCalculator.ads.actualBg() // QuickWizard button val quickWizardEntry = quickWizard.getActive() runOnUiThread { _binding ?: return@runOnUiThread if (quickWizardEntry != null && lastBG != null && profile != null && pump.isInitialized() && !pump.isSuspended() && !loop.isDisconnected) { binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE val wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false) binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + rh.gs(R.string.format_carbs, quickWizardEntry.carbs()) + " " + rh.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) if (wizard.calculatedTotalInsulin <= 0) binding.buttonsLayout.quickWizardButton.visibility = View.GONE } else binding.buttonsLayout.quickWizardButton.visibility = View.GONE } // **** Temp button **** val lastRun = loop.lastRun val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() val showAcceptButton = !closedLoopEnabled.value() && // Open mode needed lastRun != null && (lastRun.lastOpenModeAccept == 0L || lastRun.lastOpenModeAccept < lastRun.lastAPSRun) &&// never accepted or before last result lastRun.constraintsProcessed?.isChangeRequested == true // change is requested runOnUiThread { _binding ?: return@runOnUiThread if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && (loop as PluginBase).isEnabled()) { binding.buttonsLayout.acceptTempButton.visibility = View.VISIBLE binding.buttonsLayout.acceptTempButton.text = "${rh.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}" } else { binding.buttonsLayout.acceptTempButton.visibility = View.GONE } // **** Various treatment buttons **** binding.buttonsLayout.carbsButton.visibility = ((!activePlugin.activePump.pumpDescription.storesCarbInfo || pump.isInitialized() && !pump.isSuspended()) && profile != null && sp.getBoolean(R.string.key_show_carbs_button, true)).toVisibility() binding.buttonsLayout.treatmentButton.visibility = (!loop.isDisconnected && pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_treatment_button, false)).toVisibility() binding.buttonsLayout.wizardButton.visibility = (!loop.isDisconnected && pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_wizard_button, true)).toVisibility() binding.buttonsLayout.insulinButton.visibility = (!loop.isDisconnected && pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_insulin_button, true)).toVisibility() // **** Calibration & CGM buttons **** val xDripIsBgSource = xdripPlugin.isEnabled() val dexcomIsSource = dexcomPlugin.isEnabled() binding.buttonsLayout.calibrationButton.visibility = (xDripIsBgSource && actualBG != null && sp.getBoolean(R.string.key_show_calibration_button, true)).toVisibility() if (dexcomIsSource) { binding.buttonsLayout.cgmButton.setCompoundDrawablesWithIntrinsicBounds(null, rh.gd(R.drawable.ic_byoda), null, null) for (drawable in binding.buttonsLayout.cgmButton.compoundDrawables) { drawable?.mutate() drawable?.colorFilter = PorterDuffColorFilter(rh.gac(context, R.attr.cgmDexColor), PorterDuff.Mode.SRC_IN) } binding.buttonsLayout.cgmButton.setTextColor(rh.gac(context, R.attr.cgmDexColor)) } else if (xDripIsBgSource) { binding.buttonsLayout.cgmButton.setCompoundDrawablesWithIntrinsicBounds(null, rh.gd(R.drawable.ic_xdrip), null, null) for (drawable in binding.buttonsLayout.cgmButton.compoundDrawables) { drawable?.mutate() drawable?.colorFilter = PorterDuffColorFilter(rh.gac(context, R.attr.cgmXdripColor), PorterDuff.Mode.SRC_IN) } binding.buttonsLayout.cgmButton.setTextColor(rh.gac(context, R.attr.cgmXdripColor)) } binding.buttonsLayout.cgmButton.visibility = (sp.getBoolean(R.string.key_show_cgm_button, false) && (xDripIsBgSource || dexcomIsSource)).toVisibility() // Automation buttons binding.buttonsLayout.userButtonsLayout.removeAllViews() val events = automationPlugin.userEvents() if (!loop.isDisconnected && pump.isInitialized() && !pump.isSuspended() && profile != null) for (event in events) if (event.isEnabled && event.trigger.shouldRun()) context?.let { context -> SingleClickButton(context, null, R.attr.customBtnStyle).also { it.setTextColor(rh.gac(context, R.attr.treatmentButton)) it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f) it.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f).also { l -> l.setMargins(0, 0, rh.dpToPx(-4), 0) } it.setCompoundDrawablesWithIntrinsicBounds(null, rh.gd(R.drawable.ic_danar_useropt), null, null) it.text = event.title it.setOnClickListener { OKDialog.showConfirmation(context, rh.gs(R.string.run_question, event.title), { handler.post { automationPlugin.processEvent(event) } }) } binding.buttonsLayout.userButtonsLayout.addView(it) } } binding.buttonsLayout.userButtonsLayout.visibility = events.isNotEmpty().toVisibility() } } private fun processAps() { val pump = activePlugin.activePump val profile = profileFunction.getProfile() // aps mode val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() fun apsModeSetA11yLabel(stringRes: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { binding.infoLayout.apsMode.stateDescription = rh.gs(stringRes) } else { binding.infoLayout.apsMode.contentDescription = rh.gs(R.string.apsmode_title) + " " + rh.gs(stringRes) } } runOnUiThread { _binding ?: return@runOnUiThread if (config.APS && pump.pumpDescription.isTempBasalCapable) { binding.infoLayout.apsMode.visibility = View.VISIBLE binding.infoLayout.timeLayout.visibility = View.GONE when { (loop as PluginBase).isEnabled() && loop.isSuperBolus -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus) apsModeSetA11yLabel(R.string.superbolus) binding.infoLayout.apsModeText.text = dateUtil.age(loop.minutesToEndOfSuspend() * 60000L, true, rh) binding.infoLayout.apsModeText.visibility = View.VISIBLE } loop.isDisconnected -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected) apsModeSetA11yLabel(R.string.disconnected) binding.infoLayout.apsModeText.text = dateUtil.age(loop.minutesToEndOfSuspend() * 60000L, true, rh) binding.infoLayout.apsModeText.visibility = View.VISIBLE } (loop as PluginBase).isEnabled() && loop.isSuspended -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused) apsModeSetA11yLabel(R.string.suspendloop_label) binding.infoLayout.apsModeText.text = dateUtil.age(loop.minutesToEndOfSuspend() * 60000L, true, rh) binding.infoLayout.apsModeText.visibility = View.VISIBLE } pump.isSuspended() -> { binding.infoLayout.apsMode.setImageResource( if (pump.model() == PumpType.OMNIPOD_EROS || pump.model() == PumpType.OMNIPOD_DASH) { // For Omnipod, indicate the pump as disconnected when it's suspended. // The only way to 'reconnect' it, is through the Omnipod tab apsModeSetA11yLabel(R.string.disconnected) R.drawable.ic_loop_disconnected } else { apsModeSetA11yLabel(R.string.pump_paused) R.drawable.ic_loop_paused } ) binding.infoLayout.apsModeText.visibility = View.GONE } (loop as PluginBase).isEnabled() && closedLoopEnabled.value() && loop.isLGS -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_lgs) apsModeSetA11yLabel(R.string.uel_lgs_loop_mode) binding.infoLayout.apsModeText.visibility = View.GONE } (loop as PluginBase).isEnabled() && closedLoopEnabled.value() -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_closed) apsModeSetA11yLabel(R.string.closedloop) binding.infoLayout.apsModeText.visibility = View.GONE } (loop as PluginBase).isEnabled() && !closedLoopEnabled.value() -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_open) apsModeSetA11yLabel(R.string.openloop) binding.infoLayout.apsModeText.visibility = View.GONE } else -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disabled) apsModeSetA11yLabel(R.string.disabledloop) binding.infoLayout.apsModeText.visibility = View.GONE } } // Show variable sensitivity val request = loop.lastRun?.request if (request is DetermineBasalResultSMB) { val isfMgdl = profile?.getIsfMgdl() val variableSens = request.variableSens if (variableSens != isfMgdl && variableSens != null && isfMgdl != null) { binding.infoLayout.variableSensitivity.text = String.format( Locale.getDefault(), "%1$.1f→%2$.1f", Profile.toUnits(isfMgdl, isfMgdl * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()), Profile.toUnits(variableSens, variableSens * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) ) binding.infoLayout.variableSensitivity.visibility = View.VISIBLE } else binding.infoLayout.variableSensitivity.visibility = View.GONE } else binding.infoLayout.variableSensitivity.visibility = View.GONE } else { //nsclient binding.infoLayout.apsMode.visibility = View.GONE binding.infoLayout.apsModeText.visibility = View.GONE binding.infoLayout.timeLayout.visibility = View.VISIBLE } // pump status from ns binding.pump.text = nsDeviceStatus.pumpStatus binding.pump.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.pump), nsDeviceStatus.extendedPumpStatus) } } // OpenAPS status from ns binding.openaps.text = nsDeviceStatus.openApsStatus binding.openaps.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.openaps), nsDeviceStatus.extendedOpenApsStatus) } } // Uploader status from ns binding.uploader.text = nsDeviceStatus.uploaderStatusSpanned binding.uploader.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } } } } private fun prepareGraphsIfNeeded(numOfGraphs: Int) { if (numOfGraphs != secondaryGraphs.size - 1) { //aapsLogger.debug("New secondary graph count ${numOfGraphs-1}") // rebuild needed secondaryGraphs.clear() secondaryGraphsLabel.clear() binding.graphsLayout.iobGraph.removeAllViews() for (i in 1 until numOfGraphs) { val relativeLayout = RelativeLayout(context) relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) val graph = GraphView(context) graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rh.dpToPx(skinProvider.activeSkin().secondaryGraphHeight)).also { it.setMargins(0, rh.dpToPx(15), 0, rh.dpToPx(10)) } graph.gridLabelRenderer?.gridColor = rh.gac(context, R.attr.graphGrid) graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.numVerticalLabels = 3 graph.viewport.backgroundColor = rh.gac(context, R.attr.viewPortBackgroundColor) relativeLayout.addView(graph) val label = TextView(context) val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(rh.dpToPx(30), rh.dpToPx(25), 0, 0) } layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) label.layoutParams = layoutParams relativeLayout.addView(label) secondaryGraphsLabel.add(label) binding.graphsLayout.iobGraph.addView(relativeLayout) secondaryGraphs.add(graph) } } } var task: Runnable? = null private fun scheduleUpdateGUI() { class UpdateRunnable : Runnable { override fun run() { refreshAll() task = null } } task?.let { handler.removeCallbacks(it) } task = UpdateRunnable() task?.let { handler.postDelayed(it, 500) } } @SuppressLint("SetTextI18n") fun updateBg() { val units = profileFunction.getUnits() val lastBg = overviewData.lastBg val lastBgColor = overviewData.lastBgColor(context) val isActualBg = overviewData.isActualBg val glucoseStatus = glucoseStatusProvider.glucoseStatusData val trendDescription = trendCalculator.getTrendDescription(lastBg) val trendArrow = trendCalculator.getTrendArrow(lastBg) val lastBgDescription = overviewData.lastBgDescription runOnUiThread { _binding ?: return@runOnUiThread binding.infoLayout.bg.text = lastBg?.valueToUnitsString(units) ?: rh.gs(R.string.notavailable) binding.infoLayout.bg.setTextColor(lastBgColor) binding.infoLayout.arrow.setImageResource(trendArrow.directionToIcon()) binding.infoLayout.arrow.setColorFilter(lastBgColor) binding.infoLayout.arrow.contentDescription = lastBgDescription + " " + rh.gs(R.string.and) + " " + trendDescription if (glucoseStatus != null) { binding.infoLayout.deltaLarge.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) binding.infoLayout.deltaLarge.setTextColor(lastBgColor) binding.infoLayout.delta.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) binding.infoLayout.avgDelta.text = Profile.toSignedUnitsString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units) binding.infoLayout.longAvgDelta.text = Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units) } else { binding.infoLayout.deltaLarge.text = "" binding.infoLayout.delta.text = "Δ " + rh.gs(R.string.notavailable) binding.infoLayout.avgDelta.text = "" binding.infoLayout.longAvgDelta.text = "" } // strike through if BG is old binding.infoLayout.bg.paintFlags = if (!isActualBg) binding.infoLayout.bg.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG else binding.infoLayout.bg.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() val outDate = (if (!isActualBg) rh.gs(R.string.a11y_bg_outdated) else "") binding.infoLayout.bg.contentDescription = rh.gs(R.string.a11y_blood_glucose) + " " + binding.infoLayout.bg.text.toString() + " " + lastBgDescription + " " + outDate binding.infoLayout.timeAgo.text = dateUtil.minAgo(rh, lastBg?.timestamp) binding.infoLayout.timeAgo.contentDescription = dateUtil.minAgoLong(rh, lastBg?.timestamp) binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(lastBg?.timestamp) + ")" val qualityIcon = bgQualityCheckPlugin.icon() if (qualityIcon != 0) { binding.infoLayout.bgQuality.visibility = View.VISIBLE binding.infoLayout.bgQuality.setImageResource(qualityIcon) binding.infoLayout.bgQuality.contentDescription = rh.gs(R.string.a11y_bg_quality) + " " + bgQualityCheckPlugin.stateDescription() binding.infoLayout.bgQuality.setOnClickListener { context?.let { context -> OKDialog.show(context, rh.gs(R.string.data_status), bgQualityCheckPlugin.message) } } } else { binding.infoLayout.bgQuality.visibility = View.GONE } } } private fun updateProfile() { val profile = profileFunction.getProfile() runOnUiThread { _binding ?: return@runOnUiThread val profileBackgroundColor = profile?.let { if (it is ProfileSealed.EPS) { if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L) R.attr.ribbonWarningColor else R.attr.ribbonDefaultColor } else if (it is ProfileSealed.PS) { R.attr.ribbonDefaultColor } else { R.attr.ribbonDefaultColor } } ?: R.attr.ribbonCriticalColor val profileTextColor = profile?.let { if (it is ProfileSealed.EPS) { if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L) R.attr.ribbonTextWarningColor else R.attr.ribbonTextDefaultColor } else if (it is ProfileSealed.PS) { R.attr.ribbonTextDefaultColor } else { R.attr.ribbonTextDefaultColor } } ?: R.attr.ribbonTextDefaultColor setRibbon(binding.activeProfile, profileTextColor, profileBackgroundColor, profileFunction.getProfileNameWithRemainingTime()) } } private fun updateTemporaryBasal() { val temporaryBasalText = overviewData.temporaryBasalText(iobCobCalculator) val temporaryBasalColor = overviewData.temporaryBasalColor(context, iobCobCalculator) val temporaryBasalIcon = overviewData.temporaryBasalIcon(iobCobCalculator) val temporaryBasalDialogText = overviewData.temporaryBasalDialogText(iobCobCalculator) runOnUiThread { _binding ?: return@runOnUiThread binding.infoLayout.baseBasal.text = temporaryBasalText binding.infoLayout.baseBasal.setTextColor(temporaryBasalColor) binding.infoLayout.baseBasalIcon.setImageResource(temporaryBasalIcon) binding.infoLayout.basalLayout.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.basal), temporaryBasalDialogText) } } } } private fun updateExtendedBolus() { val pump = activePlugin.activePump val extendedBolus = iobCobCalculator.getExtendedBolus(dateUtil.now()) val extendedBolusText = overviewData.extendedBolusText(iobCobCalculator) val extendedBolusDialogText = overviewData.extendedBolusDialogText(iobCobCalculator) runOnUiThread { _binding ?: return@runOnUiThread binding.infoLayout.extendedBolus.text = extendedBolusText binding.infoLayout.extendedLayout.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.extended_bolus), extendedBolusDialogText) } } binding.infoLayout.extendedLayout.visibility = (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility() } } private fun updateTime() { _binding ?: return binding.infoLayout.time.text = dateUtil.timeString(dateUtil.now()) // Status lights val pump = activePlugin.activePump val isPatchPump = pump.pumpDescription.isPatchPump binding.statusLightsLayout.apply { cannulaOrPatch.setImageResource(if (isPatchPump) R.drawable.ic_patch_pump_outline else R.drawable.ic_cp_age_cannula) cannulaOrPatch.contentDescription = rh.gs(if (isPatchPump) R.string.statuslights_patch_pump_age else R.string.statuslights_cannula_age) cannulaOrPatch.scaleX = if (isPatchPump) 1.4f else 2f cannulaOrPatch.scaleY = cannulaOrPatch.scaleX insulinAge.visibility = isPatchPump.not().toVisibility() batteryLayout.visibility = (!isPatchPump || pump.pumpDescription.useHardwareLink).toVisibility() pbAge.visibility = (pump.pumpDescription.isBatteryReplaceable || pump.isBatteryChangeLoggingEnabled()).toVisibility() val useBatteryLevel = (pump.model() == PumpType.OMNIPOD_EROS && pump is OmnipodErosPumpPlugin) || (pump.model() != PumpType.ACCU_CHEK_COMBO && pump.model() != PumpType.OMNIPOD_DASH) batteryLevel.visibility = useBatteryLevel.toVisibility() statusLights.visibility = (sp.getBoolean(R.string.key_show_statuslights, true) || config.NSCLIENT).toVisibility() } statusLightHandler.updateStatusLights( binding.statusLightsLayout.cannulaAge, binding.statusLightsLayout.insulinAge, binding.statusLightsLayout.reservoirLevel, binding.statusLightsLayout.sensorAge, null, binding.statusLightsLayout.pbAge, binding.statusLightsLayout.batteryLevel ) } private fun updateIobCob() { val iobText = overviewData.iobText(iobCobCalculator) val iobDialogText = overviewData.iobDialogText(iobCobCalculator) val displayText = overviewData.cobInfo(iobCobCalculator).displayText(rh, dateUtil, buildHelper.isEngineeringMode()) val lastCarbsTime = overviewData.lastCarbsTime runOnUiThread { _binding ?: return@runOnUiThread binding.infoLayout.iob.text = iobText binding.infoLayout.iobLayout.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.iob), iobDialogText) } } // cob var cobText = displayText ?: rh.gs(R.string.value_unavailable_short) val constraintsProcessed = loop.lastRun?.constraintsProcessed val lastRun = loop.lastRun if (config.APS && constraintsProcessed != null && lastRun != null) { if (constraintsProcessed.carbsReq > 0) { //only display carbsreq when carbs have not been entered recently if (lastCarbsTime < lastRun.lastAPSRun) { cobText += " | " + constraintsProcessed.carbsReq + " " + rh.gs(R.string.required) } if (carbAnimation?.isRunning == false) carbAnimation?.start() } else { carbAnimation?.stop() carbAnimation?.selectDrawable(0) } } binding.infoLayout.cob.text = cobText } } @SuppressLint("SetTextI18n") fun updateTemporaryTarget() { val units = profileFunction.getUnits() val tempTarget = overviewData.temporaryTarget runOnUiThread { _binding ?: return@runOnUiThread if (tempTarget != null) { setRibbon( binding.tempTarget, R.attr.ribbonTextWarningColor, R.attr.ribbonWarningColor, Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh) ) } else { // If the target is not the same as set in the profile then oref has overridden it profileFunction.getProfile()?.let { profile -> val targetUsed = loop.lastRun?.constraintsProcessed?.targetBG ?: 0.0 if (targetUsed != 0.0 && abs(profile.getTargetMgdl() - targetUsed) > 0.01) { aapsLogger.debug("Adjusted target. Profile: ${profile.getTargetMgdl()} APS: $targetUsed") setRibbon( binding.tempTarget, R.attr.ribbonTextWarningColor, R.attr.tempTargetBackgroundColor, Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units) ) } else { setRibbon( binding.tempTarget, R.attr.ribbonTextDefaultColor, R.attr.ribbonDefaultColor, Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units) ) } } } } } private fun setRibbon(view: TextView, attrResText: Int, attrResBack: Int, text: String) { with(view) { setText(text) setBackgroundColor(rh.gac(context, attrResBack)) setTextColor(rh.gac(context, attrResText)) compoundDrawables[0]?.setTint(rh.gac(context, attrResText)) } } private fun updateGraph() { _binding ?: return val pump = activePlugin.activePump val graphData = GraphData(injector, binding.graphsLayout.bgGraph, overviewData) val menuChartSettings = overviewMenus.setting if (menuChartSettings.isEmpty()) return graphData.addInRangeArea(overviewData.fromTime, overviewData.endTime, defaultValueHelper.determineLowLine(), defaultValueHelper.determineHighLine()) graphData.addBgReadings(menuChartSettings[0][OverviewMenus.CharType.PRE.ordinal], context) if (buildHelper.isDev()) graphData.addBucketedData() graphData.addTreatments(context) graphData.addEps(context, 0.95) if (menuChartSettings[0][OverviewMenus.CharType.TREAT.ordinal]) graphData.addTherapyEvents() if (menuChartSettings[0][OverviewMenus.CharType.ACT.ordinal]) graphData.addActivity(0.8) if ((pump.pumpDescription.isTempBasalCapable || config.NSCLIENT) && menuChartSettings[0][OverviewMenus.CharType.BAS.ordinal]) graphData.addBasals() graphData.addTargetLine() graphData.addNowLine(dateUtil.now()) // set manual x bounds to have nice steps graphData.setNumVerticalLabels() graphData.formatAxis(overviewData.fromTime, overviewData.endTime) graphData.performUpdate() // 2nd graphs prepareGraphsIfNeeded(menuChartSettings.size) val secondaryGraphsData: ArrayList<GraphData> = ArrayList() val now = System.currentTimeMillis() for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) { val secondGraphData = GraphData(injector, secondaryGraphs[g], overviewData) var useABSForScale = false var useIobForScale = false var useCobForScale = false var useDevForScale = false var useRatioForScale = false var useDSForScale = false var useBGIForScale = false when { menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] -> useBGIForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true } val alignDevBgiScale = menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] && menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] if (menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(useABSForScale, 1.0) if (menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(useIobForScale, 1.0) if (menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(useCobForScale, if (useCobForScale) 1.0 else 0.5) if (menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(useDevForScale, 1.0) if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(useBGIForScale, if (alignDevBgiScale) 1.0 else 0.8) if (menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(useRatioForScale, if (useRatioForScale) 1.0 else 0.8) if (menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope( useDSForScale, if (useDSForScale) 1.0 else 0.8, useRatioForScale ) // set manual x bounds to have nice steps secondGraphData.formatAxis(overviewData.fromTime, overviewData.endTime) secondGraphData.addNowLine(now) secondaryGraphsData.add(secondGraphData) } for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) { secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1) secondaryGraphs[g].visibility = ( menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] ).toVisibility() secondaryGraphsData[g].performUpdate() } } private fun updateCalcProgress() { _binding ?: return binding.progressBar.progress = overviewData.calcProgressPct binding.progressBar.visibility = (overviewData.calcProgressPct != 100).toVisibility() } private fun updateSensitivity() { _binding ?: return if (sp.getBoolean(R.string.key_openapsama_useautosens, false) && constraintChecker.isAutosensModeEnabled().value()) { binding.infoLayout.sensitivityIcon.setImageResource(R.drawable.ic_swap_vert_black_48dp_green) } else { binding.infoLayout.sensitivityIcon.setImageResource(R.drawable.ic_x_swap_vert) } binding.infoLayout.sensitivity.text = overviewData.lastAutosensData(iobCobCalculator)?.let { autosensData -> String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100) } ?: "" } private fun updatePumpStatus() { _binding ?: return val status = overviewData.pumpStatus binding.pumpStatus.text = status binding.pumpStatusLayout.visibility = (status != "").toVisibility() } private fun updateNotification() { _binding ?: return binding.notifications.let { notificationStore.updateNotifications(it) } } }
agpl-3.0
6c3b18961e6573829939e2ce06f55390
53.481081
242
0.631346
5.036562
false
false
false
false
square/wire
wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt
1
17268
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.google.protobuf.ListValue import com.google.protobuf.NullValue import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.entry import org.junit.Assert.fail import org.junit.Test import squareup.proto3.kotlin.alltypes.AllStructsOuterClass import squareup.proto3.java.alltypes.AllStructs as AllStructsJ import squareup.proto3.kotlin.alltypes.AllStructs as AllStructsK class StructTest { @Test fun nullValue() { val googleMessage = null.toValue() val wireMessage = null val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun doubleValue() { val googleMessage = 0.25.toValue() val wireMessage = 0.25 val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun specialDoubleValues() { val googleMessage = listOf( Double.NEGATIVE_INFINITY, -0.0, 0.0, Double.POSITIVE_INFINITY, Double.NaN ).toListValue() val wireMessage = listOf( Double.NEGATIVE_INFINITY, -0.0, 0.0, Double.POSITIVE_INFINITY, Double.NaN ) val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun booleanTrue() { val googleMessage = true.toValue() val wireMessage = true val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun booleanFalse() { val googleMessage = false.toValue() val wireMessage = false val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun stringValue() { val googleMessage = "Cash App!".toValue() val wireMessage = "Cash App!" val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun emptyStringValue() { val googleMessage = "".toValue() val wireMessage = "" val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun utf8StringValue() { val googleMessage = "На берегу пустынных волн".toValue() val wireMessage = "На берегу пустынных волн" val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_VALUE.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_VALUE.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun map() { val googleMessage = mapOf("a" to "android", "c" to "cash").toStruct() val wireMessage = mapOf("a" to "android", "c" to "cash") val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_MAP.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_MAP.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun mapOfAllTypes() { val googleMessage = mapOf( "a" to null, "b" to 0.5, "c" to true, "d" to "cash", "e" to listOf("g", "h"), "f" to mapOf("i" to "j", "k" to "l") ).toStruct() val wireMessage = mapOf( "a" to null, "b" to 0.5, "c" to true, "d" to "cash", "e" to listOf("g", "h"), "f" to mapOf("i" to "j", "k" to "l") ) val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_MAP.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_MAP.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun mapWithoutEntries() { val googleMessage = emptyStruct() val wireMessage = mapOf<String, Any?>() val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_MAP.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_MAP.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun unsupportedKeyType() { @Suppress("UNCHECKED_CAST") // Totally unsafe. val wireMessage = mapOf(5 to "android") as Map<String, Any?> try { ProtoAdapter.STRUCT_MAP.encode(wireMessage) fail() } catch (_: ClassCastException) { } try { ProtoAdapter.STRUCT_MAP.encodedSize(wireMessage) fail() } catch (_: ClassCastException) { } try { ProtoAdapter.STRUCT_MAP.redact(wireMessage) fail() } catch (_: IllegalArgumentException) { } } @Test fun unsupportedValueType() { val wireMessage = mapOf("a" to StringBuilder("android")) try { ProtoAdapter.STRUCT_MAP.encode(wireMessage) fail() } catch (_: IllegalArgumentException) { } try { ProtoAdapter.STRUCT_MAP.encodedSize(wireMessage) fail() } catch (_: IllegalArgumentException) { } try { ProtoAdapter.STRUCT_MAP.redact(wireMessage) fail() } catch (_: IllegalArgumentException) { } } @Test fun list() { val googleMessage = listOf("android", "cash").toListValue() val wireMessage = listOf("android", "cash") val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun listOfAllTypes() { val googleMessage = listOf( null, 0.5, true, "cash", listOf("a", "b"), mapOf("c" to "d", "e" to "f") ).toListValue() val wireMessage = listOf( null, 0.5, true, "cash", listOf("a", "b"), mapOf("c" to "d", "e" to "f") ) val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun unsupportedListElement() { val wireMessage = listOf(StringBuilder()) try { ProtoAdapter.STRUCT_LIST.encode(wireMessage) fail() } catch (_: IllegalArgumentException) { } try { ProtoAdapter.STRUCT_LIST.encodedSize(wireMessage) fail() } catch (_: IllegalArgumentException) { } try { ProtoAdapter.STRUCT_LIST.redact(wireMessage) fail() } catch (_: IllegalArgumentException) { } } @Test fun listValueWithoutElements() { val googleMessage = ListValue.newBuilder().build() val wireMessage = listOf<Any?>() val googleMessageBytes = googleMessage.toByteArray() assertThat(ProtoAdapter.STRUCT_LIST.encode(wireMessage)).isEqualTo(googleMessageBytes) assertThat(ProtoAdapter.STRUCT_LIST.decode(googleMessageBytes)).isEqualTo(wireMessage) } @Test fun nullMapAndListAsFields() { val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder().build() val wireAllStructJava = AllStructsJ.Builder().build() val wireAllStructKotlin = AllStructsK() val protocAllStructBytes = protocAllStruct.toByteArray() assertThat(AllStructsJ.ADAPTER.encode(wireAllStructJava)).isEqualTo(protocAllStructBytes) assertThat(AllStructsJ.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructJava) assertThat(AllStructsK.ADAPTER.encode(wireAllStructKotlin)).isEqualTo(protocAllStructBytes) assertThat(AllStructsK.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructKotlin) } @Test fun emptyMapAndListAsFields() { val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder() .setStruct(emptyStruct()) .setList(emptyListValue()) .build() val wireAllStructJava = AllStructsJ.Builder() .struct(emptyMap<String, Any?>()) .list(emptyList<Any?>()) .build() val wireAllStructKotlin = AllStructsK( struct = emptyMap<String, Any?>(), list = emptyList<Any?>() ) val protocAllStructBytes = protocAllStruct.toByteArray() assertThat(AllStructsJ.ADAPTER.encode(wireAllStructJava)).isEqualTo(protocAllStructBytes) assertThat(AllStructsJ.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructJava) assertThat(AllStructsK.ADAPTER.encode(wireAllStructKotlin)).isEqualTo(protocAllStructBytes) assertThat(AllStructsK.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructKotlin) } // Note: We are not testing nulls because while protoc emits `NULL_VALUE`s, Wire doesn't. @Test fun structRoundTripWithData() { val protocAllStruct = AllStructsOuterClass.AllStructs.newBuilder() .setStruct(mapOf("a" to 1.0).toStruct()) .setList(listOf("a", 3.0).toListValue()) .setNullValue(NullValue.NULL_VALUE) .setValueA("a".toValue()) .setValueB(33.0.toValue()) .setValueC(true.toValue()) .setValueE(mapOf("a" to 1.0).toValue()) .setValueF(listOf("a", 3.0).toValue()) .build() val wireAllStructJava = AllStructsJ.Builder() .struct(mapOf("a" to 1.0)) .list(listOf("a", 3.0)) .null_value(null) .value_a("a") .value_b(33.0) .value_c(true) .value_e(mapOf("a" to 1.0)) .value_f(listOf("a", 3.0)) .build() val wireAllStructKotlin = AllStructsK( struct = mapOf("a" to 1.0), list = listOf("a", 3.0), null_value = null, value_a = "a", value_b = 33.0, value_c = true, value_e = mapOf("a" to 1.0), value_f = listOf("a", 3.0) ) val protocAllStructBytes = protocAllStruct.toByteArray() assertThat(AllStructsJ.ADAPTER.encode(wireAllStructJava)).isEqualTo(protocAllStructBytes) assertThat(AllStructsJ.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructJava) assertThat(AllStructsK.ADAPTER.encode(wireAllStructKotlin)).isEqualTo(protocAllStructBytes) assertThat(AllStructsK.ADAPTER.decode(protocAllStructBytes)).isEqualTo(wireAllStructKotlin) } @Test fun javaListsAreDeeplyImmutable() { val list = mutableListOf(mutableMapOf("a" to "b"), mutableListOf("c"), "d", 5.0, false, null) val allStructs = AllStructsJ.Builder() .list(list) .build() assertThat(allStructs.list.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the list. Wire should have defensive copies. (list[0] as MutableMap<*, *>).clear() (list[1] as MutableList<*>).clear() list.clear() assertThat(allStructs.list) .containsExactly(mapOf("a" to "b"), listOf("c"), "d", 5.0, false, null) } @Test fun kotlinListsAreDeeplyImmutable() { val list = mutableListOf(mutableMapOf("a" to "b"), mutableListOf("c"), "d", 5.0, false, null) val allStructs = AllStructsK.Builder() .list(list) .build() assertThat(allStructs.list!!.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the list. Wire should have defensive copies. (list[0] as MutableMap<*, *>).clear() (list[1] as MutableList<*>).clear() list.clear() assertThat(allStructs.list) .containsExactly(mapOf("a" to "b"), listOf("c"), "d", 5.0, false, null) } @Test fun javaMapsAreDeeplyImmutable() { val map = mutableMapOf( "a" to mutableMapOf("g" to "h"), "b" to mutableListOf("i"), "c" to "j", "d" to 5.0, "e" to false, "f" to null ) val allStructs = AllStructsJ.Builder() .struct(map) .build() assertThat(allStructs.struct.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the map. Wire should have defensive copies. (map["a"] as MutableMap<*, *>).clear() (map["b"] as MutableList<*>).clear() map.clear() assertThat(allStructs.struct).containsExactly( entry("a", mapOf("g" to "h")), entry("b", listOf("i")), entry("c", "j"), entry("d", 5.0), entry("e", false), entry("f", null) ) } @Test fun kotlinMapsAreDeeplyImmutable() { val map = mutableMapOf( "a" to mutableMapOf("g" to "h"), "b" to mutableListOf("i"), "c" to "j", "d" to 5.0, "e" to false, "f" to null ) val allStructs = AllStructsK.Builder() .struct(map) .build() assertThat(allStructs.struct.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the map. Wire should have defensive copies. (map["a"] as MutableMap<*, *>).clear() (map["b"] as MutableList<*>).clear() map.clear() assertThat(allStructs.struct).containsExactly( entry("a", mapOf("g" to "h")), entry("b", listOf("i")), entry("c", "j"), entry("d", 5.0), entry("e", false), entry("f", null) ) } @Test fun nonStructTypeCannotBeConstructed() { try { AllStructsK.Builder() .struct(mapOf("a" to 1)) // Int. .build() } catch (e: IllegalArgumentException) { assertThat(e).hasMessage( "struct value struct must be a JSON type " + "(null, Boolean, Double, String, List, or Map) but was class kotlin.Int: 1" ) } } @Test fun javaStructsInMapValuesAreDeeplyImmutable() { val map = mutableMapOf("a" to "b") val allStructs = AllStructsJ.Builder() .map_int32_struct(mapOf(5 to map)) .build() assertThat(allStructs.map_int32_struct.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the map. Wire should have defensive copies. map.clear() assertThat(allStructs.map_int32_struct).containsExactly(entry(5, mapOf("a" to "b"))) } @Test fun kotlinStructsInMapValuesAreDeeplyImmutable() { val map = mutableMapOf("a" to "b") val allStructs = AllStructsK.Builder() .map_int32_struct(mapOf(5 to map)) .build() assertThat(allStructs.map_int32_struct.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the map. Wire should have defensive copies. map.clear() assertThat(allStructs.map_int32_struct).containsExactly(entry(5, mapOf("a" to "b"))) } @Test fun javaStructsInListValuesAreDeeplyImmutable() { val map = mutableMapOf("a" to "b") val allStructs = AllStructsJ.Builder() .rep_struct(listOf(map)) .build() assertThat(allStructs.rep_struct.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the map. Wire should have defensive copies. map.clear() assertThat(allStructs.rep_struct).containsExactly(mapOf("a" to "b")) } @Test fun kotlinStructsInListValuesAreDeeplyImmutable() { val map = mutableMapOf("a" to "b") val allStructs = AllStructsK.Builder() .rep_struct(listOf(map)) .build() assertThat(allStructs.rep_struct.isDeeplyUnmodifiable()).isTrue() // Mutate the values used to create the map. Wire should have defensive copies. map.clear() assertThat(allStructs.rep_struct).containsExactly(mapOf("a" to "b")) } private fun Any?.isDeeplyUnmodifiable(): Boolean { return when (this) { null -> true is String -> true is Double -> true is Int -> true is Boolean -> true is List<*> -> { this.all { it.isDeeplyUnmodifiable() } && this.isUnmodifiable() } is Map<*, *> -> { this.all { it.key.isDeeplyUnmodifiable() && it.value.isDeeplyUnmodifiable() } && this.isUnmodifiable() } else -> false } } private fun List<*>.isUnmodifiable(): Boolean { try { (this as MutableList<Any>).add("x") return false } catch (_: UnsupportedOperationException) { return true } } private fun Map<*, *>.isUnmodifiable(): Boolean { try { (this as MutableMap<Any, Any>).put("x", "x") return false } catch (_: UnsupportedOperationException) { return true } } }
apache-2.0
cc6611ddd2e417932d8fdf46f8e9ff79
30.434307
97
0.673923
3.900815
false
true
false
false
thanhiro/react-liferay-portlet
src/main/kotlin/com/example/liferay/reactpoc/portlet/MainPortletConfiguration.kt
1
331
package com.example.liferay.reactpoc.portlet import aQute.bnd.annotation.metatype.Meta @Meta.OCD(id = "MainPortletConfiguration") interface MainPortletConfiguration { @Meta.AD(deflt = "false", required = false) fun universalRender(): String @Meta.AD(deflt = "false", required = false) fun historyApi(): String }
mit
d9fe37672018a52aa10c57f00cc87242
26.583333
47
0.731118
3.245098
false
true
false
false
PolymerLabs/arcs
java/arcs/core/storage/driver/volatiles/VolatileEntry.kt
1
370
package arcs.core.storage.driver.volatiles /** A single entry in a [VolatileDriver]. */ data class VolatileEntry<Data : Any>( val data: Data? = null, val version: Int = 0, val drivers: Set<VolatileDriver<Data>> = emptySet() ) { constructor(data: Data? = null, version: Int = 0, vararg drivers: VolatileDriver<Data>) : this(data, version, drivers.toSet()) }
bsd-3-clause
1f47fca8fd8244e56c3020bab9837224
32.636364
91
0.689189
3.457944
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/service/RuntimeDialogService.kt
1
4617
package com.bajdcc.LALR1.grammar.runtime.service import com.bajdcc.LALR1.grammar.runtime.RuntimeObject import com.bajdcc.LALR1.grammar.runtime.RuntimeObjectType import com.bajdcc.LALR1.grammar.runtime.data.RuntimeArray import org.apache.log4j.Logger import javax.swing.JOptionPane import javax.swing.JPanel import javax.swing.SwingUtilities /** * 【运行时】运行时文件服务 * * @author bajdcc */ class RuntimeDialogService(private val service: RuntimeService) : IRuntimeDialogService { private val arrDialogs = Array<DialogStruct?>(MAX_DIALOG) { null } private val setDialogId = mutableSetOf<Int>() private var cyclePtr = 0 override fun create(caption: String, text: String, mode: Int, panel: JPanel): Int { if (setDialogId.size >= MAX_DIALOG) { return -1 } val handle: Int while (true) { if (arrDialogs[cyclePtr] == null) { handle = cyclePtr val ds = DialogStruct(handle, caption, text, mode, panel) synchronized(setDialogId) { setDialogId.add(cyclePtr) arrDialogs[cyclePtr++] = ds if (cyclePtr >= MAX_DIALOG) { cyclePtr -= MAX_DIALOG } } break } cyclePtr++ if (cyclePtr >= MAX_DIALOG) { cyclePtr -= MAX_DIALOG } } logger.debug("Dialog #$handle '$caption' created") return handle } override fun show(handle: Int): Boolean { if (!setDialogId.contains(handle)) { return false } val ds = arrDialogs[handle]!! val mode = ds.mode when (mode) { in 0..4 -> { val type = mode - 1 SwingUtilities.invokeLater { JOptionPane.showMessageDialog(ds.panel, ds.text, ds.caption, type) // 取得共享变量 // 发送信号 synchronized(setDialogId) { arrDialogs[handle] = null setDialogId.remove(handle) } service.pipeService.write(service.pipeService.create("DIALOG#SIG#$handle", "/dialog/0"), '*') } } in 10..13 -> { val type = mode - 11 SwingUtilities.invokeLater { val value = JOptionPane.showConfirmDialog(ds.panel, ds.text, ds.caption, type).toLong() // 取得共享变量 val obj = service.shareService.getSharing("DIALOG#DATA#$handle", false) assert(obj.type == RuntimeObjectType.kArray) (obj.obj as RuntimeArray).add(RuntimeObject(value)) // 发送信号 synchronized(setDialogId) { arrDialogs[handle] = null setDialogId.remove(handle) } service.pipeService.write(service.pipeService.create("DIALOG#SIG#$handle", "/dialog/1"), '*') } } in 20..24 -> { val type = mode - 21 SwingUtilities.invokeLater { val input = JOptionPane.showInputDialog(ds.panel, ds.text, ds.caption, type) // 取得共享变量 val obj = service.shareService.getSharing("DIALOG#DATA#$handle", false) assert(obj.type == RuntimeObjectType.kArray) (obj.obj as RuntimeArray).add(RuntimeObject(input)) // 发送信号 synchronized(setDialogId) { arrDialogs[handle] = null setDialogId.remove(handle) } service.pipeService.write(service.pipeService.create("DIALOG#SIG#$handle", "/dialog/2"), '*') } } else -> { synchronized(setDialogId) { arrDialogs[handle] = null setDialogId.remove(handle) } service.pipeService.write(service.pipeService.create("DIALOG#SIG#$handle", "/dialog/?"), '*') } } return true } internal data class DialogStruct(val handle: Int, val caption: String, val text: String, val mode: Int, val panel: JPanel) companion object { private const val MAX_DIALOG = 10 private val logger = Logger.getLogger("dialog") } }
mit
165ebc898407e39c6eb1e6ee4b8d826e
37.415254
126
0.515553
4.751572
false
false
false
false