repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
grpc/grpc-kotlin
compiler/src/main/java/io/grpc/kotlin/generator/GrpcClientStubGenerator.kt
1
11135
/* * Copyright 2020 gRPC 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 io.grpc.kotlin.generator import com.google.common.annotations.VisibleForTesting import com.google.protobuf.Descriptors.MethodDescriptor import com.google.protobuf.Descriptors.ServiceDescriptor import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName import io.grpc.CallOptions import io.grpc.MethodDescriptor.MethodType import io.grpc.Status import io.grpc.StatusException import io.grpc.kotlin.AbstractCoroutineStub import io.grpc.kotlin.ClientCalls import io.grpc.kotlin.StubFor import io.grpc.kotlin.generator.protoc.Declarations import io.grpc.kotlin.generator.protoc.GeneratorConfig import io.grpc.kotlin.generator.protoc.MemberSimpleName import io.grpc.kotlin.generator.protoc.builder import io.grpc.kotlin.generator.protoc.classBuilder import io.grpc.kotlin.generator.protoc.declarations import io.grpc.kotlin.generator.protoc.member import io.grpc.kotlin.generator.protoc.methodName import io.grpc.kotlin.generator.protoc.of import io.grpc.kotlin.generator.protoc.serviceName import kotlinx.coroutines.flow.Flow import io.grpc.Channel as GrpcChannel import io.grpc.Metadata as GrpcMetadata /** * Logic for generating gRPC stubs for Kotlin. */ @VisibleForTesting class GrpcClientStubGenerator(config: GeneratorConfig) : ServiceCodeGenerator(config) { companion object { private const val STUB_CLASS_SUFFIX = "CoroutineStub" private val UNARY_PARAMETER_NAME = MemberSimpleName("request") private val STREAMING_PARAMETER_NAME = MemberSimpleName("requests") private val GRPC_CHANNEL_PARAMETER_NAME = MemberSimpleName("channel") private val CALL_OPTIONS_PARAMETER_NAME = MemberSimpleName("callOptions") private val HEADERS_PARAMETER: ParameterSpec = ParameterSpec .builder("headers", GrpcMetadata::class) .defaultValue("%T()", GrpcMetadata::class) .build() val GRPC_CHANNEL_PARAMETER = ParameterSpec.of(GRPC_CHANNEL_PARAMETER_NAME, GrpcChannel::class) val CALL_OPTIONS_PARAMETER = ParameterSpec .builder(MemberSimpleName("callOptions"), CallOptions::class) .defaultValue("%M", CallOptions::class.member("DEFAULT")) .build() private val FLOW = Flow::class.asClassName() private val UNARY_RPC_HELPER = ClientCalls::class.member("unaryRpc") private val CLIENT_STREAMING_RPC_HELPER = ClientCalls::class.member("clientStreamingRpc") private val SERVER_STREAMING_RPC_HELPER = ClientCalls::class.member("serverStreamingRpc") private val BIDI_STREAMING_RPC_HELPER = ClientCalls::class.member("bidiStreamingRpc") private val RPC_HELPER = mapOf( MethodType.UNARY to UNARY_RPC_HELPER, MethodType.CLIENT_STREAMING to CLIENT_STREAMING_RPC_HELPER, MethodType.SERVER_STREAMING to SERVER_STREAMING_RPC_HELPER, MethodType.BIDI_STREAMING to BIDI_STREAMING_RPC_HELPER ) private val MethodDescriptor.type: MethodType get() = if (isClientStreaming) { if (isServerStreaming) MethodType.BIDI_STREAMING else MethodType.CLIENT_STREAMING } else { if (isServerStreaming) MethodType.SERVER_STREAMING else MethodType.UNARY } } override fun generate(service: ServiceDescriptor): Declarations = declarations { addType(generateStub(service)) } @VisibleForTesting fun generateStub(service: ServiceDescriptor): TypeSpec { val stubName = service.serviceName.toClassSimpleName().withSuffix(STUB_CLASS_SUFFIX) // Not actually a TypeVariableName, but this at least prevents the name from being imported, // which we don't want. val stubSelfReference: TypeName = TypeVariableName(stubName.toString()) val builder = TypeSpec .classBuilder(stubName) .superclass(AbstractCoroutineStub::class.asTypeName().parameterizedBy(stubSelfReference)) .addKdoc( "A stub for issuing RPCs to a(n) %L service as suspending coroutines.", service.fullName ) .addAnnotation( AnnotationSpec.builder(StubFor::class) .addMember("%T::class", service.grpcClass) .build() ) .primaryConstructor( FunSpec .constructorBuilder() .addParameter(GRPC_CHANNEL_PARAMETER) .addParameter(CALL_OPTIONS_PARAMETER) .addAnnotation(JvmOverloads::class) .build() ) .addSuperclassConstructorParameter("%N", GRPC_CHANNEL_PARAMETER) .addSuperclassConstructorParameter("%N", CALL_OPTIONS_PARAMETER) .addFunction(buildFun(stubSelfReference)) for (method in service.methods) { builder.addFunction(generateRpcStub(method)) } return builder.build() } /** * Outputs a `FunSpec` of an override of `AbstractCoroutineStub.build` for this particular stub. */ private fun buildFun(stubName: TypeName): FunSpec { return FunSpec .builder("build") .returns(stubName) .addModifiers(KModifier.OVERRIDE) .addParameter(GRPC_CHANNEL_PARAMETER) .addParameter(ParameterSpec.of(CALL_OPTIONS_PARAMETER_NAME, CallOptions::class)) .addStatement( "return %T(%N, %N)", stubName, GRPC_CHANNEL_PARAMETER, CALL_OPTIONS_PARAMETER ) .build() } @VisibleForTesting fun generateRpcStub(method: MethodDescriptor): FunSpec = with(config) { val name = method.methodName.toMemberSimpleName() val requestType = method.inputType.messageClass() val parameter = if (method.isClientStreaming) { ParameterSpec.of(STREAMING_PARAMETER_NAME, FLOW.parameterizedBy(requestType)) } else { ParameterSpec.of(UNARY_PARAMETER_NAME, requestType) } val responseType = method.outputType.messageClass() val returnType = if (method.isServerStreaming) FLOW.parameterizedBy(responseType) else responseType val helperMethod = RPC_HELPER[method.type] ?: throw IllegalArgumentException() val funSpecBuilder = funSpecBuilder(name) .addParameter(parameter) .addParameter(HEADERS_PARAMETER) .returns(returnType) .addKdoc(rpcStubKDoc(method, parameter)) if (method.options.deprecated) { funSpecBuilder.addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("%S", "The underlying service method is marked deprecated.") .build() ) } val codeBlockMap = mapOf( "helperMethod" to helperMethod, "methodDescriptor" to method.descriptorCode, "parameter" to parameter, "headers" to HEADERS_PARAMETER ) if (!method.isServerStreaming) { funSpecBuilder.addModifiers(KModifier.SUSPEND) } funSpecBuilder.addNamedCode( """ return %helperMethod:M( channel, %methodDescriptor:L, %parameter:N, callOptions, %headers:N ) """.trimIndent(), codeBlockMap ) return funSpecBuilder.build() } private fun rpcStubKDoc( method: MethodDescriptor, parameter: ParameterSpec ): CodeBlock { val kDocBindings = mapOf( "parameter" to parameter, "flow" to Flow::class, "status" to Status::class, "statusException" to StatusException::class, "headers" to HEADERS_PARAMETER ) val kDocComponents = mutableListOf<String>() kDocComponents.add( if (method.isServerStreaming) { """ Returns a [%flow:T] that, when collected, executes this RPC and emits responses from the server as they arrive. That flow finishes normally if the server closes its response with [`Status.OK`][%status:T], and fails by throwing a [%statusException:T] otherwise. If collecting the flow downstream fails exceptionally (including via cancellation), the RPC is cancelled with that exception as a cause. """.trimIndent() } else { """ Executes this RPC and returns the response message, suspending until the RPC completes with [`Status.OK`][%status:T]. If the RPC completes with another status, a corresponding [%statusException:T] is thrown. If this coroutine is cancelled, the RPC is also cancelled with the corresponding exception as a cause. """.trimIndent() } ) when (method.type) { MethodType.BIDI_STREAMING -> { kDocComponents.add( """ The [%flow:T] of requests is collected once each time the [%flow:T] of responses is collected. If collection of the [%flow:T] of responses completes normally or exceptionally before collection of `%parameter:N` completes, the collection of `%parameter:N` is cancelled. If the collection of `%parameter:N` completes exceptionally for any other reason, then the collection of the [%flow:T] of responses completes exceptionally for the same reason and the RPC is cancelled with that reason. """.trimIndent() ) } MethodType.CLIENT_STREAMING -> { kDocComponents.add( """ This function collects the [%flow:T] of requests. If the server terminates the RPC for any reason before collection of requests is complete, the collection of requests will be cancelled. If the collection of requests completes exceptionally for any other reason, the RPC will be cancelled for that reason and this method will throw that exception. """.trimIndent() ) } else -> {} } kDocComponents.add( if (method.isClientStreaming) { "@param %parameter:N A [%flow:T] of request messages." } else { "@param %parameter:N The request message to send to the server." } ) kDocComponents.add( "@param %headers:N Metadata to attach to the request. Most users will not need this." ) kDocComponents.add( if (method.isServerStreaming) { "@return A flow that, when collected, emits the responses from the server." } else { "@return The single response from the server." } ) return CodeBlock .builder() .addNamed(kDocComponents.joinToString("\n\n"), kDocBindings) .build() } }
apache-2.0
a02a9dde1b09641fa876b0fb2ad74350
35.870861
98
0.703727
4.546754
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/attention/multihead/MultiHeadAttentionParameters.kt
1
2702
/* Copyright 2020-present Simone Cangialosi. All Rights Reserved. * * 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 com.kotlinnlp.simplednn.deeplearning.attention.multihead import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer import com.kotlinnlp.simplednn.core.layers.LayerInterface import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters import com.kotlinnlp.simplednn.core.layers.models.attention.scaleddot.ScaledDotAttentionLayerParameters import java.io.Serializable /** * The parameters of the multi-head attention network. * * @property inputSize the size of the input arrays * @property attentionSize the size of the attention arrays * @property attentionOutputSize the size of the attention outputs * @property numOfHeads the number of self-attention heads * @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot) * @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot) */ class MultiHeadAttentionParameters( val inputSize: Int, val attentionSize: Int, val attentionOutputSize: Int, val numOfHeads: Int, weightsInitializer: Initializer? = GlorotInitializer(), biasesInitializer: Initializer? = GlorotInitializer() ) : Serializable { companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L } /** * The size of the output arrays. */ val outputSize: Int = this.inputSize /** * The parameters of the scaled-dot attention layers. */ val attention: List<ScaledDotAttentionLayerParameters> = List(this.numOfHeads) { ScaledDotAttentionLayerParameters( inputSize = this.inputSize, attentionSize = this.attentionSize, outputSize = this.attentionOutputSize, weightsInitializer = weightsInitializer, biasesInitializer = biasesInitializer) } /** * The parameters of the output merge network. */ val merge = StackedLayersParameters( LayerInterface(sizes = List(this.numOfHeads) { this.attentionOutputSize }), LayerInterface(size = this.outputSize, connectionType = LayerType.Connection.ConcatFeedforward), weightsInitializer = weightsInitializer, biasesInitializer = biasesInitializer ) }
mpl-2.0
453d6a22629d01919a07ef6583e816f2
36.527778
103
0.744264
4.69913
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/ConvertCallChainIntoSequenceInspection.kt
1
11058
// 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.inspections.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.psi.PsiWhiteSpace import com.intellij.ui.EditorTextField import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import java.awt.BorderLayout import javax.swing.JPanel class ConvertCallChainIntoSequenceInspection : AbstractKotlinInspection() { private val defaultCallChainLength = 5 private var callChainLength = defaultCallChainLength var callChainLengthText = defaultCallChainLength.toString() set(value) { field = value callChainLength = value.toIntOrNull() ?: defaultCallChainLength } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(expression) { val (qualified, firstCall, callChainLength) = expression.findCallChain() ?: return val rangeInElement = firstCall.calleeExpression?.textRange?.shiftRight(-qualified.startOffset) ?: return val highlightType = if (callChainLength >= this.callChainLength) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION holder.registerProblemWithoutOfflineInformation( qualified, KotlinBundle.message("call.chain.on.collection.could.be.converted.into.sequence.to.improve.performance"), isOnTheFly, highlightType, rangeInElement, ConvertCallChainIntoSequenceFix() ) }) override fun createOptionsPanel(): JPanel = OptionsPanel(this) private class OptionsPanel(owner: ConvertCallChainIntoSequenceInspection) : JPanel() { init { layout = BorderLayout() val regexField = EditorTextField(owner.callChainLengthText).apply { setOneLineMode(true) } regexField.document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { owner.callChainLengthText = regexField.text } }) val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("call.chain.length.to.transform"), BorderLayout.WEST) add(labeledComponent, BorderLayout.NORTH) } } } private class ConvertCallChainIntoSequenceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("convert.call.chain.into.sequence.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtQualifiedExpression ?: return val context = expression.analyze(BodyResolveMode.PARTIAL) val calls = expression.collectCallExpression(context).reversed() val firstCall = calls.firstOrNull() ?: return val lastCall = calls.lastOrNull() ?: return val first = firstCall.getQualifiedExpressionForSelector() ?: firstCall val last = lastCall.getQualifiedExpressionForSelector() ?: return val endWithTermination = lastCall.isTermination(context) val psiFactory = KtPsiFactory(expression) val dot = buildString { if (first is KtQualifiedExpression && first.receiverExpression.siblings().filterIsInstance<PsiWhiteSpace>().any { it.textContains('\n') } ) append("\n") if (first is KtSafeQualifiedExpression) append("?") append(".") } val firstCommentSaver = CommentSaver(first) val firstReplaced = first.replaced( psiFactory.buildExpression { if (first is KtQualifiedExpression) { appendExpression(first.receiverExpression) appendFixedText(dot) } appendExpression(psiFactory.createExpression("asSequence()")) appendFixedText(dot) appendExpression(firstCall) } ) firstCommentSaver.restore(firstReplaced) if (!endWithTermination) { val lastCommentSaver = CommentSaver(last) val lastReplaced = last.replace( psiFactory.buildExpression { appendExpression(last) appendFixedText(dot) appendExpression(psiFactory.createExpression("toList()")) } ) lastCommentSaver.restore(lastReplaced) } } } private data class CallChain( val qualified: KtQualifiedExpression, val firstCall: KtCallExpression, val callChainLength: Int ) private fun KtQualifiedExpression.findCallChain(): CallChain? { if (parent is KtQualifiedExpression) return null val context = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val calls = collectCallExpression(context) if (calls.isEmpty()) return null val lastCall = calls.last() val receiverType = lastCall.receiverType(context) if (receiverType?.isIterable(DefaultBuiltIns.Instance) != true) return null val firstCall = calls.first() val qualified = firstCall.getQualifiedExpressionForSelector() ?: firstCall.getQualifiedExpressionForReceiver() ?: return null return CallChain(qualified, lastCall, calls.size) } private fun KtQualifiedExpression.collectCallExpression(context: BindingContext): List<KtCallExpression> { val calls = mutableListOf<KtCallExpression>() fun collect(qualified: KtQualifiedExpression) { val call = qualified.callExpression ?: return calls.add(call) val receiver = qualified.receiverExpression if (receiver is KtCallExpression && receiver.implicitReceiver(context) != null) { calls.add(receiver) return } if (receiver is KtQualifiedExpression) collect(receiver) } collect(this) if (calls.size < 2) return emptyList() val transformationCalls = calls .asSequence() .dropWhile { !it.isTransformationOrTermination(context) } .takeWhile { it.isTransformationOrTermination(context) && !it.hasReturn() } .toList() .dropLastWhile { it.isLazyTermination(context) } if (transformationCalls.size < 2) return emptyList() return transformationCalls } private fun KtCallExpression.hasReturn(): Boolean = valueArguments.any { arg -> arg.anyDescendantOfType<KtReturnExpression> { it.labelQualifier == null } } private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean { val fqName = transformationAndTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isTermination(context: BindingContext): Boolean { val fqName = terminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isLazyTermination(context: BindingContext): Boolean { val fqName = lazyTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } internal val collectionTransformationFunctionNames = listOf( "chunked", "distinct", "distinctBy", "drop", "dropWhile", "filter", "filterIndexed", "filterIsInstance", "filterNot", "filterNotNull", "flatten", "map", "mapIndexed", "mapIndexedNotNull", "mapNotNull", "minus", "minusElement", "onEach", "onEachIndexed", "plus", "plusElement", "requireNoNulls", "sorted", "sortedBy", "sortedByDescending", "sortedDescending", "sortedWith", "take", "takeWhile", "windowed", "withIndex", "zipWithNext" ) @NonNls private val transformations = collectionTransformationFunctionNames.associateWith { FqName("kotlin.collections.$it") } internal val collectionTerminationFunctionNames = listOf( "all", "any", "asIterable", "asSequence", "associate", "associateBy", "associateByTo", "associateTo", "average", "contains", "count", "elementAt", "elementAtOrElse", "elementAtOrNull", "filterIndexedTo", "filterIsInstanceTo", "filterNotNullTo", "filterNotTo", "filterTo", "find", "findLast", "first", "firstNotNullOf", "firstNotNullOfOrNull", "firstOrNull", "fold", "foldIndexed", "groupBy", "groupByTo", "groupingBy", "indexOf", "indexOfFirst", "indexOfLast", "joinTo", "joinToString", "last", "lastIndexOf", "lastOrNull", "mapIndexedNotNullTo", "mapIndexedTo", "mapNotNullTo", "mapTo", "maxOrNull", "maxByOrNull", "maxWithOrNull", "maxOf", "maxOfOrNull", "maxOfWith", "maxOfWithOrNull", "minOrNull", "minByOrNull", "minWithOrNull", "minOf", "minOfOrNull", "minOfWith", "minOfWithOrNull", "none", "partition", "reduce", "reduceIndexed", "reduceIndexedOrNull", "reduceOrNull", "runningFold", "runningFoldIndexed", "runningReduce", "runningReduceIndexed", "scan", "scanIndexed", "single", "singleOrNull", "sum", "sumBy", "sumByDouble", "sumOf", "toCollection", "toHashSet", "toList", "toMutableList", "toMutableSet", "toSet", "toSortedSet", "unzip" ) @NonNls private val terminations = collectionTerminationFunctionNames.associateWith { val pkg = if (it in listOf("contains", "indexOf", "lastIndexOf")) "kotlin.collections.List" else "kotlin.collections" FqName("$pkg.$it") } private val lazyTerminations = terminations.filter { (key, _) -> key == "groupingBy" } private val transformationAndTerminations = transformations + terminations
apache-2.0
e51d3127b31aa782aeb6a1bc9e783c54
32.307229
158
0.685296
5.093505
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/settings/CodeVisionGroupSettingProvider.kt
4
2754
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.codeVision.settings import com.intellij.codeInsight.codeVision.CodeVisionBundle import com.intellij.codeInsight.codeVision.CodeVisionProvider import com.intellij.codeInsight.codeVision.CodeVisionProviderFactory import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls interface CodeVisionGroupSettingProvider { /** * Group id settings refer to. @see [CodeVisionProvider.groupId] */ val groupId: String /** * Name that is shown in settings */ @get:Nls val groupName: String get() = CodeVisionBundle.message("codeLens.${groupId}.name") @get:Nls val description: String get() = CodeVisionBundle.message("codeLens.${groupId}.description") fun createModel(project: Project): CodeVisionGroupSettingModel { val providers = CodeVisionProviderFactory.createAllProviders(project).filter { it.groupId == groupId } val settings = CodeVisionSettings.instance() val isEnabled = settings.codeVisionEnabled && settings.isProviderEnabled(groupId) return createSettingsModel(isEnabled, providers) } fun createSettingsModel(isEnabled: Boolean, providers: List<CodeVisionProvider<*>>): CodeVisionGroupSettingModel { return CodeVisionGroupDefaultSettingModel(groupName, groupId, description, isEnabled, providers) } object EP { val EXTENSION_POINT_NAME: ExtensionPointName<CodeVisionGroupSettingProvider> = ExtensionPointName.create<CodeVisionGroupSettingProvider>("com.intellij.config.codeVisionGroupSettingProvider") fun findGroupModels(): List<CodeVisionGroupSettingProvider> { val extensions = EXTENSION_POINT_NAME.extensions val distinctExtensions = extensions.distinctBy { it.groupId } if (extensions.size != distinctExtensions.size) logger<CodeVisionGroupSettingProvider>().error("Multiple CodeLensGroupSettingProvider with same groupId are registered") return distinctExtensions } /** * Find all registered [CodeVisionProvider] without [CodeVisionGroupSettingProvider] */ fun findSingleModels(project: Project): List<CodeVisionGroupSettingProvider> { val registeredGroupIds = EXTENSION_POINT_NAME.extensions.distinctBy { it.groupId }.map { it.groupId } val providersWithoutGroup = CodeVisionProviderFactory.createAllProviders(project).filter { registeredGroupIds.contains(it.groupId).not() } return providersWithoutGroup.map { CodeVisionUngroppedSettingProvider(it.groupId) } } } }
apache-2.0
d3b9858d4636ea6ba1d77247fab43172
43.435484
158
0.78032
4.865724
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinBlock.kt
4
5352
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.formatter import com.intellij.formatting.* import com.intellij.formatting.alignment.AlignmentStrategy import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.FormatterUtil import com.intellij.psi.formatter.common.AbstractBlock import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.KtNodeTypes.WHEN_ENTRY import org.jetbrains.kotlin.lexer.KtTokens.ARROW /** * @see Block for good JavaDoc documentation */ class KotlinBlock( node: ASTNode, private val myAlignmentStrategy: CommonAlignmentStrategy, private val myIndent: Indent?, wrap: Wrap?, mySettings: CodeStyleSettings, private val mySpacingBuilder: KotlinSpacingBuilder, overrideChildren: Sequence<ASTNode>? = null ) : AbstractBlock(node, wrap, myAlignmentStrategy.getAlignment(node)) { private val kotlinDelegationBlock = object : KotlinCommonBlock( node, mySettings, mySpacingBuilder, myAlignmentStrategy, overrideChildren ) { override fun getNullAlignmentStrategy(): CommonAlignmentStrategy = NodeAlignmentStrategy.getNullStrategy() override fun createAlignmentStrategy(alignOption: Boolean, defaultAlignment: Alignment?): CommonAlignmentStrategy { return NodeAlignmentStrategy.fromTypes(AlignmentStrategy.wrap(createAlignment(alignOption, defaultAlignment))) } override fun getAlignmentForCaseBranch(shouldAlignInColumns: Boolean): CommonAlignmentStrategy { return if (shouldAlignInColumns) { NodeAlignmentStrategy.fromTypes( AlignmentStrategy.createAlignmentPerTypeStrategy(listOf(ARROW as IElementType), WHEN_ENTRY, true) ) } else { NodeAlignmentStrategy.getNullStrategy() } } override fun getAlignment(): Alignment? = alignment override fun isIncompleteInSuper(): Boolean = [email protected]() override fun getSuperChildAttributes(newChildIndex: Int): ChildAttributes = [email protected](newChildIndex) override fun getSubBlocks(): List<Block> = subBlocks override fun createBlock( node: ASTNode, alignmentStrategy: CommonAlignmentStrategy, indent: Indent?, wrap: Wrap?, settings: CodeStyleSettings, spacingBuilder: KotlinSpacingBuilder, overrideChildren: Sequence<ASTNode>? ): ASTBlock { return KotlinBlock( node, alignmentStrategy, indent, wrap, mySettings, mySpacingBuilder, overrideChildren ) } override fun createSyntheticSpacingNodeBlock(node: ASTNode): ASTBlock { return object : AbstractBlock(node, null, null) { override fun isLeaf(): Boolean = false override fun getSpacing(child1: Block?, child2: Block): Spacing? = null override fun buildChildren(): List<Block> = emptyList() } } } override fun getIndent(): Indent? = myIndent override fun buildChildren(): List<Block> = kotlinDelegationBlock.buildChildren() override fun getSpacing(child1: Block?, child2: Block): Spacing? = mySpacingBuilder.getSpacing(this, child1, child2) override fun getChildAttributes(newChildIndex: Int): ChildAttributes = kotlinDelegationBlock.getChildAttributes(newChildIndex) override fun isLeaf(): Boolean = kotlinDelegationBlock.isLeaf() override fun getTextRange() = kotlinDelegationBlock.getTextRange() override fun isIncomplete(): Boolean = kotlinDelegationBlock.isIncomplete() } object KotlinSpacingBuilderUtilImpl : KotlinSpacingBuilderUtil { override fun getPreviousNonWhitespaceLeaf(node: ASTNode?): ASTNode? { return FormatterUtil.getPreviousNonWhitespaceLeaf(node) } override fun isWhitespaceOrEmpty(node: ASTNode?): Boolean { return FormatterUtil.isWhitespaceOrEmpty(node) } override fun createLineFeedDependentSpacing( minSpaces: Int, maxSpaces: Int, minimumLineFeeds: Int, keepLineBreaks: Boolean, keepBlankLines: Int, dependency: TextRange, rule: DependentSpacingRule ): Spacing { return object : DependantSpacingImpl(minSpaces, maxSpaces, dependency, keepLineBreaks, keepBlankLines, rule) { override fun getMinLineFeeds(): Int { val superMin = super.getMinLineFeeds() return if (superMin == 0) minimumLineFeeds else superMin } } } } private fun createAlignment(alignOption: Boolean, defaultAlignment: Alignment?): Alignment? { return if (alignOption) createAlignmentOrDefault(null, defaultAlignment) else defaultAlignment } private fun createAlignmentOrDefault(base: Alignment?, defaultAlignment: Alignment?): Alignment? { return defaultAlignment ?: if (base == null) Alignment.createAlignment() else Alignment.createChildAlignment(base) }
apache-2.0
7f97fb8249a579aa1f2b121df7bf8d01
39.24812
158
0.701046
5.211295
false
false
false
false
jk1/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/sam/ClosureToSamConverter.kt
1
1666
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.sam import com.intellij.psi.PsiClassType import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.ConversionResult import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.ApplicableTo.* import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE class ClosureToSamConverter : GrTypeConverter() { private val myPositions = setOf(ASSIGNMENT, RETURN_VALUE, METHOD_PARAMETER) override fun isApplicableTo(position: ApplicableTo): Boolean = position in myPositions override fun isConvertibleEx(targetType: PsiType, actualType: PsiType, context: GroovyPsiElement, currentPosition: ApplicableTo): ConversionResult? { if (targetType !is PsiClassType || (actualType !is GrClosureType && !actualType.equalsToText(GROOVY_LANG_CLOSURE))) return null if (!isSamConversionAllowed(context)) return null val result = targetType.resolveGenerics() val targetClass = result.element ?: return null val targetFqn = targetClass.qualifiedName ?: return null // anonymous classes has no fqn if (targetFqn == GROOVY_LANG_CLOSURE) return null findSingleAbstractSignature(targetClass) ?: return null return ConversionResult.OK } }
apache-2.0
d171b86024f6c0108f99e6088f7d473f
49.484848
140
0.788115
4.527174
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-plugins/ktor-client-json/common/test/KotlinxSerializerTest.kt
1
4035
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.json import io.ktor.client.call.* import io.ktor.client.plugins.* import io.ktor.client.plugins.kotlinx.serializer.* import io.ktor.client.request.* import io.ktor.client.request.forms.* import io.ktor.client.tests.utils.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.utils.io.core.* import kotlinx.serialization.* import kotlin.test.* @Serializable internal data class User(val id: Long, val login: String) @Serializable internal data class Photo(val id: Long, val path: String) @Suppress("DEPRECATION") class KotlinxSerializerTest : ClientLoader() { @Test fun testRegisterCustom() { val serializer = KotlinxSerializer() val user = User(1, "vasya") val actual = serializer.testWrite(user) assertEquals("{\"id\":1,\"login\":\"vasya\"}", actual) } @Test fun testRegisterCustomList() { val serializer = KotlinxSerializer() val user = User(2, "petya") val photo = Photo(3, "petya.jpg") assertEquals("[{\"id\":2,\"login\":\"petya\"}]", serializer.testWrite(listOf(user))) assertEquals("[{\"id\":3,\"path\":\"petya.jpg\"}]", serializer.testWrite(listOf(photo))) } @Test fun testCustomFormBody() = clientTests { config { expectSuccess = true install(JsonPlugin) } val data = { formData { append("name", "hello") append("content") { writeText("123456789") } append("file", "urlencoded_name.jpg") { for (i in 1..4096) { writeByte(i.toByte()) } } append("hello", 5) } } test { client -> var throwed = false try { client.submitFormWithBinaryData(url = "upload", formData = data()).body<String>() } catch (cause: Throwable) { throwed = true } assertTrue(throwed, "Connection exception expected.") } } @Test fun testStringWithJsonPlugin() = clientTests { config { install(JsonPlugin) { removeIgnoredType<String>() } defaultRequest { val contentType = ContentType.parse("application/vnd.string+json") accept(contentType) contentType(contentType) } } test { client -> val response = client.post("$TEST_SERVER/echo-with-content-type") { setBody("Hello") }.body<String>() assertEquals("Hello", response) val textResponse = client.post("$TEST_SERVER/echo") { setBody("Hello") }.body<String>() assertEquals("\"Hello\"", textResponse) val emptyResponse = client.post("$TEST_SERVER/echo").body<String>() assertEquals("", emptyResponse) } } @Test fun testMultipleListSerializersWithClient() = clientTests { val testSerializer = KotlinxSerializer() config { install(JsonPlugin) { serializer = testSerializer } defaultRequest { accept(ContentType.Application.Json) } } test { client -> val users = client.get("$TEST_SERVER/json/users").body<List<User>>() val photos = client.get("$TEST_SERVER/json/photos").body<List<Photo>>() assertEquals(listOf(User(42, "TestLogin")), users) assertEquals(listOf(Photo(4242, "cat.jpg")), photos) } } private fun JsonSerializer.testWrite(data: Any): String = (write(data, ContentType.Application.Json) as? TextContent)?.text ?: error("Failed to get serialized $data") }
apache-2.0
3b6ea207c43c0bbf15dd4c8154c5b93d
29.11194
119
0.55539
4.569649
false
true
false
false
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/propertyelement/constructor/PropertyItemConstructor.kt
1
3564
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.propertyelement.constructor import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml import com.tickaroo.tikxml.annotationprocessing.DateConverter import java.util.Date /** * @author Hannes Dorfmann */ @Xml(name = "item") class PropertyItemConstructor( @param:PropertyElement val aString: String?, @param:PropertyElement val anInt: Int, @param:PropertyElement val aBoolean: Boolean, @param:PropertyElement val aDouble: Double, @param:PropertyElement val aLong: Long, @param:PropertyElement(converter = DateConverter::class) val aDate: Date?, @param:PropertyElement val intWrapper: Int?, @param:PropertyElement val booleanWrapper: Boolean?, @param:PropertyElement val doubleWrapper: Double?, @param:PropertyElement val longWrapper: Long? ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PropertyItemConstructor) return false val that = other as PropertyItemConstructor? if (anInt != that!!.anInt) return false if (aBoolean != that.aBoolean) return false if (java.lang.Double.compare(that.aDouble, aDouble) != 0) return false if (aLong != that.aLong) return false if (if (aString != null) aString != that.aString else that.aString != null) return false if (if (aDate != null) aDate != that.aDate else that.aDate != null) return false if (if (intWrapper != null) intWrapper != that.intWrapper else that.intWrapper != null) { return false } if (if (booleanWrapper != null) booleanWrapper != that.booleanWrapper else that.booleanWrapper != null) { return false } if (if (doubleWrapper != null) doubleWrapper != that.doubleWrapper else that.doubleWrapper != null) { return false } return if (longWrapper != null) longWrapper == that.longWrapper else that.longWrapper == null } override fun hashCode(): Int { var result: Int val temp: Long result = aString?.hashCode() ?: 0 result = 31 * result + anInt result = 31 * result + if (aBoolean) 1 else 0 temp = java.lang.Double.doubleToLongBits(aDouble) result = 31 * result + (temp xor temp.ushr(32)).toInt() result = 31 * result + (aLong xor aLong.ushr(32)).toInt() result = 31 * result + (aDate?.hashCode() ?: 0) result = 31 * result + (intWrapper?.hashCode() ?: 0) result = 31 * result + (booleanWrapper?.hashCode() ?: 0) result = 31 * result + (doubleWrapper?.hashCode() ?: 0) result = 31 * result + (longWrapper?.hashCode() ?: 0) return result } }
apache-2.0
f0e8691f9245d96ebc3acca8125b3c63
39.044944
101
0.638328
4.460576
false
false
false
false
Talentica/AndroidWithKotlin
app/src/main/java/com/talentica/androidkotlin/ui/CommentAdapter.kt
1
3820
/* * Copyright 2017, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.talentica.androidkotlin.ui import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.talentica.androidkotlin.R import com.talentica.androidkotlin.databinding.CommentItemBinding import com.talentica.androidkotlin.db.entity.CommentEntity import com.talentica.androidkotlin.ui.CommentAdapter.CommentViewHolder class CommentAdapter(private val mCommentClickCallback: CommentClickCallback?) : RecyclerView.Adapter<CommentViewHolder>() { private var mCommentList: List<CommentEntity?>? = null fun setCommentList(comments: List<CommentEntity?>?) { if (mCommentList == null) { mCommentList = comments if (comments != null) { notifyItemRangeInserted(0, comments.size) } } else { val diffResult = DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun getOldListSize(): Int { return mCommentList!!.size } override fun getNewListSize(): Int { return comments?.size ?: 0 } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val old = mCommentList!![oldItemPosition] val comment = comments?.get(newItemPosition) return if (old != null && comment != null) { old.id == comment.id } else { false } } override fun areContentsTheSame( oldItemPosition: Int, newItemPosition: Int ): Boolean { val old = mCommentList!![oldItemPosition] val comment = comments?.get(newItemPosition) return if (old != null && comment != null) { old.id == comment.id && old.postedAt === comment.postedAt && old.productId == comment.productId && old.text == comment.text } else { false } } }) mCommentList = comments diffResult.dispatchUpdatesTo(this) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentViewHolder { val binding: CommentItemBinding = DataBindingUtil .inflate( LayoutInflater.from(parent.context), R.layout.comment_item, parent, false ) binding.callback = mCommentClickCallback return CommentViewHolder(binding) } override fun onBindViewHolder(holder: CommentViewHolder, position: Int) { holder.binding.comment = mCommentList!![position] holder.binding.executePendingBindings() } override fun getItemCount(): Int { return if (mCommentList == null) 0 else mCommentList!!.size } class CommentViewHolder(val binding: CommentItemBinding) : RecyclerView.ViewHolder( binding.root ) }
apache-2.0
b63929a150b143f2dbf446316f0f7f69
38.391753
147
0.615969
5.433855
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/util/FileUtil.kt
1
1808
package org.wikipedia.util import android.graphics.Bitmap import java.io.* object FileUtil { private const val JPEG_QUALITY = 85 @JvmStatic fun writeToFile(bytes: ByteArrayOutputStream, destinationFile: File): File { val fo = FileOutputStream(destinationFile) try { fo.write(bytes.toByteArray()) } finally { fo.flush() fo.close() } return destinationFile } @JvmStatic fun compressBmpToJpg(bitmap: Bitmap): ByteArrayOutputStream { val bytes = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, bytes) return bytes } @JvmStatic fun readFile(inputStream: InputStream?): String { BufferedReader(InputStreamReader(inputStream)).use { reader -> val stringBuilder = StringBuilder() var readStr: String? while (reader.readLine().also { readStr = it } != null) { stringBuilder.append(readStr).append('\n') } return stringBuilder.toString() } } @JvmStatic fun deleteRecursively(f: File) { if (f.isDirectory) { f.listFiles()?.forEach { deleteRecursively(it) } } f.delete() } @JvmStatic fun sanitizeFileName(fileName: String): String { return fileName.replace("[:\\\\/*\"?|<>']".toRegex(), "_") } @JvmStatic fun isVideo(mimeType: String): Boolean { return mimeType.contains("ogg") || mimeType.contains("video") } @JvmStatic fun isAudio(mimeType: String): Boolean { return mimeType.contains("audio") } @JvmStatic fun isImage(mimeType: String): Boolean { return mimeType.contains("image") } }
apache-2.0
7ae76087b58348e2e02f6d85b22953e7
25.202899
80
0.587389
4.860215
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/relationship/internal/RelationshipHandlerShould.kt
1
7568
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.relationship.internal import com.nhaarman.mockitokotlin2.* import org.hisp.dhis.android.core.arch.db.stores.internal.StoreWithState import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.common.ObjectWithUid import org.hisp.dhis.android.core.relationship.Relationship import org.hisp.dhis.android.core.relationship.RelationshipConstraintType import org.hisp.dhis.android.core.relationship.RelationshipHelper import org.hisp.dhis.android.core.relationship.RelationshipItem import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class RelationshipHandlerShould { private val relationshipStore: RelationshipStore = mock() private val relationshipItemStore: RelationshipItemStore = mock() private val relationshipItemHandler: Handler<RelationshipItem> = mock() private val storeSelector: RelationshipItemElementStoreSelector = mock() private val itemElementStore: StoreWithState<*> = mock() private val NEW_UID = "new-uid" private val TEI_3_UID = "tei3" private val TEI_4_UID = "tei4" private val tei3Item: RelationshipItem = RelationshipHelper.teiItem(TEI_3_UID) private val tei4Item: RelationshipItem = RelationshipHelper.teiItem(TEI_4_UID) private val existingRelationship: Relationship = RelationshipSamples.get230() private val existingRelationshipWithNewUid: Relationship = RelationshipSamples.get230().toBuilder().uid(NEW_UID).build() private val newRelationship: Relationship = RelationshipSamples.get230(NEW_UID, TEI_3_UID, TEI_4_UID) // object to test private lateinit var relationshipHandler: RelationshipHandlerImpl @Before fun setUp() { relationshipHandler = RelationshipHandlerImpl( relationshipStore, relationshipItemStore, relationshipItemHandler, storeSelector ) whenever(storeSelector.getElementStore(any())).thenReturn(itemElementStore) whenever(itemElementStore.exists(RelationshipSamples.FROM_UID)).thenReturn(true) whenever(itemElementStore.exists(RelationshipSamples.TO_UID)).thenReturn(true) whenever(itemElementStore.exists(TEI_3_UID)).thenReturn(true) whenever(itemElementStore.exists(TEI_4_UID)).thenReturn(true) whenever( relationshipItemStore.getRelationshipUidsForItems( RelationshipSamples.fromItem, RelationshipSamples.toItem ) ).thenReturn(listOf(RelationshipSamples.UID)) whenever(relationshipItemStore.getRelationshipUidsForItems(tei3Item, tei4Item)).thenReturn(emptyList()) whenever(relationshipStore.selectByUid(RelationshipSamples.UID)).thenReturn(RelationshipSamples.get230()) whenever(relationshipStore.updateOrInsert(any())).thenReturn(HandleAction.Insert) } @Test fun not_delete_relationship_if_existing_id_matches() { relationshipHandler.handle(existingRelationship) verify(relationshipStore, never()).delete(RelationshipSamples.UID) } @Test fun not_call_delete_if_no_existing_relationship() { relationshipHandler.handle(newRelationship) verify(relationshipStore, never()).delete(RelationshipSamples.UID) } @Test fun update_relationship_store_for_existing_relationship() { relationshipHandler.handle(existingRelationship) verify(relationshipStore).updateOrInsert(existingRelationship) } @Test fun update_relationship_store_for_existing_relationship_with_new_uid() { relationshipHandler.handle(existingRelationshipWithNewUid) verify(relationshipStore).updateOrInsert(existingRelationshipWithNewUid) } @Test fun update_relationship_store_for_new_relationship() { relationshipHandler.handle(newRelationship) verify(relationshipStore).updateOrInsert(newRelationship) } @Test fun update_relationship_handler_store_for_existing_relationship() { relationshipHandler.handle(existingRelationship) verify(relationshipItemHandler).handle( RelationshipSamples.fromItem.toBuilder().relationship(ObjectWithUid.create(existingRelationship.uid())) .relationshipItemType(RelationshipConstraintType.FROM).build() ) verify(relationshipItemHandler).handle( RelationshipSamples.toItem.toBuilder().relationship(ObjectWithUid.create(existingRelationship.uid())) .relationshipItemType(RelationshipConstraintType.TO).build() ) } @Test fun update_relationship_item_handler_for_existing_relationship_with_new_uid() { relationshipHandler.handle(existingRelationshipWithNewUid) verify(relationshipItemHandler).handle( RelationshipSamples.fromItem.toBuilder() .relationship(ObjectWithUid.create(existingRelationshipWithNewUid.uid())) .relationshipItemType(RelationshipConstraintType.FROM).build() ) verify(relationshipItemHandler).handle( RelationshipSamples.toItem.toBuilder() .relationship(ObjectWithUid.create(existingRelationshipWithNewUid.uid())) .relationshipItemType(RelationshipConstraintType.TO).build() ) } @Test fun update_relationship_item_handler_for_new_relationship() { relationshipHandler.handle(newRelationship) verify(relationshipItemHandler).handle( tei3Item.toBuilder().relationship(ObjectWithUid.create(newRelationship.uid())) .relationshipItemType(RelationshipConstraintType.FROM).build() ) verify(relationshipItemHandler).handle( tei4Item.toBuilder().relationship(ObjectWithUid.create(newRelationship.uid())) .relationshipItemType(RelationshipConstraintType.TO).build() ) } }
bsd-3-clause
97b31830951cd86e931a534a261d7e54
46.3
115
0.745904
4.741855
false
true
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/TrackerPostStateManager.kt
1
5200
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.internal import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableDataObjectStore import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.enrollment.EnrollmentInternalAccessor import org.hisp.dhis.android.core.enrollment.internal.EnrollmentStore import org.hisp.dhis.android.core.event.Event import org.hisp.dhis.android.core.event.internal.EventStore import org.hisp.dhis.android.core.fileresource.FileResource import org.hisp.dhis.android.core.relationship.Relationship import org.hisp.dhis.android.core.relationship.internal.RelationshipStore import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceInternalAccessor @Reusable internal class TrackerPostStateManager @Inject internal constructor( private val trackedEntityInstanceStore: TrackedEntityInstanceStore, private val enrollmentStore: EnrollmentStore, private val eventStore: EventStore, private val relationshipStore: RelationshipStore, private val fileResourceStore: IdentifiableDataObjectStore<FileResource>, private val h: StatePersistorHelper ) { fun restorePayloadStates( trackedEntityInstances: List<TrackedEntityInstance> = emptyList(), events: List<Event> = emptyList(), relationships: List<Relationship> = emptyList(), fileResources: List<String> = emptyList() ) { setPayloadStates(trackedEntityInstances, events, relationships, fileResources, null) } @Suppress("NestedBlockDepth") fun setPayloadStates( trackedEntityInstances: List<TrackedEntityInstance> = emptyList(), events: List<Event> = emptyList(), relationships: List<Relationship> = emptyList(), fileResources: List<String> = emptyList(), forcedState: State? ) { val teiMap: MutableMap<State, MutableList<String>> = mutableMapOf() val enrollmentMap: MutableMap<State, MutableList<String>> = mutableMapOf() val eventMap: MutableMap<State, MutableList<String>> = mutableMapOf() val relationshipMap: MutableMap<State, MutableList<String>> = mutableMapOf() val fileResourceMap: MutableMap<State, MutableList<String>> = mutableMapOf() trackedEntityInstances.forEach { instance -> h.addState(teiMap, instance, forcedState) TrackedEntityInstanceInternalAccessor.accessEnrollments(instance)?.forEach { enrollment -> h.addState(enrollmentMap, enrollment, forcedState) for (event in EnrollmentInternalAccessor.accessEvents(enrollment)) { h.addState(eventMap, event, forcedState) } } TrackedEntityInstanceInternalAccessor.accessRelationships(instance)?.forEach { r -> h.addState(relationshipMap, r, forcedState) } } events.forEach { h.addState(eventMap, it, forcedState) } relationships.forEach { h.addState(relationshipMap, it, forcedState) } fileResources.forEach { fileResource -> fileResourceStore.selectByUid(fileResource)?.let { h.addState(fileResourceMap, it, forcedState) } } h.persistStates(teiMap, trackedEntityInstanceStore) h.persistStates(enrollmentMap, enrollmentStore) h.persistStates(eventMap, eventStore) h.persistStates(relationshipMap, relationshipStore) h.persistStates(fileResourceMap, fileResourceStore) } }
bsd-3-clause
0494bf338620e56c4dbc8f174b2cd4fd
48.056604
102
0.740192
4.919584
false
false
false
false
theapache64/Mock-API
src/com/theah64/mock_api/utils/HeaderSecurity.kt
1
1429
package com.theah64.mock_api.utils import com.theah64.mock_api.database.Projects /** * Created by shifar on 31/12/15. */ class HeaderSecurity @Throws(AuthorizationException::class) constructor(private val authorization: String?) { lateinit var projectId: String private set val failureReason: String get() = if (this.authorization == null) REASON_API_KEY_MISSING else REASON_INVALID_API_KEY init { isAuthorized() }//Collecting header from passed request /** * Used to identify if passed API-KEY has a valid victim. */ @Throws(AuthorizationException::class) private fun isAuthorized() { if (this.authorization == null) { //No api key passed along with request throw AuthorizationException("Unauthorized access") } Projects.instance.get(Projects.COLUMN_API_KEY, this.authorization, Projects.COLUMN_ID, true).let { projectId -> if (projectId == null) { throw AuthorizationException("Invalid API KEY: " + this.authorization) } this.projectId = projectId } } inner class AuthorizationException(message: String) : Exception(message) companion object { val KEY_AUTHORIZATION = "Authorization" private val REASON_API_KEY_MISSING = "API key is missing" private val REASON_INVALID_API_KEY = "Invalid API key" } }
apache-2.0
91e1808359f547e83353192f01cb7c0c
27.019608
119
0.650805
4.580128
false
false
false
false
intellij-solidity/intellij-solidity
src/main/kotlin/me/serce/solidity/ide/errors.kt
1
3377
package me.serce.solidity.ide import com.intellij.diagnostic.IdeaReportingEvent import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.diagnostic.ErrorReportSubmitter import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.SubmittedReportInfo import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus.FAILED import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus.NEW_ISSUE import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.SystemInfo import com.intellij.util.Consumer import io.sentry.DefaultSentryClientFactory import io.sentry.Sentry import io.sentry.connection.ConnectionException import io.sentry.event.Event import io.sentry.event.EventBuilder import io.sentry.event.interfaces.ExceptionInterface import java.awt.Component class SentryReportSubmitter : ErrorReportSubmitter() { init { // IntelliJ Solidity N val dsn = "https://4cf4758bb74b408a82c9c4f200b63837:[email protected]/301677" + "?${DefaultSentryClientFactory.UNCAUGHT_HANDLER_ENABLED_OPTION}=false" Sentry.init(dsn) } private val pluginVersion = PluginManagerCore.getPlugin(PluginId.getId("me.serce.solidity"))?.version ?: "unknown" override fun getReportActionText() = "Submit error to IntelliJ Solidity maintainers" override fun submit( events: Array<out IdeaLoggingEvent>, additionalInfo: String?, parentComponent: Component, consumer: Consumer<in SubmittedReportInfo> ): Boolean { val ijEvent = events.firstOrNull() if (ijEvent == null) { return true } if (pluginVersion.endsWith("-SNAPSHOT")) { // do not report errors from dev-versions. If someone uses a dev version, he will // be able to report the issue and all related info as a github issue or even fix it. consumer.consume(SubmittedReportInfo(null, "Error submission is disabled in dev versions", FAILED)) return false } val eventBuilder = EventBuilder() .withMessage(ijEvent.message) .withLevel(Event.Level.ERROR) .withTag("build", ApplicationInfo.getInstance().build.asString()) .withTag("plugin_version", pluginVersion) .withTag("os", SystemInfo.OS_NAME) .withTag("os_version", SystemInfo.OS_VERSION) .withTag("os_arch", SystemInfo.OS_ARCH) .withTag("java_version", SystemInfo.JAVA_VERSION) .withTag("java_runtime_version", SystemInfo.JAVA_RUNTIME_VERSION) val error = when (ijEvent) { is IdeaReportingEvent -> ijEvent.data.throwable else -> ijEvent.throwable } if (error != null) { eventBuilder.withSentryInterface(ExceptionInterface(error)) } if (additionalInfo != null) { eventBuilder.withExtra("additional_info", additionalInfo) } if (events.size > 1) { eventBuilder.withExtra("extra_events", events.drop(1).joinToString("\n") { it.toString() }) } return try { Sentry.capture(eventBuilder) consumer.consume(SubmittedReportInfo(null, "Error has been successfully reported", NEW_ISSUE)) true } catch (e: ConnectionException) { // sentry is temporarily unavailable consumer.consume(SubmittedReportInfo(null, "Error submission has failed", FAILED)) false } } }
mit
07c6777ce47da55366bd432dcf7f34f5
38.729412
116
0.743263
4.280101
false
false
false
false
ilya-g/intellij-markdown
src/org/intellij/markdown/parser/markerblocks/providers/SetextHeaderProvider.kt
2
2103
package org.intellij.markdown.parser.markerblocks.providers import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider import org.intellij.markdown.parser.markerblocks.impl.SetextHeaderMarkerBlock import kotlin.text.Regex public class SetextHeaderProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> { override fun createMarkerBlocks(pos: LookaheadText.Position, productionHolder: ProductionHolder, stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> { if (stateInfo.paragraphBlock != null) { return emptyList() } val currentConstaints = stateInfo.currentConstraints if (stateInfo.nextConstraints != currentConstaints) { return emptyList() } if (MarkerBlockProvider.isStartOfLineWithConstraints(pos, currentConstaints) && getNextLineFromConstraints(pos, currentConstaints)?.let { REGEX.matches(it) } == true) { return listOf(SetextHeaderMarkerBlock(currentConstaints, productionHolder)) } else { return emptyList() } } override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean { return false } private fun getNextLineFromConstraints(pos: LookaheadText.Position, constraints: MarkdownConstraints): CharSequence? { val line = pos.nextLine ?: return null val nextLineConstraints = MarkdownConstraints.fillFromPrevious(line, 0, constraints) if (nextLineConstraints.extendsPrev(constraints)) { return nextLineConstraints.eatItselfFromString(line) } else { return null } } companion object { val REGEX: Regex = Regex("^ {0,3}(\\-+|=+) *$") } }
apache-2.0
de55f53d8c17c4a32a8ee084c5324975
42.833333
122
0.704708
5.205446
false
false
false
false
Madrapps/Pikolo
pikolo/src/main/java/com/madrapps/pikolo/components/hsl/SaturationComponent.kt
1
881
package com.madrapps.pikolo.components.hsl import androidx.core.graphics.ColorUtils import com.madrapps.pikolo.Metrics import com.madrapps.pikolo.Paints import com.madrapps.pikolo.components.ArcComponent internal class SaturationComponent(metrics: Metrics, paints: Paints, arcLength: Float, arcStartAngle: Float) : ArcComponent(metrics, paints, arcLength, arcStartAngle) { override val componentIndex: Int = 1 override val range: Float = 1f override val noOfColors = 11 // TODO 2 should be sufficient override val colors = IntArray(noOfColors) override val colorPosition = FloatArray(noOfColors) override fun getColorArray(color: FloatArray): IntArray { for (i in 0 until noOfColors) { color[componentIndex] = i.toFloat() / (noOfColors - 1) colors[i] = ColorUtils.HSLToColor(color) } return colors } }
apache-2.0
8e8822c12d1477756a705d2cdd2649f5
37.347826
168
0.728717
3.89823
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/Functions.kt
2
15823
package rhmodding.tickompiler import rhmodding.tickompiler.compiler.FunctionCall import rhmodding.tickompiler.decompiler.CommentType import rhmodding.tickompiler.decompiler.DecompilerState import java.util.* import kotlin.math.abs @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class DeprecatedFunction(val value: String) abstract class Functions { val opcode = OpcodeFunction() val bytecode = BytecodeFunction() abstract val allFunctions: MutableList<Function> val byName: MutableMap<String, Function> get() = allFunctions.associateBy { it.name }.toMutableMap() operator fun get(op: Long): Function { allFunctions.forEach { if (it.acceptOp(op)) return@get it } return opcode } operator fun set(op: Long, alias: String) { val f = op alias alias allFunctions.add(f) } private fun isNumeric(input: String): Boolean { return input.toIntOrNull() != null } operator fun get(key: String): Function { return if (key.startsWith("0x") or isNumeric(key)) { opcode } else { byName[key] ?: throw MissingFunctionError("Failed to find function $key") } } protected fun alias(opcode: Long, alias: String, argsNeeded: IntRange, indentChange: Int = 0, currentAdjust: Int = 0): AliasedFunction { return AliasedFunction(opcode, alias, argsNeeded, indentChange, currentAdjust) } /** * Assumes 0..0b1111 for args needed. */ protected infix fun Long.alias(alias: String): AliasedFunction { return alias(this, alias, 0..0b1111) } } fun createInts(opcode: Long, special: Long, args: LongArray?): LongArray { if (args == null) return longArrayOf(opcode) if (args.size > 0b1111) throw IllegalArgumentException("Args size cannot be more than ${0b1111}") val firstLong: Long = opcode or ((args.size.toLong() and 0b1111) shl 10) or ((special and 0b111111111111111111) shl 14) return longArrayOf(firstLong, *args) } object MegamixFunctions : Functions() { override val allFunctions = mutableListOf( opcode, bytecode, BytesFunction(), RestFunction(0xE), SpecialOnlyFunction(0x12, "unrest"), SpecialOnlyFunction(0x14, "label"), SpecialOnlyFunction(0x15, "goto"), SpecialOnlyFunction(0x1A, "case", indentChange = 1), SpecialOnlyFunction(0xB8, "random"), SpecificSpecialFunction(0x1, 0, "get_async", 2..2), SpecificSpecialFunction(0x1, 1, "set_func", 2..2), SpecificSpecialFunction(0x3, 0, "kill_all", 0..0), SpecificSpecialFunction(0x3, 1, "kill_cat", 1..1), SpecificSpecialFunction(0x3, 2, "kill_loc", 1..1), SpecificSpecialFunction(0x3, 3, "kill_sub", 1..1), SpecificSpecialFunction(0xF, 0, "getrest", 1..1), SpecificSpecialFunction(0xF, 1, "setrest", 2..2), SpecificSpecialFunction(0x16, 0, "if", 1..1, 1), SpecificSpecialFunction(0x16, 1, "if_neq", 1..1, 1), SpecificSpecialFunction(0x16, 2, "if_lt", 1..1, 1), SpecificSpecialFunction(0x16, 3, "if_leq", 1..1, 1), SpecificSpecialFunction(0x16, 4, "if_gt", 1..1, 1), SpecificSpecialFunction(0x16, 5, "if_geq", 1..1, 1), SpecificSpecialFunction(0x1E, 0, "set_countdown", 1..1), SpecificSpecialFunction(0x1E, 1, "set_countdown_condvar", 0..0), SpecificSpecialFunction(0x1E, 2, "get_countdown_init", 0..0), SpecificSpecialFunction(0x1E, 3, "get_countdown_prog", 0..0), SpecificSpecialFunction(0x1E, 4, "get_countdown", 0..0), SpecificSpecialFunction(0x1E, 5, "dec_countdown", 0..0), SpecificSpecialFunction(0x2A, 0, "game_model", 2..2), SpecificSpecialFunction(0x2A, 2, "game_cellanim", 2..2), SpecificSpecialFunction(0x2A, 3, "game_effect", 2..2), SpecificSpecialFunction(0x2A, 4, "game_layout", 2..2), SpecificSpecialFunction(0x31, 0, "set_model", 3..3), SpecificSpecialFunction(0x31, 1, "remove_model", 1..1), SpecificSpecialFunction(0x31, 2, "has_model", 1..1), SpecificSpecialFunction(0x35, 0, "set_cellanim", 3..3), SpecificSpecialFunction(0x35, 1, "cellanim_busy", 1..1), SpecificSpecialFunction(0x35, 3, "remove_cellanim", 1..1), SpecificSpecialFunction(0x39, 0, "set_effect", 3..3), SpecificSpecialFunction(0x39, 1, "effect_busy", 1..1), SpecificSpecialFunction(0x39, 7, "remove_effect", 1..1), SpecificSpecialFunction(0x3E, 0, "set_layout", 3..3), SpecificSpecialFunction(0x3E, 1, "layout_busy", 1..1), SpecificSpecialFunction(0x3E, 7, "remove_layout", 1..1), SpecificSpecialFunction(0x7E, 0, "zoom", 3..3), SpecificSpecialFunction(0x7E, 1, "zoom_gradual", 6..6), SpecificSpecialFunction(0x7F, 0, "pan", 3..3), SpecificSpecialFunction(0x7F, 1, "pan_gradual", 6..6), SpecificSpecialFunction(0x80, 0, "rotate", 2..2), SpecificSpecialFunction(0x80, 1, "rotate_gradual", 5..5), OptionalArgumentsFunction(0, "async_sub", 3, 0, 2000), OptionalArgumentsFunction(2, "async_call", 2, 0), alias(0x4, "sub", 1..1), alias(0x5, "get_sync", 1..1), alias(0x6, "call", 1..1), alias(0x7, "return", 0..0), alias(0x8, "stop", 0..0), alias(0x9, "set_cat", 1..1), alias(0xA, "set_condvar", 1..1), alias(0xB, "add_condvar", 1..1), alias(0xC, "push_condvar", 0..0), alias(0xD, "pop_condvar", 0..0), alias(0x11, "rest_reset", 0..0), alias(0x17, "else", 0..0, 0, -1), // current adjust pushes the else back an indent alias(0x18, "endif", 0..0, -1, -1), // same here alias(0x19, "switch", 0..0, 1), alias(0x1B, "break", 0..0, -1), alias(0x1C, "default", 0..0, 1), alias(0x1D, "endswitch", 0..0, -1, -1), alias(0x24, "speed", 1..1), alias(0x25, "speed_relative", 3..3), alias(0x28, "engine", 1..1), alias(0x40, "play_sfx", 1..1), alias(0x5D, "set_sfx", 2..2), alias(0x5F, "remove_sfx", 1..1), alias(0x6A, "input", 1..1), alias(0xAE, "star", 1..1), alias(0xB5, "debug", 1..1), 0x7DL alias "fade" ) } object DSFunctions : Functions() { override val allFunctions = mutableListOf<Function>( RestFunction(1) ) } abstract class Function(val opCode: Long, val name: String, val argsNeeded: IntRange) { open fun acceptOp(op: Long): Boolean { val opcode = op and 0x3FF val args = (op and 0x3C00) ushr 10 return opcode == opCode && args in argsNeeded } fun checkArgsNeeded(functionCall: FunctionCall) { val args = functionCall.args.size.toLong() if (args !in argsNeeded) { throw WrongArgumentsError(args, argsNeeded, "function ${functionCall.func}<${functionCall.specialArg}>, got ${functionCall.args}") } } abstract fun produceBytecode(funcCall: FunctionCall): LongArray abstract fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String fun argsToTickflowArgs(args: LongArray, specialArgStrings: Map<Int, String>, radix: Int = 16): String { return args.mapIndexed { index, it -> if (specialArgStrings.containsKey(index)) { specialArgStrings[index] } else { if (radix == 16) getHex(it) else it.toInt().toString(radix).toString() } }.joinToString(separator = ", ") } fun addSpecialArg(specialArg: Long): String { return (if (specialArg != 0L) "<${getHex(specialArg)}>" else "") } fun getHex(num: Long): String { return if (abs(num.toInt()) < 10) num.toInt().toString(16).toString().toUpperCase(Locale.ROOT) else (if (num.toInt() < 0) "-" else "") + "0x" + abs(num.toInt()).toString(16).toString().toUpperCase(Locale.ROOT) } } class BytecodeFunction : Function(-1, "bytecode", 1..1) { override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { throw NotImplementedError() } override fun produceBytecode(funcCall: FunctionCall): LongArray { return longArrayOf(funcCall.args.first()) } } class BytesFunction : Function(-1, "bytes", 1..Int.MAX_VALUE) { override fun produceBytecode(funcCall: FunctionCall): LongArray { val list = mutableListOf<Long>() var i = 0 while (i < funcCall.args.size) { var n = 0L n += funcCall.args[i] if (i + 1 < funcCall.args.size) n += funcCall.args[i+1] shl 8 if (i + 2 < funcCall.args.size) n += funcCall.args[i+2] shl 16 if (i + 3 < funcCall.args.size) n += funcCall.args[i+3] shl 24 i += 4 list.add(n) } return list.toLongArray() } override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { return this.name + " " + argsToTickflowArgs(args, specialArgStrings) } } class OpcodeFunction : Function(-1, "opcode", 0..Integer.MAX_VALUE) { override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { return getHex(opcode) + addSpecialArg(specialArg) + " " + argsToTickflowArgs(args, specialArgStrings) } override fun produceBytecode(funcCall: FunctionCall): LongArray { val opcode = if (funcCall.func.startsWith("0x")) funcCall.func.substring(2).toLong(16) else funcCall.func.toLong() return createInts(opcode, funcCall.specialArg, funcCall.args.toLongArray()) } } open class OptionalArgumentsFunction(opcode: Long, alias: String, val numArgs: Int, vararg val defaultArgs: Long): AliasedFunction(opcode, alias, (numArgs - defaultArgs.size)..numArgs) { override fun acceptOp(op: Long): Boolean { val opcode = op and 0x3FF val args = (op and 0x3C00) ushr 10 return opcode == opCode && args == numArgs.toLong() } override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { val newArgs = args.toMutableList() while (newArgs.size > argsNeeded.first && newArgs.last() == defaultArgs[newArgs.size - argsNeeded.first - 1]) { newArgs.removeAt(newArgs.size-1) } return super.produceTickflow(state, opcode, specialArg, newArgs.toLongArray(), comments, specialArgStrings) } override fun produceBytecode(funcCall: FunctionCall): LongArray { val newArgs = funcCall.args.toMutableList() while (newArgs.size < numArgs) { newArgs.add(defaultArgs[newArgs.size - argsNeeded.first]) } return super.produceBytecode(FunctionCall(funcCall.func, funcCall.specialArg, newArgs)) } } open class SpecialOnlyFunction(opcode: Long, alias: String, val indentChange: Int = 0, val currentAdjust: Int = 0) : Function(opcode, alias, 1..1) { override fun acceptOp(op: Long): Boolean { val opcode = op and 0x3FF val args = (op and 0x3C00) ushr 10 return opcode == opCode && args == 0L } override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { state.nextIndentLevel += indentChange state.currentAdjust = currentAdjust return "${this.name} ${getHex(specialArg)}" } override fun produceBytecode(funcCall: FunctionCall): LongArray { val spec: Long = funcCall.args.first() if (spec !in 0..0b111111111111111111) throw IllegalArgumentException( "Special argument out of range: got $spec, needs to be ${0..0b111111111111111111}") return longArrayOf((this.opCode or (spec shl 14))) } } open class SpecificSpecialFunction(opcode: Long, val special: Long, alias: String, argsNeeded: IntRange = 0..0b1111, indentChange: Int = 0, currentAdjust: Int = 0) : AliasedFunction(opcode, alias, argsNeeded, indentChange, currentAdjust) { override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { return super.produceTickflow(state, opcode, 0, args, comments, specialArgStrings) } override fun produceBytecode(funcCall: FunctionCall): LongArray { return createInts(opCode, special, funcCall.args.toLongArray()) } override fun acceptOp(op: Long): Boolean { val opcode = op and 0x3FF val args = (op and 0x3C00) ushr 10 val special = op ushr 14 return opcode == opCode && special == this.special && args in argsNeeded } } open class RestFunction(opcode: Long) : SpecialOnlyFunction(opcode, "rest") { override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { return "rest " + getHex(specialArg) + if (comments != CommentType.NONE) "\t// ${specialArg / 48f} beats" else "" } } open class AliasedFunction(opcode: Long, alias: String, argsNeeded: IntRange, val indentChange: Int = 0, val currentAdjust: Int = 0) : Function(opcode, alias, argsNeeded) { override fun produceTickflow(state: DecompilerState, opcode: Long, specialArg: Long, args: LongArray, comments: CommentType, specialArgStrings: Map<Int, String>): String { state.nextIndentLevel += indentChange state.currentAdjust = currentAdjust return this.name + addSpecialArg(specialArg) + " " + argsToTickflowArgs(args, specialArgStrings) } override fun produceBytecode(funcCall: FunctionCall): LongArray { return createInts(this.opCode, funcCall.specialArg, funcCall.args.toLongArray()) } }
mit
a69d4c880ad4142cc8e52e06d48a287d
42.114441
186
0.586109
3.947854
false
false
false
false
paplorinc/intellij-community
uast/uast-common/src/org/jetbrains/uast/evaluation/UEvaluator.kt
4
2036
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.evaluation import com.intellij.openapi.extensions.Extensions import com.intellij.psi.PsiElement import org.jetbrains.uast.* import org.jetbrains.uast.values.UDependency import org.jetbrains.uast.values.UValue // Role: at the current state, evaluate expression(s) interface UEvaluator { val context: UastContext val languageExtensions: List<UEvaluatorExtension> get() { val rootArea = Extensions.getRootArea() if (!rootArea.hasExtensionPoint(UEvaluatorExtension.EXTENSION_POINT_NAME.name)) return listOf() return rootArea.getExtensionPoint(UEvaluatorExtension.EXTENSION_POINT_NAME).extensions.toList() } fun PsiElement.languageExtension(): UEvaluatorExtension? = languageExtensions.firstOrNull { it.language == language } fun UElement.languageExtension(): UEvaluatorExtension? = psi?.languageExtension() fun analyze(method: UMethod, state: UEvaluationState = method.createEmptyState()) fun analyze(field: UField, state: UEvaluationState = field.createEmptyState()) fun evaluate(expression: UExpression, state: UEvaluationState? = null): UValue fun evaluateVariableByReference(variableReference: UReferenceExpression, state: UEvaluationState? = null): UValue fun getDependents(dependency: UDependency): Set<UValue> } fun createEvaluator(context: UastContext, extensions: List<UEvaluatorExtension>): UEvaluator = TreeBasedEvaluator(context, extensions)
apache-2.0
f540179eb84756bbbd30f7dd00a9b22f
38.153846
119
0.777505
4.514412
false
false
false
false
algra/pact-jvm
pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/matchingrules/Category.kt
1
3846
package au.com.dius.pact.model.matchingrules import au.com.dius.pact.model.PactSpecVersion import mu.KLogging import java.util.Comparator import java.util.function.Predicate import java.util.function.ToIntFunction /** * Matching rules category */ data class Category @JvmOverloads constructor( val name: String, var matchingRules: MutableMap<String, MatchingRuleGroup> = mutableMapOf() ) { companion object : KLogging() fun addRule(item: String, matchingRule: MatchingRule): Category { if (!matchingRules.containsKey(item)) { matchingRules[item] = MatchingRuleGroup(mutableListOf(matchingRule)) } else { matchingRules[item]!!.rules.add(matchingRule) } return this } fun addRule(matchingRule: MatchingRule) = addRule("", matchingRule) fun setRule(item: String, matchingRule: MatchingRule) { matchingRules[item] = MatchingRuleGroup(mutableListOf(matchingRule)) } fun setRule(matchingRule: MatchingRule) = setRule("", matchingRule) fun setRules(item: String, rules: List<MatchingRule>) { setRules(item, MatchingRuleGroup(rules.toMutableList())) } fun setRules(matchingRules: List<MatchingRule>) = setRules("", matchingRules) fun setRules(item: String, rules: MatchingRuleGroup) { matchingRules[item] = rules } /** * If the rules are empty */ fun isEmpty() = matchingRules.isEmpty() || matchingRules.all { it.value.rules.isEmpty() } /** * If the rules are not empty */ fun isNotEmpty() = matchingRules.any { it.value.rules.isNotEmpty() } fun filter(predicate: Predicate<String>) = copy(matchingRules = matchingRules.filter { predicate.test(it.key) }.toMutableMap()) @Deprecated("Use maxBy(Comparator) as this function causes a defect (see issue #698)") fun maxBy(fn: ToIntFunction<String>): MatchingRuleGroup { val max = matchingRules.maxBy { fn.applyAsInt(it.key) } return max?.value ?: MatchingRuleGroup() } fun maxBy(comparator: Comparator<String>): MatchingRuleGroup { val max = matchingRules.maxWith(Comparator { a, b -> comparator.compare(a.key, b.key) }) return max?.value ?: MatchingRuleGroup() } fun allMatchingRules() = matchingRules.flatMap { it.value.rules } fun addRules(item: String, rules: List<MatchingRule>) { if (!matchingRules.containsKey(item)) { matchingRules[item] = MatchingRuleGroup(rules.toMutableList()) } else { matchingRules[item]!!.rules.addAll(rules) } } fun applyMatcherRootPrefix(prefix: String) { matchingRules = matchingRules.mapKeys { e -> prefix + e.key }.toMutableMap() } fun copyWithUpdatedMatcherRootPrefix(prefix: String): Category { val category = copy() category.applyMatcherRootPrefix(prefix) return category } fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any?> { return if (pactSpecVersion < PactSpecVersion.V3) { matchingRules.entries.associate { val keyBase = "\$.$name" if (it.key.startsWith('$')) { Pair(keyBase + it.key.substring(1), it.value.toMap(pactSpecVersion)) } else { Pair(keyBase + it.key, it.value.toMap(pactSpecVersion)) } } } else { matchingRules.entries.associate { Pair(it.key, it.value.toMap(pactSpecVersion)) } } } fun fromMap(map: Map<String, Any?>) { map.forEach { (key, value) -> if (value is Map<*, *>) { val ruleGroup = MatchingRuleGroup.fromMap(value as Map<String, Any?>) if (name == "path") { setRules("", ruleGroup) } else { setRules(key, ruleGroup) } } else if (name == "path" && value is List<*>) { value.forEach { addRule(MatchingRuleGroup.ruleFromMap(it as Map<String, Any?>)) } } else { logger.warn { "$value is not a valid matcher definition" } } } } }
apache-2.0
f875ecc0b193f45567cbcebc77cb638c
30.268293
92
0.670827
3.92449
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/LinuxDistributionBuilder.kt
1
20644
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("BlockingMethodInNonBlockingContext") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.io.NioFiles import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.BundledRuntimeImpl.Companion.getProductPrefix import org.jetbrains.intellij.build.impl.productInfo.* import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder import org.jetbrains.intellij.build.io.* import java.nio.file.* import java.nio.file.attribute.PosixFilePermissions import kotlin.time.Duration.Companion.minutes class LinuxDistributionBuilder(override val context: BuildContext, private val customizer: LinuxDistributionCustomizer, private val ideaProperties: Path?) : OsSpecificDistributionBuilder { private val iconPngPath: Path? override val targetOs: OsFamily get() = OsFamily.LINUX init { val iconPng = (if (context.applicationInfo.isEAP) customizer.iconPngPathForEAP else null) ?: customizer.iconPngPath iconPngPath = if (iconPng.isNullOrEmpty()) null else Path.of(iconPng) } override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) { spanBuilder("copy files for os distribution").setAttribute("os", targetOs.osName).setAttribute("arch", arch.name).useWithScope2 { withContext(Dispatchers.IO) { val distBinDir = targetPath.resolve("bin") val sourceBinDir = context.paths.communityHomeDir.resolve("bin/linux") copyFileToDir(sourceBinDir.resolve("restart.py"), distBinDir) if (arch == JvmArchitecture.x64 || arch == JvmArchitecture.aarch64) { @Suppress("SpellCheckingInspection") listOf("fsnotifier", "libdbm.so").forEach { copyFileToDir(sourceBinDir.resolve("${arch.dirName}/${it}"), distBinDir) } } generateBuildTxt(context, targetPath) copyDistFiles(context = context, newDir = targetPath, os = OsFamily.LINUX, arch = arch) Files.copy(ideaProperties!!, distBinDir.resolve(ideaProperties.fileName), StandardCopyOption.REPLACE_EXISTING) //todo[nik] converting line separators to unix-style make sense only when building Linux distributions under Windows on a local machine; // for real installers we need to checkout all text files with 'lf' separators anyway convertLineSeparators(targetPath.resolve("bin/idea.properties"), "\n") if (iconPngPath != null) { Files.copy(iconPngPath, distBinDir.resolve("${context.productProperties.baseFileName}.png"), StandardCopyOption.REPLACE_EXISTING) } generateVMOptions(distBinDir) generateUnixScripts(distBinDir = distBinDir, os = OsFamily.LINUX, arch = arch, context = context) generateReadme(targetPath) generateVersionMarker(targetPath, context) RepairUtilityBuilder.bundle(context = context, os = OsFamily.LINUX, arch = arch, distributionDir = targetPath) customizer.copyAdditionalFiles(context = context, targetDir = targetPath, arch = arch) } } } override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) { copyFilesForOsDistribution(osAndArchSpecificDistPath, arch) val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}" context.executeStep(spanBuilder("build linux .tar.gz").setAttribute("arch", arch.name), BuildOptions.LINUX_ARTIFACTS_STEP) { if (customizer.buildTarGzWithoutBundledRuntime) { context.executeStep(spanBuilder("Build Linux .tar.gz without bundled Runtime").setAttribute("arch", arch.name), BuildOptions.LINUX_TAR_GZ_WITHOUT_BUNDLED_RUNTIME_STEP) { val tarGzPath = buildTarGz(runtimeDir = null, unixDistPath = osAndArchSpecificDistPath, suffix = NO_JBR_SUFFIX + suffix, arch = arch) checkExecutablePermissions(tarGzPath, rootDirectoryName, includeRuntime = false) } } if (customizer.buildOnlyBareTarGz) { return@executeStep } val runtimeDir = context.bundledRuntime.extract(getProductPrefix(context), OsFamily.LINUX, arch) val tarGzPath = buildTarGz(arch = arch, runtimeDir = runtimeDir, unixDistPath = osAndArchSpecificDistPath, suffix = suffix) checkExecutablePermissions(tarGzPath, rootDirectoryName, includeRuntime = true) if (arch == JvmArchitecture.x64) { buildSnapPackage(runtimeDir = runtimeDir, unixDistPath = osAndArchSpecificDistPath, arch = arch) } else { // TODO: Add snap for aarch64 Span.current().addEvent("skip building Snap packages for non-x64 arch") } if (!context.options.buildStepsToSkip.contains(BuildOptions.REPAIR_UTILITY_BUNDLE_STEP)) { val tempTar = Files.createTempDirectory(context.paths.tempDir, "tar-") try { ArchiveUtils.unTar(tarGzPath, tempTar) RepairUtilityBuilder.generateManifest(context = context, unpackedDistribution = tempTar.resolve(rootDirectoryName), os = OsFamily.LINUX, arch = arch) } finally { NioFiles.deleteRecursively(tempTar) } } } } private fun generateVMOptions(distBinDir: Path) { val fileName = "${context.productProperties.baseFileName}64.vmoptions" @Suppress("SpellCheckingInspection") val vmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties) + listOf("-Dsun.tools.attach.tmp.only=true") VmOptionsGenerator.writeVmOptions(distBinDir.resolve(fileName), vmOptions, "\n") } private fun generateReadme(unixDistPath: Path) { val fullName = context.applicationInfo.productName val sourceFile = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/linux/Install-Linux-tar.txt") val targetFile = unixDistPath.resolve("Install-Linux-tar.txt") substituteTemplatePlaceholders(sourceFile, targetFile, "@@", listOf( Pair("product_full", fullName), Pair("product", context.productProperties.baseFileName), Pair("product_vendor", context.applicationInfo.shortCompanyName), Pair("system_selector", context.systemSelector) ), convertToUnixLineEndings = true) } override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> { var patterns = persistentListOf("bin/*.sh", "plugins/**/*.sh", "bin/*.py", "bin/fsnotifier*") .addAll(customizer.extraExecutables) if (includeRuntime) { patterns = patterns.addAll(context.bundledRuntime.executableFilesPatterns(OsFamily.LINUX)) } return patterns.addAll(context.getExtraExecutablePattern(OsFamily.LINUX)) } private val rootDirectoryName: String get() = customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber) private fun buildTarGz(arch: JvmArchitecture, runtimeDir: Path?, unixDistPath: Path, suffix: String): Path { val tarRoot = rootDirectoryName val tarName = artifactName(context, suffix) val tarPath = context.paths.artifactDir.resolve(tarName) val paths = mutableListOf(context.paths.distAllDir, unixDistPath) var javaExecutablePath: String? = null if (runtimeDir != null) { paths.add(runtimeDir) javaExecutablePath = "jbr/bin/java" require(Files.exists(runtimeDir.resolve(javaExecutablePath))) { "$javaExecutablePath was not found under $runtimeDir" } } val productJsonDir = context.paths.tempDir.resolve("linux.dist.product-info.json$suffix") generateProductJson(targetDir = productJsonDir, arch = arch, javaExecutablePath = javaExecutablePath, context = context) paths.add(productJsonDir) val executableFilesPatterns = generateExecutableFilesPatterns(runtimeDir != null) spanBuilder("build Linux tar.gz") .setAttribute("runtimeDir", runtimeDir?.toString() ?: "") .useWithScope { synchronized(context.paths.distAllDir) { // Sync to prevent concurrent context.paths.distAllDir modification and reading from two Linux builders, // otherwise tar building may fail due to FS change (changed attributes) while reading a file for (dir in paths) { updateExecutablePermissions(dir, executableFilesPatterns) } ArchiveUtils.tar(tarPath, tarRoot, paths.map(Path::toString), context.options.buildDateInSeconds) } checkInArchive(tarPath, tarRoot, context) context.notifyArtifactBuilt(tarPath) } return tarPath } private suspend fun buildSnapPackage(runtimeDir: Path, unixDistPath: Path, arch: JvmArchitecture) { val snapName = customizer.snapName ?: return if (!context.options.buildUnixSnaps) { return } val snapDir = context.paths.buildOutputDir.resolve("dist.snap") spanBuilder("build Linux .snap package") .setAttribute("snapName", snapName) .useWithScope { span -> check(iconPngPath != null) { context.messages.error("'iconPngPath' not set") } check(!customizer.snapDescription.isNullOrBlank()) { context.messages.error("'snapDescription' not set") } span.addEvent("prepare files") val unixSnapDistPath = context.paths.buildOutputDir.resolve("dist.unix.snap") copyDir(unixDistPath, unixSnapDistPath) val appInfo = context.applicationInfo val productName = appInfo.productNameWithEdition substituteTemplatePlaceholders( inputFile = context.paths.communityHomeDir.resolve("platform/platform-resources/src/entry.desktop"), outputFile = snapDir.resolve("$snapName.desktop"), placeholder = "$", values = listOf( Pair("NAME", productName), Pair("ICON", "\${SNAP}/bin/${context.productProperties.baseFileName}.png"), Pair("SCRIPT", snapName), Pair("COMMENT", appInfo.motto ?: ""), Pair("WM_CLASS", getLinuxFrameClass(context)) ) ) copyFile(iconPngPath, snapDir.resolve("$snapName.png")) val snapcraftTemplate = context.paths.communityHomeDir.resolve( "platform/build-scripts/resources/linux/snap/snapcraft-template.yaml") val versionSuffix = appInfo.versionSuffix?.replace(' ', '-') ?: "" val version = "${appInfo.majorVersion}.${appInfo.minorVersion}${if (versionSuffix.isEmpty()) "" else "-${versionSuffix}"}" substituteTemplatePlaceholders( inputFile = snapcraftTemplate, outputFile = snapDir.resolve("snapcraft.yaml"), placeholder = "$", values = listOf( Pair("NAME", snapName), Pair("VERSION", version), Pair("SUMMARY", productName), Pair("DESCRIPTION", customizer.snapDescription!!), Pair("GRADE", if (appInfo.isEAP) "devel" else "stable"), Pair("SCRIPT", "bin/${context.productProperties.baseFileName}.sh") ) ) FileSet(unixSnapDistPath) .include("bin/*.sh") .include("bin/*.py") .include("bin/fsnotifier*") .enumerate().forEach(::makeFileExecutable) FileSet(runtimeDir) .include("jbr/bin/*") .enumerate().forEach(::makeFileExecutable) if (!customizer.extraExecutables.isEmpty()) { for (distPath in listOf(unixSnapDistPath, context.paths.distAllDir)) { val fs = FileSet(distPath) customizer.extraExecutables.forEach(fs::include) fs.enumerateNoAssertUnusedPatterns().forEach(::makeFileExecutable) } } validateProductJson(jsonText = generateProductJson(unixSnapDistPath, arch = arch, "jbr/bin/java", context), relativePathToProductJson = "", installationDirectories = listOf(context.paths.distAllDir, unixSnapDistPath, runtimeDir), installationArchives = listOf(), context = context) val resultDir = snapDir.resolve("result") Files.createDirectories(resultDir) span.addEvent("build package") val snapArtifact = snapName + "_" + version + "_amd64.snap" runProcess( args = listOf( "docker", "run", "--rm", "--volume=$snapDir/snapcraft.yaml:/build/snapcraft.yaml:ro", "--volume=$snapDir/$snapName.desktop:/build/snap/gui/$snapName.desktop:ro", "--volume=$snapDir/$snapName.png:/build/prime/meta/gui/icon.png:ro", "--volume=$snapDir/result:/build/result", "--volume=${context.paths.getDistAll()}:/build/dist.all:ro", "--volume=$unixSnapDistPath:/build/dist.unix:ro", "--volume=$runtimeDir:/build/jre:ro", "--workdir=/build", context.options.snapDockerImage, "snapcraft", "snap", "-o", "result/$snapArtifact" ), workingDir = snapDir, timeout = context.options.snapDockerBuildTimeoutMin.minutes, ) moveFileToDir(resultDir.resolve(snapArtifact), context.paths.artifactDir) context.notifyArtifactWasBuilt(context.paths.artifactDir.resolve(snapArtifact)) } } } private const val NO_JBR_SUFFIX = "-no-jbr" private fun generateProductJson(targetDir: Path, arch: JvmArchitecture, javaExecutablePath: String?, context: BuildContext): String { val scriptName = context.productProperties.baseFileName val file = targetDir.resolve(PRODUCT_INFO_FILE_NAME) Files.createDirectories(targetDir) val json = generateMultiPlatformProductJson( relativePathToBin = "bin", builtinModules = context.builtinModule, launch = listOf(ProductInfoLaunchData( os = OsFamily.LINUX.osName, arch = arch.dirName, launcherPath = "bin/$scriptName.sh", javaExecutablePath = javaExecutablePath, vmOptionsFilePath = "bin/" + scriptName + "64.vmoptions", startupWmClass = getLinuxFrameClass(context), bootClassPathJarNames = context.bootClassPathJarNames, additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.LINUX, arch))), context = context ) Files.writeString(file, json) return json } private fun generateVersionMarker(unixDistPath: Path, context: BuildContext) { val targetDir = unixDistPath.resolve("lib") Files.createDirectories(targetDir) Files.writeString(targetDir.resolve("build-marker-" + context.fullBuildNumber), context.fullBuildNumber) } private fun artifactName(buildContext: BuildContext, suffix: String?): String { val baseName = buildContext.productProperties.getBaseArtifactName(buildContext.applicationInfo, buildContext.buildNumber) return "$baseName$suffix.tar.gz" } private fun makeFileExecutable(file: Path) { Span.current().addEvent("set file permission to 0755", Attributes.of(AttributeKey.stringKey("file"), file.toString())) @Suppress("SpellCheckingInspection") Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rwxr-xr-x")) } internal const val REMOTE_DEV_SCRIPT_FILE_NAME = "remote-dev-server.sh" internal fun generateUnixScripts(distBinDir: Path, os: OsFamily, arch: JvmArchitecture, context: BuildContext) { val classPathJars = context.bootClassPathJarNames var classPath = "CLASS_PATH=\"\$IDE_HOME/lib/${classPathJars[0]}\"" for (i in 1 until classPathJars.size) { classPath += "\nCLASS_PATH=\"\$CLASS_PATH:\$IDE_HOME/lib/${classPathJars[i]}\"" } val additionalJvmArguments = context.getAdditionalJvmArguments(os = os, arch = arch, isScript = true).toMutableList() if (!context.xBootClassPathJarNames.isEmpty()) { val bootCp = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$IDE_HOME/lib/${it}" } additionalJvmArguments.add("\"-Xbootclasspath/a:$bootCp\"") } val additionalJvmArgs = additionalJvmArguments.joinToString(separator = " ") val baseName = context.productProperties.baseFileName val vmOptionsPath = when (os) { OsFamily.LINUX -> distBinDir.resolve("${baseName}64.vmoptions") OsFamily.MACOS -> distBinDir.resolve("${baseName}.vmoptions") else -> throw IllegalStateException("Unknown OsFamily") } val defaultXmxParameter = try { Files.readAllLines(vmOptionsPath).firstOrNull { it.startsWith("-Xmx") } } catch (e: NoSuchFileException) { throw IllegalStateException("File '$vmOptionsPath' should be already generated at this point", e) } ?: throw IllegalStateException("-Xmx was not found in '$vmOptionsPath'") val isRemoteDevEnabled = context.productProperties.productLayout.bundledPluginModules.contains("intellij.remoteDevServer") Files.createDirectories(distBinDir) val sourceScriptDir = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/linux/scripts") when (os) { OsFamily.LINUX -> { val scriptName = "$baseName.sh" Files.newDirectoryStream(sourceScriptDir).use { for (file in it) { val fileName = file.fileName.toString() if (!isRemoteDevEnabled && fileName == REMOTE_DEV_SCRIPT_FILE_NAME) { continue } val target = distBinDir.resolve(if (fileName == "executable-template.sh") scriptName else fileName) copyScript(sourceFile = file, targetFile = target, vmOptionsFileName = baseName, additionalJvmArgs = additionalJvmArgs, defaultXmxParameter = defaultXmxParameter, classPath = classPath, scriptName = scriptName, context = context) } } copyInspectScript(context, distBinDir) } OsFamily.MACOS -> { copyScript(sourceFile = sourceScriptDir.resolve(REMOTE_DEV_SCRIPT_FILE_NAME), targetFile = distBinDir.resolve(REMOTE_DEV_SCRIPT_FILE_NAME), vmOptionsFileName = baseName, additionalJvmArgs = additionalJvmArgs, defaultXmxParameter = defaultXmxParameter, classPath = classPath, scriptName = baseName, context = context) } else -> { throw IllegalStateException("Unsupported OsFamily: $os") } } } private fun copyScript(sourceFile: Path, targetFile: Path, vmOptionsFileName: String, additionalJvmArgs: String, defaultXmxParameter: String, classPath: String, scriptName: String, context: BuildContext) { // Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts // https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri substituteTemplatePlaceholders( inputFile = sourceFile, outputFile = targetFile, placeholder = "__", values = listOf( Pair("product_full", context.applicationInfo.productName), Pair("product_uc", context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)), Pair("product_vendor", context.applicationInfo.shortCompanyName), Pair("product_code", context.applicationInfo.productCode), Pair("vm_options", vmOptionsFileName), Pair("system_selector", context.systemSelector), Pair("ide_jvm_args", additionalJvmArgs), Pair("ide_default_xmx", defaultXmxParameter.trim()), Pair("class_path", classPath), Pair("script_name", scriptName), Pair("main_class_name", context.productProperties.mainClassName), ), mustUseAllPlaceholders = false, convertToUnixLineEndings = true, ) }
apache-2.0
e3cd3affbdb90b7ea0af23c80bf1af1c
46.787037
144
0.675983
4.879225
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrame/CapturedValuesSearcher.kt
1
5089
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core.stackFrame import com.intellij.debugger.impl.descriptors.data.DescriptorData import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl import com.sun.jdi.Field import com.sun.jdi.ObjectReference import com.sun.jdi.Value import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.inline.INLINE_TRANSFORMATION_SUFFIX import org.jetbrains.kotlin.idea.debugger.base.util.safeFields import java.util.* private sealed class PendingValue { class Ordinary(val name: String, val field: Field, val container: Container) : PendingValue() { override fun addTo(existingVariables: ExistingVariables): CapturedAsFieldValueData? { if (!existingVariables.add(ExistingVariable.Ordinary(name))) { return null } return CapturedAsFieldValueData(name, container.value, field) } } class This(val label: String, val value: Value?) : PendingValue() { override fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? { val thisName = if (existingVariables.hasThisVariables) { if (!existingVariables.add(ExistingVariable.LabeledThis(label))) { // Avoid item duplication return null } getThisName(label) } else { if (!existingVariables.add(ExistingVariable.LabeledThis(label))) { return null } AsmUtil.THIS } return LabeledThisData(label, thisName, value) } } class Container(val value: ObjectReference) : PendingValue() { fun getChildren(): List<PendingValue> { return value.referenceType().safeFields() .filter { it.isApplicable() } .mapNotNull { createPendingValue(this, it) } } private fun Field.isApplicable(): Boolean { val name = name() return name.startsWith(AsmUtil.CAPTURED_PREFIX) || name == AsmUtil.CAPTURED_THIS_FIELD } override fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? { throw IllegalStateException("Should not be called on a container") } } abstract fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? } internal fun attachCapturedValues( containerValue: ObjectReference, existingVariables: ExistingVariables, collector: (DescriptorData<out ValueDescriptorImpl>) -> Unit ) { val values = collectPendingValues(PendingValue.Container(containerValue)) for (value in values) { val descriptorData = value.addTo(existingVariables) ?: continue collector(descriptorData) } } private fun collectPendingValues(container: PendingValue.Container): List<PendingValue> { val queue = ArrayDeque<PendingValue>() queue.offer(container) val values = mutableListOf<PendingValue>() collectValuesBfs(queue, values) return values } private tailrec fun collectValuesBfs(queue: Deque<PendingValue>, consumer: MutableList<PendingValue>) { val deeperValues = ArrayDeque<PendingValue>() while (queue.isNotEmpty()) { val value = queue.removeFirst() ?: break if (value is PendingValue.Container) { val children = value.getChildren() deeperValues.addAll(children) continue } consumer += value } if (deeperValues.isNotEmpty()) { collectValuesBfs(deeperValues, consumer) } } private fun createPendingValue(container: PendingValue.Container, field: Field): PendingValue? { val name = field.name() if (name == AsmUtil.CAPTURED_THIS_FIELD) { /* * Captured entities. * In case of captured lambda, we just add values captured to the lambda to the list. * In case of captured this (outer this, for example), we add the 'this' value. */ val value = container.value.getValue(field) as? ObjectReference ?: return null return when (val label = getThisValueLabel(value)) { null -> PendingValue.Container(value) else -> PendingValue.This(label, value) } } else if (name.startsWith(AsmUtil.CAPTURED_LABELED_THIS_FIELD)) { // Extension receivers for a new scheme ($this_<label>) val value = container.value.getValue(field) val label = name.drop(AsmUtil.CAPTURED_LABELED_THIS_FIELD.length).takeIf { it.isNotEmpty() } ?: return null return PendingValue.This(label, value) } // Ordinary values (everything but 'this') assert(name.startsWith(AsmUtil.CAPTURED_PREFIX)) val capturedValueName = name.drop(1).removeSuffix(INLINE_TRANSFORMATION_SUFFIX).takeIf { it.isNotEmpty() } ?: return null return PendingValue.Ordinary(capturedValueName, field, container) }
apache-2.0
3940c8b6c48bdf437ba23bab62181d3b
37.270677
125
0.670269
4.787394
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTrimMarginToTrimIndentIntention.kt
1
3368
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention.Companion.calculateIndent import org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention.Companion.isStartOfLine import org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention.Companion.isSurroundedByLineBreaksOrBlanks import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtLiteralStringTemplateEntry import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertTrimMarginToTrimIndentIntention : SelfTargetingIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.to.trim.indent") ) { override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean { val template = (element.getQualifiedExpressionForSelector()?.receiverExpression as? KtStringTemplateExpression) ?: return false if (!template.text.startsWith("\"\"\"")) return false val callee = element.calleeExpression ?: return false if (callee.text != "trimMargin" || callee.getCallableDescriptor()?.fqNameSafe != FqName("kotlin.text.trimMargin")) return false if (!template.isSurroundedByLineBreaksOrBlanks()) return false val marginPrefix = element.marginPrefix() ?: return false return template.entries.all { entry -> !entry.isStartOfLine() || entry.text.dropWhile { it.isWhitespace() }.startsWith(marginPrefix) } } override fun applyTo(element: KtCallExpression, editor: Editor?) { val qualifiedExpression = element.getQualifiedExpressionForSelector() val template = (qualifiedExpression?.receiverExpression as? KtStringTemplateExpression) ?: return val marginPrefix = element.marginPrefix() ?: return val indent = template.calculateIndent() val newTemplate = buildString { template.entries.forEach { entry -> val text = entry.text if (entry.isStartOfLine()) { append(indent) append(entry.text.dropWhile { it.isWhitespace() }.replaceFirst(marginPrefix, "")) } else { append(text) } } } qualifiedExpression.replace(KtPsiFactory(element.project).createExpression("\"\"\"$newTemplate\"\"\".trimIndent()")) } } private fun KtCallExpression.marginPrefix(): String? { val argument = valueArguments.firstOrNull()?.getArgumentExpression() if (argument != null) { if (argument !is KtStringTemplateExpression) return null val entry = argument.entries.toList().singleOrNull() as? KtLiteralStringTemplateEntry ?: return null return entry.text.replace("\"", "") } return "|" }
apache-2.0
909dc38894c54a9df03f0e2c5f9a4264
51.625
135
0.732482
5.303937
false
false
false
false
fancylou/FancyFilePicker
fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/ui/presenter/FileClassficationActivityPresenter.kt
1
18120
package net.muliba.fancyfilepickerlibrary.ui.presenter import android.provider.MediaStore import android.util.Log import android.widget.TextView import net.muliba.fancyfilepickerlibrary.ext.concat import net.muliba.fancyfilepickerlibrary.model.Classification import net.muliba.fancyfilepickerlibrary.model.DataSource import net.muliba.fancyfilepickerlibrary.ui.view.FileClassificationUIView import net.muliba.fancyfilepickerlibrary.util.Utils import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import java.io.File import java.util.HashSet import kotlin.collections.ArrayList /** * Created by fancyLou on 2018/3/15. * Copyright © 2018 O2. All rights reserved. */ class FileClassficationActivityPresenter { private val QUERY_FILE_URI = MediaStore.Files.getContentUri("external") private val QUERY_AUDIO_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI private val QUERY_VIDEO_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI private val QUERY_IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI private var mView: FileClassificationUIView? = null fun attachView(view: FileClassificationUIView) { mView = view } fun detachView() { mView = null } /** * 计算每个分类的数量 */ fun countFiles(classification: Classification, countTv: android.widget.TextView) { when (classification) { Classification.PICTURE -> countPictures(countTv) Classification.APPLICATION -> countApplication(countTv) Classification.ARCHIVE -> countArchive(countTv) Classification.AUDIO -> countAudio(countTv) Classification.DOCUMENT -> countDocument(countTv) Classification.VIDEO -> countVideo(countTv) } } /** * 查询列表 */ fun loadingItems(level: Int = -1, parentPath: String = "", filter: HashSet<String> = HashSet()) { when (level) { -1 -> loadMainItems() 0 -> loadPictureFolderItems() 1 -> loadAudioItems() 2 -> loadVideoItems() 3 -> loadDocumentItems(filter) 4 -> loadArchiveItems() 5 -> loadApplicationItems() 6 -> loadPictureItems(parentPath) } } /** * 计算视频数量 */ private fun countVideo(countTv: TextView) { doAsync { val count = if (mView!=null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_VIDEO_URI, arrayOf(MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA), "${MediaStore.Video.Media.SIZE} > ? ", arrayOf("0"), null) val count = query.count query.close() count }else { 0 } uiThread { if (countTv.tag == Classification.VIDEO) { countTv.text = "($count)" } } } } /** * 计算文档数量 */ private fun countDocument(countTv: TextView) { doAsync { val count = if (mView!=null) { val selectStr: String = MediaStore.Files.FileColumns.MIME_TYPE + " = ?" .concat(" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?") .concat(" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?") .concat(" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?") .concat(" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?") .concat(" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?") .concat(" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?") val list = Utils.DOCUMENT_TYPE_LABEL_ARRAY.map { Utils.getMimeTypeFromExtension(it) }.toTypedArray() val query = mView!!.contextInstance().contentResolver.query(QUERY_FILE_URI, arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA), selectStr, list, null) val count = query.count query.close() count }else { 0 } uiThread { if (countTv.tag == Classification.DOCUMENT) { countTv.text = "($count)" } } } } /** * 计算mp3数量 */ private fun countAudio(countTv: TextView) { doAsync { val count = if(mView!=null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_AUDIO_URI, arrayOf(MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA), MediaStore.Audio.Media.SIZE + " > ? ", arrayOf("0"), null) val count = query.count query.close() count }else { 0 } uiThread { if (countTv.tag == Classification.AUDIO) { countTv.text = "($count)" } } } } /** * 计算压缩包的数量 */ private fun countArchive(countTv: TextView) { doAsync { val count = if(mView!=null) { val selectStr: String = MediaStore.Files.FileColumns.MIME_TYPE + " = ?" val array = arrayOf(Utils.getMimeTypeFromExtension(Utils.DOUMENT_TYPE_LABEL_ZIP)) val query = mView!!.contextInstance().contentResolver.query(QUERY_FILE_URI, arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA), selectStr, array, null) val count = query.count query.close() count }else { 0 } uiThread { if (countTv.tag == Classification.ARCHIVE) { countTv.text = "($count)" } } } } /** * 计算apk安装包的数量 */ private fun countApplication(countTv: TextView) { doAsync { val count = if(mView!=null) { val selectStr: String = MediaStore.Files.FileColumns.MIME_TYPE + " = ?" val array = arrayOf(Utils.getMimeTypeFromExtension(Utils.DOUMENT_TYPE_LABEL_APK)) val query = mView!!.contextInstance().contentResolver.query(QUERY_FILE_URI, arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA), selectStr, array, null) val count = query.count query.close() count }else { 0 } uiThread { if (countTv.tag == Classification.APPLICATION) { countTv.text = "($count)" } } } } /** * 计算图片数量 */ private fun countPictures(countTv: TextView) { doAsync { val count = if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_IMAGE_URI, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN), "${MediaStore.Images.Media.SIZE} > ? or ${MediaStore.Images.Media.SIZE} is null", arrayOf("0"), null) val count = query.count query.close() count } else { 0 } uiThread { if (countTv.tag == Classification.PICTURE) { countTv.text = "($count)" } } } } /** * 加载某个目录下所有图片 */ private fun loadPictureItems(bucketId: String) { doAsync { val items = ArrayList<DataSource>() val PROJECTION = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN) val SELECTION = "${MediaStore.Images.Media.BUCKET_ID} = ? and ( ${MediaStore.Images.Media.SIZE} > ? or ${MediaStore.Images.Media.SIZE} is null ) " val ORDER_BY = " ${MediaStore.Images.Media.DATE_TAKEN} DESC" if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_IMAGE_URI, PROJECTION, SELECTION, arrayOf(bucketId, "0"), ORDER_BY) while (query.moveToNext()) { val filePath = query.getString(query.getColumnIndex(MediaStore.Images.Media.DATA)) items.add(DataSource.Picture(filePath)) } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载应用安装包文件 */ private fun loadApplicationItems() { doAsync { val items = ArrayList<DataSource>() val selectStr: String = MediaStore.Files.FileColumns.MIME_TYPE + " = ?" val array = arrayOf(Utils.getMimeTypeFromExtension(Utils.DOUMENT_TYPE_LABEL_APK)) if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_FILE_URI, arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA), selectStr, array, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC") while (query.moveToNext()) { val path = query.getString(query.getColumnIndex(MediaStore.Files.FileColumns.DATA)) val file = File(path) if (file.exists()) { items.add(DataSource.File(path, file)) } else { Log.e("loadApplicationItems", "path:$path not exists!") } } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载压缩包 */ private fun loadArchiveItems() { doAsync { val items = ArrayList<DataSource>() val selectStr: String = MediaStore.Files.FileColumns.MIME_TYPE + " = ?" val array = arrayOf(Utils.getMimeTypeFromExtension(Utils.DOUMENT_TYPE_LABEL_ZIP)) if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_FILE_URI, arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA), selectStr, array, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC") while (query.moveToNext()) { val path = query.getString(query.getColumnIndex(MediaStore.Files.FileColumns.DATA)) val file = File(path) if (file.exists()) { items.add(DataSource.File(path, file)) } else { Log.e("loadArchiveItems", "path:$path not exists!") } } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载文档列表 */ private fun loadDocumentItems(filter: HashSet<String>) { doAsync { val items = ArrayList<DataSource>() val queryList = ArrayList<String>() if (filter.isEmpty()) { Utils.DOCUMENT_TYPE_LABEL_ARRAY.map { queryList.add(Utils.getMimeTypeFromExtension(it)) } } else { filter.map { queryList.add(it) } } var selectStr = "" queryList.mapIndexed { index, _ -> selectStr += if (index > 0) { (" or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? ") } else { (MediaStore.Files.FileColumns.MIME_TYPE + " = ? ") } } val array = queryList.toTypedArray() if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_FILE_URI, arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA), selectStr, array, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC") while (query.moveToNext()) { val path = query.getString(query.getColumnIndex(MediaStore.Files.FileColumns.DATA)) val file = File(path) if (file.exists()) { items.add(DataSource.File(path, file)) } else { Log.e("loadDocumentItems", "path:$path not exists!") } } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载视频文件列表 */ private fun loadVideoItems() { doAsync { val items = ArrayList<DataSource>() val selectStr: String = MediaStore.Video.Media.SIZE + " > ?" val array = arrayOf("0") if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_VIDEO_URI, arrayOf(MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA), selectStr, array, MediaStore.Video.Media.DATE_MODIFIED + " DESC") while (query.moveToNext()) { val path = query.getString(query.getColumnIndex(MediaStore.Video.Media.DATA)) val file = File(path) if (file.exists()) { items.add(DataSource.File(path, file)) } else { Log.e("loadVideoItems", "path:$path not exists!") } } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载音频文件列表 */ private fun loadAudioItems() { doAsync { val items = ArrayList<DataSource>() //FIXME 用MIME_TYPE查不到文件??? val selectStr: String = MediaStore.Audio.Media.SIZE + " > ? " if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_AUDIO_URI, arrayOf(MediaStore.Audio.AudioColumns._ID, MediaStore.Audio.AudioColumns.DATA), selectStr, arrayOf("0"), MediaStore.Audio.Media.DATE_MODIFIED + " DESC") while (query.moveToNext()) { val path = query.getString(query.getColumnIndex(MediaStore.Audio.AudioColumns.DATA)) val file = File(path) if (file.exists()) { items.add(DataSource.File(path, file)) } else { Log.e("loadAudioItems", "path:$path not exists!") } } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载图片文件夹 */ private fun loadPictureFolderItems() { doAsync { val items = ArrayList<DataSource>() val projection = arrayOf(MediaStore.Images.Media.BUCKET_ID, MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA, "count(bucket_id) as cou", MediaStore.Images.Media._ID) val selectStr = " _size > ? or _size is null ) GROUP BY 1,(2" val array = arrayOf("0") if (mView != null) { val query = mView!!.contextInstance().contentResolver.query(QUERY_IMAGE_URI, projection, selectStr, array, "MAX(datetaken) DESC") while (query.moveToNext()) { val bucketId = query.getString(query.getColumnIndex(MediaStore.Images.Media.BUCKET_ID)) val bucketName = query.getString(query.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)) val filePath = query.getString(query.getColumnIndex(android.provider.MediaStore.Images.Media.DATA)) val folderCount = query.getLong(3) if (folderCount < 1) { continue } items.add(DataSource.PictureFolder(bucketName, bucketId, filePath, folderCount)) } query.close() } uiThread { mView?.returnItems(items) } } } /** * 加载主页面 */ private fun loadMainItems() { doAsync { val items = ArrayList<DataSource>() Classification.values().map { items.add(DataSource.Main(it.stringResId, it.imageResId)) } uiThread { mView?.returnItems(items) } } } }
apache-2.0
444d2b14ecb7adde24d2c259acaf2411
36.176715
159
0.494212
4.962809
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/AuthorAdapterDelegate.kt
2
2066
package org.stepik.android.view.catalog.ui.adapter.delegate import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_author.* import kotlinx.android.synthetic.main.layout_author_properties.view.* import org.stepic.droid.R import org.stepic.droid.util.TextUtil import org.stepik.android.domain.catalog.model.CatalogAuthor import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class AuthorAdapterDelegate( private val onItemClick: (Long) -> Unit ) : AdapterDelegate<CatalogAuthor, DelegateViewHolder<CatalogAuthor>>() { override fun isForViewType(position: Int, data: CatalogAuthor): Boolean = true override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogAuthor> = ViewHolder(createView(parent, R.layout.item_author)) private inner class ViewHolder( override val containerView: View ) : DelegateViewHolder<CatalogAuthor>(containerView), LayoutContainer { private val authorCourseCount = authorListPropertiesContainer.coursesCountText private val authorSubscriberCount = authorListPropertiesContainer.subscribersCountText init { containerView.setOnClickListener { itemData?.id?.let(onItemClick) } } override fun onBind(data: CatalogAuthor) { Glide .with(context) .asBitmap() .load(data.avatar) .placeholder(R.drawable.general_placeholder) .fitCenter() .into(authorListImage) authorListTitle.text = data.fullName authorCourseCount.text = context.resources.getQuantityString(R.plurals.course_count, data.createdCoursesCount, data.createdCoursesCount) authorSubscriberCount.text = context.resources.getString(R.string.author_subscribers, TextUtil.formatNumbers(data.followersCount.toLong())) } } }
apache-2.0
1b7df7108eaa82aa581639b6576cc043
42.0625
151
0.733785
4.838407
false
false
false
false
allotria/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/ngram/ModelRunnerWithCache.kt
3
1553
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.ml.ngram import com.intellij.completion.ml.ngram.NGram.forgetTokens import com.intellij.completion.ml.ngram.NGram.learnTokens import com.intellij.completion.ml.ngram.NGram.lexPsiFile import com.intellij.completion.ngram.slp.modeling.Model import com.intellij.completion.ngram.slp.modeling.ngram.JMModel import com.intellij.completion.ngram.slp.modeling.runners.ModelRunner import com.intellij.psi.PsiFile import com.intellij.psi.SmartPsiElementPointer internal class ModelRunnerWithCache(model: Model = JMModel()) : ModelRunner(model) { private val myCache = FilePath2Tokens(this) internal fun processFile(filePointer: SmartPsiElementPointer<PsiFile>) { val filePath = filePointer.virtualFile?.path ?: return if (filePath in myCache) return val tokens = lexPsiFile(filePointer.element ?: return, TEXT_RANGE_LIMIT) myCache[filePath] = tokens learnTokens(tokens) } private class FilePath2Tokens(private val myModelRunner: ModelRunner) : LinkedHashMap<String, List<String>>() { override fun removeEldestEntry(eldest: Map.Entry<String?, List<String>?>): Boolean { if (size > CACHE_SIZE) { eldest.value?.let { myModelRunner.forgetTokens(it) } return true } return false } } companion object { private const val CACHE_SIZE = 9 private const val TEXT_RANGE_LIMIT = 16 * 1024 // 32 KB of chars } }
apache-2.0
9bf818e469163ef5656b16457599b5b5
37.85
140
0.754024
3.892231
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/branch/ShowDiffWithBranchDialog.kt
3
3583
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.branch import com.intellij.dvcs.ui.CompareBranchesDiffPanel import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.FrameWrapper import com.intellij.openapi.ui.Messages import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import git4idea.config.GitVcsSettings import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.util.GitLocalCommitCompareInfo import org.jetbrains.annotations.Nls import java.awt.BorderLayout import javax.swing.JComponent private val LOG = logger<ShowDiffWithBranchDialog>() internal class ShowDiffWithBranchDialog(val project: Project, val branchName: String, val repositories: List<GitRepository>, val currentBranchName: String ) : FrameWrapper(project, "ShowDiffWithBranchDialog", // NON-NLS title = GitBundle.message("show.diff.between.dialog.title", branchName)) { private var diffPanel : CompareBranchesDiffPanel private val loadingPanel: JBLoadingPanel init { closeOnEsc() diffPanel = CompareBranchesDiffPanel(project, GitVcsSettings.getInstance(project), branchName, currentBranchName) diffPanel.disableControls() diffPanel.setEmptyText("") loadingPanel = JBLoadingPanel(BorderLayout(), this).apply { startLoading() add(diffPanel) } val rootPanel = JBUI.Panels.simplePanel() rootPanel.addToCenter(loadingPanel) rootPanel.border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP) component = rootPanel } override fun show() { super.show() val modalityState = ModalityState.stateForComponent(diffPanel) ApplicationManager.getApplication().executeOnPooledThread { val result = loadDiff() runInEdt(modalityState) { if (!isDisposed) { loadingPanel.stopLoading() when (result) { is LoadingResult.Success -> { diffPanel.setCompareInfo(result.compareInfo) diffPanel.setEmptyText(GitBundle.message("show.diff.between.dialog.no.differences.empty.text")) diffPanel.enableControls() } is LoadingResult.Error -> Messages.showErrorDialog(diffPanel, result.error) } } } } } override var preferredFocusedComponent: JComponent? get() = diffPanel.preferredFocusComponent set(_) {} private fun loadDiff() : LoadingResult { try { val compareInfo = GitLocalCommitCompareInfo(project, branchName) for (repository in repositories) { compareInfo.putTotalDiff(repository, GitBranchWorker.loadTotalDiff(repository, branchName)) } return LoadingResult.Success(compareInfo) } catch (e: Exception) { LOG.warn(e) return LoadingResult.Error(GitBundle.message("show.diff.between.dialog.could.not.load.diff.with.branch.error", branchName, e.message)) } } private sealed class LoadingResult { class Success(val compareInfo: GitLocalCommitCompareInfo): LoadingResult() class Error(@Nls val error: String) : LoadingResult() } }
apache-2.0
835dabecd6013b824317b87667ed3f81
35.20202
140
0.712531
4.611326
false
false
false
false
Kotlin/kotlinx.coroutines
benchmarks/src/jmh/kotlin/benchmarks/scheduler/StatefulAwaitsBenchmark.kt
1
5305
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks.scheduler import benchmarks.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import org.openjdk.jmh.annotations.* import java.util.concurrent.* /* * Benchmark which launches multiple async jobs each with either own private or global shared state, * each job iterates over its state multiple times and suspends after every iteration. * Benchmark is intended to indicate pros and cons of coroutines affinity (assuming threads are rarely migrated) * and comparison with single thread and ForkJoinPool * * Benchmark (dispatcher) (jobsCount) Mode Cnt Score Error Units * StatefulAsyncBenchmark.dependentStateAsync fjp 1 avgt 10 42.147 ± 11.563 us/op * StatefulAsyncBenchmark.dependentStateAsync fjp 8 avgt 10 111.053 ± 40.097 us/op * StatefulAsyncBenchmark.dependentStateAsync fjp 16 avgt 10 239.992 ± 52.839 us/op * StatefulAsyncBenchmark.dependentStateAsync ftp_1 1 avgt 10 32.851 ± 11.385 us/op * StatefulAsyncBenchmark.dependentStateAsync ftp_1 8 avgt 10 51.692 ± 0.961 us/op * StatefulAsyncBenchmark.dependentStateAsync ftp_1 16 avgt 10 101.511 ± 3.060 us/op * StatefulAsyncBenchmark.dependentStateAsync ftp_8 1 avgt 10 31.549 ± 1.014 us/op * StatefulAsyncBenchmark.dependentStateAsync ftp_8 8 avgt 10 103.990 ± 1.588 us/op * StatefulAsyncBenchmark.dependentStateAsync ftp_8 16 avgt 10 156.384 ± 2.914 us/op * * StatefulAsyncBenchmark.independentStateAsync fjp 1 avgt 10 32.503 ± 0.721 us/op * StatefulAsyncBenchmark.independentStateAsync fjp 8 avgt 10 73.000 ± 1.686 us/op * StatefulAsyncBenchmark.independentStateAsync fjp 16 avgt 10 98.629 ± 7.541 us/op * StatefulAsyncBenchmark.independentStateAsync ftp_1 1 avgt 10 26.111 ± 0.814 us/op * StatefulAsyncBenchmark.independentStateAsync ftp_1 8 avgt 10 54.644 ± 1.261 us/op * StatefulAsyncBenchmark.independentStateAsync ftp_1 16 avgt 10 104.871 ± 1.599 us/op * StatefulAsyncBenchmark.independentStateAsync ftp_8 1 avgt 10 31.929 ± 0.698 us/op * StatefulAsyncBenchmark.independentStateAsync ftp_8 8 avgt 10 108.959 ± 1.029 us/op * StatefulAsyncBenchmark.independentStateAsync ftp_8 16 avgt 10 159.593 ± 5.262 us/op * */ @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Fork(value = 2) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) @State(Scope.Benchmark) open class StatefulAsyncBenchmark : ParametrizedDispatcherBase() { private val stateSize = 2048 private val jobSuspensions = 2 // multiplicative factor for throughput // it's useful to have more jobs than cores so run queue always will be non empty @Param("1", "8", "16") var jobsCount = 1 @Param("fjp", "ftp_1", "dispatcher") override var dispatcher: String = "fjp" @Volatile private var state: Array<LongArray>? = null @Setup override fun setup() { super.setup() state = Array(Runtime.getRuntime().availableProcessors() * 4) { LongArray(stateSize) { ThreadLocalRandom.current().nextLong() } } } @Benchmark fun independentStateAsync() = runBlocking { val broadcastChannel = BroadcastChannel<Int>(1) val subscriptionChannel = Channel<Int>(jobsCount) val jobs= (0 until jobsCount).map { launchJob(it, broadcastChannel, subscriptionChannel) }.toList() repeat(jobsCount) { subscriptionChannel.receive() // await all jobs to start } // Fire barrier to start execution broadcastChannel.send(1) jobs.forEach { it.await() } } @Benchmark fun dependentStateAsync() = runBlocking { val broadcastChannel = BroadcastChannel<Int>(1) val subscriptionChannel = Channel<Int>(jobsCount) val jobs= (0 until jobsCount).map { launchJob(0, broadcastChannel, subscriptionChannel) }.toList() repeat(jobsCount) { subscriptionChannel.receive() // await all jobs to start } // Fire barrier to start execution broadcastChannel.send(1) jobs.forEach { it.await() } } private fun launchJob( stateNum: Int, channel: BroadcastChannel<Int>, subscriptionChannel: Channel<Int> ): Deferred<Long> = async { val subscription = channel.openSubscription() subscriptionChannel.send(1) subscription.receive() var sum = 0L repeat(jobSuspensions) { val arr = state!![stateNum] for (i in 0 until stateSize) { sum += arr[i] } yield() } sum } }
apache-2.0
05f0e56d9c336db374c8b4e07a84bfcd
43.058333
137
0.626442
4.026657
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/flow/operators/IndexedTest.kt
1
1148
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlin.test.* class IndexedTest : TestBase() { @Test fun testWithIndex() = runTest { val flow = flowOf(3, 2, 1).withIndex() assertEquals(listOf(IndexedValue(0, 3), IndexedValue(1, 2), IndexedValue(2, 1)), flow.toList()) } @Test fun testWithIndexEmpty() = runTest { val flow = emptyFlow<Int>().withIndex() assertEquals(emptyList(), flow.toList()) } @Test fun testCollectIndexed() = runTest { val result = ArrayList<IndexedValue<Long>>() flowOf(3L, 2L, 1L).collectIndexed { index, value -> result.add(IndexedValue(index, value)) } assertEquals(listOf(IndexedValue(0, 3L), IndexedValue(1, 2L), IndexedValue(2, 1L)), result) } @Test fun testCollectIndexedEmptyFlow() = runTest { val flow = flow<Int> { expect(1) } flow.collectIndexed { _, _ -> expectUnreached() } finish(2) } }
apache-2.0
a2db42abf970e5a345864bb95217487a
24.511111
103
0.597561
3.958621
false
true
false
false
pzhangleo/android-base
base/src/main/java/hope/base/extensions/ViewExtensions.kt
1
2649
package hope.base.extensions import android.content.Context import android.graphics.Bitmap import android.os.Build import android.view.View import android.view.ViewTreeObserver import android.view.inputmethod.InputMethodManager import androidx.annotation.RequiresApi import hope.base.utils.ImageUtils @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) fun View.focusAndShowKeyboard() { /** * This is to be called when the window already has focus. */ fun View.showTheKeyboardNow() { if (isFocused) { post { // We still post the call, just in case we are being notified of the windows focus // but InputMethodManager didn't get properly setup yet. val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) } } } requestFocus() if (hasWindowFocus()) { // No need to wait for the window to get focus. showTheKeyboardNow() } else { // We need to wait until the window gets focus. viewTreeObserver.addOnWindowFocusChangeListener( object : ViewTreeObserver.OnWindowFocusChangeListener { override fun onWindowFocusChanged(hasFocus: Boolean) { // This notification will arrive just before the InputMethodManager gets set up. if (hasFocus) { [email protected]() // It’s very important to remove this listener once we are done. viewTreeObserver.removeOnWindowFocusChangeListener(this) } } }) } } fun View.gone() { if (visibility != View.GONE) { this.visibility = View.GONE } } inline fun View.goneIf(block: () -> Boolean) { if (visibility != View.GONE && block()) { visibility = View.GONE } } fun View.visible() { if (visibility != View.VISIBLE) { this.visibility = View.VISIBLE } } inline fun View.visiableIf(block: () -> Boolean) { if (visibility != View.VISIBLE && block()) { visibility = View.VISIBLE } } fun View.invisible() { if (visibility != View.INVISIBLE) { this.visibility = View.INVISIBLE } } inline fun View.invisiableIf(block: () -> Boolean) { if (visibility != View.INVISIBLE && block()) { visibility = View.INVISIBLE } } fun View.getBitmap(): Bitmap { return ImageUtils.saveViewBitmap(this) }
lgpl-3.0
42ffed9a3c744591fc0deb6737844a3a
29.425287
104
0.609369
4.66843
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/model/NetworkDescription.kt
1
1507
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.model import android.net.MacAddress import android.net.wifi.ScanResult import android.net.wifi.WifiNetworkSuggestion import android.os.Parcelable import androidx.annotation.RequiresApi import androidx.core.util.ObjectsCompat import kotlinx.parcelize.Parcelize @Parcelize class NetworkDescription(var ssid: String, var bssid: String?, var password: String?) : Parcelable { override fun equals(other: Any?): Boolean { if (other is NetworkDescription) { return bssid == other.bssid || (bssid == null && ssid == other.ssid) } return super.equals(other) } override fun hashCode(): Int { return ObjectsCompat.hash(ssid, bssid, password) } }
gpl-2.0
4c695c223f4c6fabddb13cda662b280c
35.731707
100
0.733732
4.206704
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-result/src/main/kotlin/slatekit/results/Aliases.kt
1
2072
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A Kotlin Tool-Kit for Server + Android * </slate_header> */ package slatekit.results /** * Alias for Result<T,E> to avoid collision with the Kotlin Result type */ typealias Expect<T,E> = slatekit.results.Result<T,E> /** * Alias for Result<T,E> defaulting the E error type ( [Failure] branch ) to [Unit] * * This allows for : * 1. Representing null using Option * 2. Allows for mapping Option<T> to Outcome<T> * 3. Can provide additional info on why something is null via status */ typealias Option<T> = Result<T, Unit> /** * Alias for Result<T,E> defaulting the E error type ( [Failure] branch ) to [Exception] * * This allows for : * 1. slightly easier usage by only requiring 1 type parameter * 2. avoid collision with the Kotlin Result type * 3. similarity to Try type available in other languages like Scala */ typealias Try<T> = Result<T, Throwable> /** * Alias for Result<T,E> defaulting the E error type ( [Failure] branch ) to [String] * * This allows for : * 1. slightly easier usage by only requiring 1 type parameter * 2. avoid collision with the Kotlin Result type * 3. use a simple [String] for failures without having to build [Err] or [Exception] */ typealias Notice<T> = Result<T, String> /** * Alias for Result<T,E> defaulting the E error type ( [Failure] branch ) to [Err] interface * * This allows for : * 1. slightly easier usage by only requiring 1 type parameter * 2. avoid collision with the Kotlin Result type * 3. allows for using the sensible default implementations for [Err] */ typealias Outcome<T> = Result<T, Err> /** * Alias for Result<T,E> defaulting the E error type ( [Failure] branch ) to [Err.ErrorList] * * This allows for : * 1. Is to be used for validation purposes * 2. Collecting multiple errors */ typealias Validated<T> = Result<T, Err.ErrorList>
apache-2.0
92bdbbb4903f5033a3fbbd25d4993de6
29.925373
92
0.702703
3.535836
false
false
false
false
zdary/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GHPRMetadataModelBase.kt
12
1073
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.details import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer import org.jetbrains.plugins.github.pullrequest.data.service.GHPRRepositoryDataService import java.util.concurrent.CompletableFuture abstract class GHPRMetadataModelBase(private val repositoryDataService: GHPRRepositoryDataService) : GHPRMetadataModel { override fun loadPotentialReviewers(): CompletableFuture<List<GHPullRequestRequestedReviewer>> { val author = getAuthor() return repositoryDataService.potentialReviewers.thenApply { reviewers -> reviewers.mapNotNull { if (it == author) null else it } } } protected abstract fun getAuthor(): GHUser? override fun loadPotentialAssignees() = repositoryDataService.issuesAssignees override fun loadAssignableLabels() = repositoryDataService.labels }
apache-2.0
ec2d5d155acc7a33bb7b5f0f3f28a53b
47.818182
140
0.815471
4.833333
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/package/invokespecial.kt
2
598
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS // KT-2202 Wrong instruction for invoke private setter class A { private fun f1() { } fun foo() { f1() } } class B { private val foo = 1 get fun foo() { foo } } class C { private var foo = 1 get set fun foo() { foo = 2 foo } } class D { var foo = 1 private set fun foo() { foo = 2 } } fun box(): String { A().foo() B().foo() C().foo() D().foo() return "OK" }
apache-2.0
0a7df9e58a41a6608cedef402485b060
11.458333
72
0.4699
3.417143
false
false
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/tools/info/MessageModel.kt
1
1790
/* * 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.tools.info import android.content.Context import androidx.annotation.StringRes import dev.chromeos.videocompositionsample.presentation.R class MessageModel(private val message: String? = "", @StringRes private val messageResId: Int? = 0, val callbackDetails: CallbackDetails? = null ) { fun getMessage(context: Context): String { return if (message.isNullOrEmpty()) { var message = "" if (messageResId != null && messageResId > 0) { message = try { context.getString(messageResId) } catch (e: Exception) { this.message ?: "" } } if (message.isEmpty()) context.getString(R.string.messages__no_comments) else message } else { message } } data class CallbackDetails( val positiveButtonText: String? = null, val negativeButtonText: String? = null, val positiveKey: String? = null, val negativeKey: String? = null ) }
apache-2.0
fe382773b588d38771148e36c6765ea5
31.563636
75
0.61676
4.824798
false
false
false
false
smmribeiro/intellij-community
plugins/stats-collector/test/com/intellij/stats/completion/network/status/bean/JetStatSettingsTest.kt
12
1538
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.stats.completion.network.status.bean import junit.framework.TestCase import org.assertj.core.api.Assertions class JetStatSettingsTest : TestCase() { fun `test correct settings json parsing`() { val status = "ok" val urlForCompressed = "http://test.jetstat-resty.aws.intellij.net/uploadstats/compressed" val json = """{ "status": "$status", "salt": "sdfs", "experimentVersion": 2, "performExperiment": false, "url": "http://test.jetstat-resty.aws.intellij.net/uploadstats", "urlForZipBase64Content": "$urlForCompressed" }""" val result = JetStatSettingsDeserializer.deserialize(json) Assertions.assertThat(result).isNotNull Assertions.assertThat(result!!.status).isEqualTo(status) Assertions.assertThat(result.urlForZipBase64Content).isEqualTo(urlForCompressed) } fun `test partial settings json parsing`() { val json = """{ "salt": "sdfs", "experimentVersion": 2, "performExperiment": false, "url": "http://test.jetstat-resty.aws.intellij.net/uploadstats" }""" val result = JetStatSettingsDeserializer.deserialize(json) Assertions.assertThat(result).isNotNull Assertions.assertThat(result!!.status).isNotEqualTo("ok") Assertions.assertThat(result.urlForZipBase64Content).isEqualTo("") } }
apache-2.0
8a037de449abc375ada4709f27cb8e22
36.536585
140
0.684655
4.112299
false
true
false
false
daviddenton/configur8
kotlin/src/main/kotlin/io/github/konfigur8/Property.kt
1
1107
package io.github.konfigur8 import java.util.* class Property<T>(val name: String, val deserialize: (String) -> T, val serialize: (T) -> String = { it: T -> it.toString() }, val exposeMode: ExposeMode = ExposeMode.Public) { override fun toString() = name companion object { fun string(name: String, exposeMode: ExposeMode = ExposeMode.Public) = Property(name, { it }, exposeMode = exposeMode) fun int(name: String, exposeMode: ExposeMode = ExposeMode.Public) = Property(name, { it.toInt() }, exposeMode = exposeMode) fun long(name: String, exposeMode: ExposeMode = ExposeMode.Public) = Property(name, { it.toLong() }, exposeMode = exposeMode) fun bool(name: String, exposeMode: ExposeMode = ExposeMode.Public) = Property(name, { it.toBoolean() }, exposeMode = exposeMode) fun character(name: String, exposeMode: ExposeMode = ExposeMode.Public) = Property(name, { it.first() }, exposeMode = exposeMode) fun uuid(name: String, exposeMode: ExposeMode = ExposeMode.Public) = Property(name, { UUID.fromString(it) }, exposeMode = exposeMode) } }
apache-2.0
5cbd3dc0239fb2912ea428731c450230
51.761905
176
0.688347
3.536741
false
false
false
false
smmribeiro/intellij-community
plugins/toml/core/src/main/kotlin/org/toml/ide/formatter/TomlFmtBlock.kt
9
2194
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide.formatter import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.formatter.FormatterUtil import org.toml.ide.formatter.impl.computeIndent import org.toml.ide.formatter.impl.computeSpacing import org.toml.ide.formatter.impl.isWhitespaceOrEmpty import org.toml.lang.psi.TomlElementTypes.ARRAY class TomlFmtBlock( private val node: ASTNode, private val alignment: Alignment?, private val indent: Indent?, private val wrap: Wrap?, private val ctx: TomlFmtContext ) : ASTBlock { override fun getNode(): ASTNode = node override fun getTextRange(): TextRange = node.textRange override fun getAlignment(): Alignment? = alignment override fun getIndent(): Indent? = indent override fun getWrap(): Wrap? = wrap override fun getSubBlocks(): List<Block> = mySubBlocks private val mySubBlocks: List<Block> by lazy { buildChildren() } private fun buildChildren(): List<Block> { return node.getChildren(null) .filter { !it.isWhitespaceOrEmpty() } .map { childNode: ASTNode -> TomlFormattingModelBuilder.createBlock( node = childNode, alignment = null, indent = computeIndent(childNode), wrap = null, ctx = ctx ) } } override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2, ctx) override fun getChildAttributes(newChildIndex: Int): ChildAttributes { val indent = when (node.elementType) { ARRAY -> Indent.getNormalIndent() else -> Indent.getNoneIndent() } return ChildAttributes(indent, null) } override fun isLeaf(): Boolean = node.firstChildNode == null override fun isIncomplete(): Boolean = myIsIncomplete private val myIsIncomplete: Boolean by lazy { FormatterUtil.isIncomplete(node) } override fun toString() = "${node.text} $textRange" }
apache-2.0
0069b7569c1b496a98b909e4d07aec43
33.825397
106
0.665907
4.589958
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/equipment/EquipmentDetailFragment.kt
1
3265
package com.habitrpg.android.habitica.ui.fragments.inventory.equipment import android.os.Bundle import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.inventory.Equipment import com.habitrpg.android.habitica.models.user.Items import com.habitrpg.android.habitica.ui.adapter.inventory.EquipmentRecyclerViewAdapter import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.fragments.inventory.customization.AvatarCustomizationFragmentArgs import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator import io.reactivex.functions.Consumer import io.realm.RealmResults import kotlinx.android.synthetic.main.fragment_recyclerview.* import javax.inject.Inject class EquipmentDetailFragment : BaseMainFragment() { @Inject lateinit var inventoryRepository: InventoryRepository var type: String? = null var equippedGear: String? = null var isCostume: Boolean? = null private var adapter: EquipmentRecyclerViewAdapter = EquipmentRecyclerViewAdapter(null, true) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val v = inflater.inflate(R.layout.fragment_recyclerview, container, false) this.adapter.equippedGear = this.equippedGear this.adapter.isCostume = this.isCostume this.adapter.type = this.type compositeSubscription.add(this.adapter.equipEvents.flatMapMaybe { key -> inventoryRepository.equipGear(user, key, isCostume ?: false).firstElement() } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) return v } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val args = EquipmentDetailFragmentArgs.fromBundle(it) type = args.type isCostume = args.isCostume equippedGear = args.equippedGear } recyclerView.adapter = this.adapter recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.addItemDecoration(DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL)) recyclerView.itemAnimator = SafeDefaultItemAnimator() type?.let { type -> inventoryRepository.getOwnedEquipment(type).firstElement().subscribe(Consumer<RealmResults<Equipment>> { this.adapter.updateData(it) }, RxErrorHandler.handleEmptyError()) } } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } }
gpl-3.0
9068ab4e29a37e4b5593ae154e1c92c5
42.121622
200
0.743645
4.992355
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/models/NumberOptionsTest.kt
1
2480
package com.kickstarter.models import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.NumberOptions import org.junit.Test import java.math.RoundingMode class NumberOptionsTest : KSRobolectricTestCase() { @Test fun testDefaultInit() { val numberOptions = NumberOptions.builder() .bucketAbove(3.2f) .bucketPrecision(10) .currencyCode("USD") .currencySymbol("$") .precision(12) .roundingMode(RoundingMode.HALF_UP) .build() assertEquals(numberOptions.bucketAbove(), 3.2f) assertEquals(numberOptions.bucketPrecision(), 10) assertEquals(numberOptions.currencyCode(), "USD") assertEquals(numberOptions.currencySymbol(), "$") assertEquals(numberOptions.precision(), 12) assertEquals(numberOptions.roundingMode(), RoundingMode.HALF_UP) } @Test fun testDefaultToBuilder() { val numberOptions = NumberOptions.builder().build().toBuilder().currencySymbol("$").build() assertEquals(numberOptions.currencySymbol(), "$") } @Test fun testNumberOptions_equalFalse() { val numberOptions = NumberOptions.builder().build() val numberOptions2 = NumberOptions.builder().bucketAbove(3.2f).build() val numberOptions3 = NumberOptions.builder().currencySymbol("$").currencyCode("USD").build() val numberOptions4 = NumberOptions.builder().precision(12).build() assertFalse(numberOptions == numberOptions2) assertFalse(numberOptions == numberOptions3) assertFalse(numberOptions == numberOptions4) assertFalse(numberOptions3 == numberOptions2) assertFalse(numberOptions3 == numberOptions4) } @Test fun testNumberOptions_equalTrue() { val numberOptions1 = NumberOptions.builder().build() val numberOptions2 = NumberOptions.builder().build() assertEquals(numberOptions1, numberOptions2) } @Test fun testNumberOptions_isCurrency() { val numberOptions1 = NumberOptions.builder().build() val numberOptions2 = NumberOptions.builder() .bucketAbove(3.2f) .bucketPrecision(10) .currencyCode("USD") .currencySymbol("$") .precision(12) .roundingMode(RoundingMode.HALF_UP) .build() assertFalse(numberOptions1.isCurrency) assertTrue(numberOptions2.isCurrency) } }
apache-2.0
d5212b395fdef6d0e0c84b71b5737bc6
32.972603
100
0.658871
4.732824
false
true
false
false
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/Assets.kt
1
2359
/* * Copyright 2014-2017 FuturemanGaming * * 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.futuremangaming.futurebot object Assets { val MUSIC_PLAYLIST_FOOTER: String? get() = System.getProperty("music.playlist.footer") val MUSIC_EMBED_COLOR: Int get() = Integer.decode(System.getProperty("music.embed.color", "0x50aace")) val TWITCH_URL: String? get() = System.getProperty("twitch.url") val TWITCH_FOOTER_ICON: String? get() = System.getProperty("twitch.footer.icon") val SOCIAL_MERCH: String? get() = System.getProperty("social.merch") val SOCIAL_TWITTER: String? get() = System.getProperty("social.twitter") val SOCIAL_YOUTUBE: String? get() = System.getProperty("social.youtube") val SOCIAL_TWITCH: String? get() = System.getProperty("social.twitch") val PAGES_NEXT: String? get() = System.getProperty("pages.next") val PAGES_PREV: String? get() = System.getProperty("pages.prev") val PAGES_LAST: String? get() = System.getProperty("pages.last") val PAGES_FIRST: String? get() = System.getProperty("pages.first") val all = mapOf( "music.playlist.footer" to MUSIC_PLAYLIST_FOOTER, "music.embed.color" to MUSIC_EMBED_COLOR, "twitch.url" to TWITCH_URL, "twitch.footer.icon" to TWITCH_FOOTER_ICON, "social.merch" to SOCIAL_MERCH, "social.twitter" to SOCIAL_TWITTER, "social.youtube" to SOCIAL_YOUTUBE, "social.twitch" to SOCIAL_TWITCH, "pages.next" to PAGES_NEXT, "pages.prev" to PAGES_PREV, "pages.last" to PAGES_LAST, "pages.first" to PAGES_FIRST ) init { val properties = System.getProperties() val stream = Assets::class.java.classLoader.getResourceAsStream("assets.properties") properties.load(stream) } }
apache-2.0
bc2d97480d2a463ee11ed1f6f93bc0da
39.689655
106
0.678677
3.72082
false
false
false
false
viartemev/requestmapper
src/test/kotlin/com/viartemev/requestmapper/annotations/jaxrs/GETSpek.kt
1
2766
package com.viartemev.requestmapper.annotations.jaxrs import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifierList import com.intellij.psi.PsiParameter import com.intellij.psi.PsiParameterList import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object GETSpek : Spek({ describe("GET") { context("values on annotation without anything") { val psiModifierList = mock<PsiModifierList> { on { annotations } doReturn emptyArray<PsiAnnotation>() } val psiParameterList = mock<PsiParameterList> { on { parameters } doReturn emptyArray<PsiParameter>() } val psiMethod = mock<PsiMethod> { on { modifierList } doReturn psiModifierList on { parameterList } doReturn psiParameterList } val annotation = mock<PsiAnnotation> { on { parent } doReturn psiMethod } val requestMapping = GET(annotation) it("should return one root mapping with default GET method") { requestMapping.values().size shouldBeEqualTo 1 requestMapping.values()[0].name shouldBeEqualTo "GET /" } } context("values on annotation with annotated class") { val psiParameterList = mock<PsiParameterList> { on { parameters } doReturn emptyArray<PsiParameter>() } val memberValue = mock<PsiAnnotationMemberValue> { on { text } doReturn "api" } val mappingAnnotation = mock<PsiAnnotation> { on { qualifiedName } doReturn "javax.ws.rs.Path" on { findAttributeValue("value") } doReturn memberValue } val psiModifierList = mock<PsiModifierList> { on { annotations } doReturn arrayOf(mappingAnnotation) } val psiMethod = mock<PsiMethod> { on { modifierList } doReturn psiModifierList on { parameterList } doReturn psiParameterList } val annotation = mock<PsiAnnotation> { on { parent } doReturn psiMethod } val requestMapping = GET(annotation) it("should return one class mapping with default GET method") { requestMapping.values().size shouldBeEqualTo 1 requestMapping.values()[0].name shouldBeEqualTo "GET /api" } } } })
mit
6d0f516af511319e1b736f46819a1b29
40.283582
75
0.614606
5.444882
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/util/QuadTree.kt
1
3621
package com.cout970.modeler.util /** * Created by cout970 on 2017/09/09. */ class QuadTree<T>(val depth: Int) { private var root: Node<T>? = null private var actual = false fun get(x: Int, y: Int): T? { var dep = depth var iter = root while (true) { if (iter == null) return null else if (iter is Node.Leaf) return iter.value iter = (iter as Node.Branch<T>).nodes[number(x, y, --dep)] } } fun set(x: Int, y: Int, value: T) { if (root == null) root = Node.Branch() if (root!!.set(x, y, value, depth - 1)) { root = Node.Leaf(value) } actual = false } override fun toString(): String = root.toString() sealed class Node<T> { abstract fun set(x: Int, y: Int, value: T, depth: Int): Boolean class Leaf<T>(var value: T) : Node<T>() { override fun set(x: Int, y: Int, value: T, depth: Int): Boolean { throw UnsupportedOperationException("set on Leaf element") } override fun toString(): String = "L{$value}" } class Branch<T>() : Node<T>() { constructor(value: T, exclude: Int) : this() { var i = 0 while (i < 4) { if (i != exclude) { nodes[i] = Leaf(value) } i++ } } private fun canClusterize(value: T): Boolean { var i = 0 while (i < 4) { val w = nodes[i] if (w == null || w !is Leaf || value != w.value) { return false } i++ } return true } override fun set(x: Int, y: Int, value: T, depth: Int): Boolean { val branchIndex = number(x, y, depth) val node = nodes[branchIndex] when (node) { null -> { if (depth == 0) { nodes[branchIndex] = Leaf(value) return canClusterize(value) } else { nodes[branchIndex] = Branch() } } is Leaf<T> -> { if (node.value == value) { return false } else if (depth == 0) { node.value = value return canClusterize(value) } nodes[branchIndex] = Branch(node.value, number(x, y, depth - 1)) } else -> Unit } if (nodes[branchIndex]!!.set(x, y, value, depth - 1)) { nodes[branchIndex] = Leaf(value) return canClusterize(value) } return false } val nodes = arrayOfNulls<Node<T>>(4) override fun toString(): String = nodes.joinToString(prefix = "[", postfix = "]") } } companion object { fun number(x: Int, y: Int, depth: Int): Int { val mask = 1 shl depth if (x and mask != 0) { if (y and mask != 0) { return 3 } return 2 } if (y and mask != 0) { return 1 } return 0 } } }
gpl-3.0
dfb8da51fd0fe42b382b436d19fe2f17
27.519685
93
0.389395
4.618622
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt
1
874
package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat class InputInsulin(injector: HasAndroidInjector) : Element(injector) { var value = 0.0 constructor(injector: HasAndroidInjector, another: InputInsulin) : this(injector) { value = another.value } override fun addToLayout(root: LinearLayout) { val numberPicker = NumberPicker(root.context, null) numberPicker.setParams(0.0, -20.0, 20.0, 0.1, DecimalFormat("0.0"), true, root.findViewById(R.id.ok)) numberPicker.value = value numberPicker.setOnValueChangedListener { value: Double -> this.value = value } root.addView(numberPicker) } }
agpl-3.0
d6dc5c9457f16d161f69d3c4b0d23320
37.043478
109
0.742563
4.305419
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/controller/usecases/Textures.kt
1
1380
package com.cout970.modeler.controller.usecases import com.cout970.modeler.api.model.IModel import com.cout970.modeler.controller.tasks.ITask import com.cout970.modeler.controller.tasks.TaskNone import com.cout970.modeler.controller.tasks.TaskUpdateModel import com.cout970.modeler.core.helpers.TransformationHelper import com.cout970.modeler.core.project.IProgramState @UseCase("model.texture.split") private fun splitTextures(model: IModel, state: IProgramState): ITask { val sel = state.textureSelection.getOrNull() ?: state.modelSelection.getOrNull() ?: return TaskNone val newModel = TransformationHelper.splitTextures(model, sel) return TaskUpdateModel(oldModel = model, newModel = newModel) } @UseCase("model.texture.scale.up") private fun scaleTexturesUp(accessor: IProgramState): ITask { val (model, sel) = accessor val selection = sel.getOrNull() ?: return TaskNone val newModel = TransformationHelper.scaleTextures(model, selection, 2f) return TaskUpdateModel(oldModel = model, newModel = newModel) } @UseCase("model.texture.scale.down") private fun scaleTexturesDown(accessor: IProgramState): ITask { val (model, sel) = accessor val selection = sel.getOrNull() ?: return TaskNone val newModel = TransformationHelper.scaleTextures(model, selection, 0.5f) return TaskUpdateModel(oldModel = model, newModel = newModel) }
gpl-3.0
02ef65904e4bcee43323376e3cc8531a
39.617647
103
0.77971
4.107143
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/JKElementInfoStorage.kt
2
2819
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.utils.SmartList import kotlin.random.Random interface JKElementInfo sealed class SuperFunctionInfo data class ExternalSuperFunctionInfo(val descriptor: FunctionDescriptor) : SuperFunctionInfo() data class InternalSuperFunctionInfo(val label: JKElementInfoLabel) : SuperFunctionInfo() data class FunctionInfo(val superFunctions: List<SuperFunctionInfo>) : JKElementInfo enum class JKTypeInfo(val unknownNullability: Boolean, val unknownMutability: Boolean) : JKElementInfo { KNOWN_NULLABILITY_KNOWN_MUTABILITY(false, false), UNKNOWN_NULLABILITY_KNOWN_MUTABILITY(true, false), KNOWN_NULLABILITY_UNKNOWN_MUTABILITY(false, true), UNKNOWN_NULLABILITY_UNKNOWN_MUTABILITY(true, true) ; companion object { operator fun invoke(unknownNullability: Boolean, unknownMutability: Boolean) = when { !unknownNullability && !unknownMutability -> KNOWN_NULLABILITY_KNOWN_MUTABILITY unknownNullability && !unknownMutability -> UNKNOWN_NULLABILITY_KNOWN_MUTABILITY !unknownNullability && unknownMutability -> KNOWN_NULLABILITY_UNKNOWN_MUTABILITY else -> UNKNOWN_NULLABILITY_UNKNOWN_MUTABILITY } } } inline class JKElementInfoLabel(val label: String) { fun render(): String = "/*@@$label@@*/" companion object { val LABEL_REGEX = """/\*@@(\w+)@@\*/""".toRegex() } } fun String.asLabel(): JKElementInfoLabel? = JKElementInfoLabel.LABEL_REGEX.matchEntire(this)?.groupValues?.getOrNull(1)?.let { JKElementInfoLabel(it) } class JKElementInfoStorage { private val labelToInfo = mutableMapOf<JKElementInfoLabel, MutableList<JKElementInfo>>() private val elementToLabel = mutableMapOf<Any, JKElementInfoLabel>() fun getOrCreateInfoForElement(element: Any): JKElementInfoLabel = elementToLabel.getOrPut(element) { JKElementInfoLabel(createRandomString()) } fun getInfoForLabel(label: JKElementInfoLabel): List<JKElementInfo>? = labelToInfo[label] fun addEntry(element: Any, info: JKElementInfo) { val label = elementToLabel.getOrPut(element) { JKElementInfoLabel(createRandomString()) } labelToInfo.getOrPut(label) { SmartList() } += info elementToLabel[element] = label } companion object { private val charPool = ('a'..'z').toList() private const val generatedStringLength = 6 private fun createRandomString() = (1..generatedStringLength).joinToString("") { charPool[Random.nextInt(0, charPool.size)].toString() } } }
apache-2.0
6f0367d230acd2691219db92e5e82fdc
39.285714
158
0.729691
4.546774
false
false
false
false
siosio/intellij-community
platform/statistics/devkit/testSrc/com/intellij/internal/statistic/actions/StatisticsEventLogToolWindowTest.kt
1
7369
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.actions import com.intellij.execution.process.ProcessOutputType import com.intellij.internal.statistic.eventLog.LogEvent import com.intellij.internal.statistic.eventLog.LogEventAction import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.ValidationResultType.* import com.intellij.internal.statistic.toolwindow.StatisticsEventLogFilter.Companion.LOG_PATTERN import com.intellij.internal.statistic.toolwindow.StatisticsEventLogMessageBuilder import com.intellij.internal.statistic.toolwindow.StatisticsEventLogToolWindow import com.intellij.internal.statistic.toolwindow.StatisticsLogFilterModel import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.text.DateFormatUtil import org.junit.Test class StatisticsEventLogToolWindowTest : BasePlatformTestCase() { private val eventId = "third.party" private val eventTime = 1564643114456 private val eventGroup = "toolwindow" private val groupVersion = "21" private val formattedEventTime = DateFormatUtil.formatTimeWithSeconds(eventTime) @Test fun testShortenProjectId() { val action = LogEventAction(eventId) val data = hashMapOf( "project" to "5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea", "plugin_type" to "PLATFORM" ) for ((key, value) in data) { action.addData(key, value) } doTestCountCollector("{\"plugin_type\":\"PLATFORM\", \"project\":\"5410c65e...ea\"}", action, data) } @Test fun testNotShortenProjectId() { val action = LogEventAction(eventId) val projectId = "12345" action.addData("project", projectId) doTestCountCollector("{\"project\":\"$projectId\"}", action, hashMapOf("project" to projectId)) } @Test fun testFilterSystemFields() { val action = LogEventAction(eventId) val data = hashMapOf( "last" to "1564643442610", "created" to "1564643442610" ) for ((key, value) in data) { action.addData(key, value) } doTestCountCollector("{}", action, data) } @Test fun testLogIncorrectEventIdAsError() { val incorrectEventId = INCORRECT_RULE.description val action = LogEventAction(incorrectEventId) val filterModel = StatisticsLogFilterModel() val logMessage = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap()) assertEquals("$formattedEventTime - [\"$eventGroup\", v$groupVersion]: \"$incorrectEventId[$eventId]\" {}", logMessage) val processingResult = filterModel.processLine(logMessage) assertEquals(processingResult.key, ProcessOutputType.STDERR) } @Test fun testLogIncorrectEventDataAsError() { val action = LogEventAction(eventId) action.addData("test", INCORRECT_RULE.description) action.addData("project", UNDEFINED_RULE.description) val filterModel = StatisticsLogFilterModel() val rawData = hashMapOf( "test" to "foo", "project" to "5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea" ) val logMessage = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, rawData) val expectedLine = buildExpectedLine( "{\"test\":\"validation.incorrect_rule[foo]\", \"project\":\"validation.undefined_rule[5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea]\"}") assertEquals(expectedLine, logMessage) val processingResult = filterModel.processLine(logMessage) assertEquals(processingResult.key, ProcessOutputType.STDERR) } @Test fun testLogIncorrectEventDataWithoutRawData() { val action = LogEventAction(eventId) action.addData("test", INCORRECT_RULE.description) action.addData("project", UNDEFINED_RULE.description) action.addData("map", hashMapOf("foo" to "bar")) action.addData("list", listOf("foo")) val filterModel = StatisticsLogFilterModel() val logMessage = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), null, null) val expectedLine = buildExpectedLine( "{\"test\":\"validation.incorrect_rule\", \"project\":\"validation.undefined_rule\", \"list\":[\"foo\"], \"map\":{\"foo\":\"bar\"}}") assertEquals(expectedLine, logMessage) val processingResult = filterModel.processLine(logMessage) assertEquals(processingResult.key, ProcessOutputType.STDERR) } @Test fun testAllValidationTypesUsed() { val correctValidationTypes = setOf(ACCEPTED, THIRD_PARTY) for (resultType in ValidationResultType.values()) { assertTrue("Don't forget to change toolWindow logic in case of a new value in ValidationResult", StatisticsEventLogToolWindow.rejectedValidationTypes.contains(resultType) || correctValidationTypes.contains(resultType)) } } @Test fun testHandleCollectionsInEventData() { val action = LogEventAction(eventId) action.addData("dataKey", listOf("1", "2", "3")) doTestCountCollector("{\"dataKey\":[\"1\",\"2\",\"3\"]}", action, hashMapOf("dataKey" to listOf("1", "2", "3"))) } @Test fun testLogCountCollectors() { val count = 2 val action = LogEventAction(eventId, false, count) val actual = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap()) assertEquals("$formattedEventTime - [\"$eventGroup\", v$groupVersion]: \"$eventId\" (count=${count}) {}", actual) } @Test fun testLogLineWithCountMatchesRegexpPattern() { val action = LogEventAction(eventId, false, 2) val logLineWithCount = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap()) val matcher = LOG_PATTERN.matcher(logLineWithCount) assertTrue(matcher.find()) assertEquals(eventGroup, matcher.group("groupId")) assertEquals(eventId, matcher.group("event")) assertEquals("{}", matcher.group("eventData")) } @Test fun testLogLineMatchesRegexpPattern() { val action = LogEventAction(eventId, true) action.addData("plugin_type", "PLATFORM") val logLineWithCount = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap()) val matcher = LOG_PATTERN.matcher(logLineWithCount) assertTrue(matcher.find()) assertEquals(eventGroup, matcher.group("groupId")) assertEquals(eventId, matcher.group("event")) assertEquals("{\"plugin_type\":\"PLATFORM\"}", matcher.group("eventData")) } private fun doTestCountCollector(expectedEventDataPart: String, action: LogEventAction, rawData: Map<String, Any> = emptyMap()) { val actual = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, rawData) assertEquals(buildExpectedLine(expectedEventDataPart), actual) } private fun buildExpectedLine(expectedEventDataPart: String) = "$formattedEventTime - [\"$eventGroup\", v$groupVersion]: \"$eventId\" $expectedEventDataPart" private fun buildLogEvent(action: LogEventAction, groupId: String = eventGroup) = LogEvent("2e5b2e32e061", "193.1801", "176", eventTime, groupId, groupVersion, "32", action) }
apache-2.0
39a2c4a9d0c8feda98fc8836e8170e7d
42.352941
163
0.735242
4.433815
false
true
false
false
bozaro/git-lfs-java
gitlfs-common/src/main/kotlin/ru/bozaro/gitlfs/common/data/LocksRes.kt
1
399
package ru.bozaro.gitlfs.common.data import com.fasterxml.jackson.annotation.JsonProperty class LocksRes( @field:JsonProperty(value = "locks", required = true) @param:JsonProperty(value = "locks", required = true) val locks: List<Lock>, @field:JsonProperty(value = "next_cursor") @param:JsonProperty(value = "next_cursor") val nextCursor: String? )
lgpl-3.0
d85f95e76a9a6982b39ede448a50e46c
32.25
61
0.671679
3.873786
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/note/recycler/NoteRecyclerItem.kt
1
2392
package com.maubis.scarlet.base.note.recycler import android.content.Context import androidx.core.content.ContextCompat import com.maubis.markdown.Markdown import com.maubis.scarlet.base.R import com.maubis.scarlet.base.core.note.getNoteState import com.maubis.scarlet.base.core.note.getReminderV2 import com.maubis.scarlet.base.database.room.note.Note import com.maubis.scarlet.base.note.adjustedColor import com.maubis.scarlet.base.note.getDisplayTime import com.maubis.scarlet.base.note.getImageFile import com.maubis.scarlet.base.note.getLockedAwareTextForHomeList import com.maubis.scarlet.base.note.getTagString import com.maubis.scarlet.base.settings.sheet.sNoteItemLineCount import com.maubis.scarlet.base.support.recycler.RecyclerItem import com.maubis.scarlet.base.support.ui.ColorUtil class NoteRecyclerItem(context: Context, val note: Note) : RecyclerItem() { val lineCount = sNoteItemLineCount val backgroundColor = note.adjustedColor() val isLightShaded = ColorUtil.isLightColored(backgroundColor) val description = note.getLockedAwareTextForHomeList() val descriptionColor = when (isLightShaded) { true -> ContextCompat.getColor(context, R.color.dark_tertiary_text) false -> ContextCompat.getColor(context, R.color.light_primary_text) } val state = note.getNoteState() val indicatorColor = when (isLightShaded) { true -> ContextCompat.getColor(context, R.color.dark_tertiary_text) false -> ContextCompat.getColor(context, R.color.light_tertiary_text) } val hasReminder = note.getReminderV2() !== null val actionBarIconColor = when (isLightShaded) { true -> ContextCompat.getColor(context, R.color.dark_secondary_text) false -> ContextCompat.getColor(context, R.color.light_secondary_text) } val tagsSource = note.getTagString() val tags = Markdown.renderSegment(tagsSource, true) val tagsColor = when (isLightShaded) { true -> ContextCompat.getColor(context, R.color.dark_tertiary_text) false -> ContextCompat.getColor(context, R.color.light_secondary_text) } val timestamp = note.getDisplayTime() val timestampColor = when (isLightShaded) { true -> ContextCompat.getColor(context, R.color.dark_hint_text) false -> ContextCompat.getColor(context, R.color.light_hint_text) } val imageSource = note.getImageFile() val disableBackup = note.disableBackup override val type = Type.NOTE }
gpl-3.0
c4fb2bc435f97fe2f5940f03f3045d98
38.866667
75
0.781773
3.796825
false
false
false
false
jwren/intellij-community
plugins/kotlin/compiler-plugins/compiler-plugin-support/common/src/org/jetbrains/kotlin/idea/compilerPlugin/idePluginUtils.kt
1
2806
// 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.compilerPlugin import com.intellij.openapi.module.Module import org.jetbrains.kotlin.idea.macros.KOTLIN_BUNDLED import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.facet.KotlinFacet import java.io.File fun Module.getSpecialAnnotations(prefix: String): List<String> { val kotlinFacet = KotlinFacet.get(this) ?: return emptyList() val commonArgs = kotlinFacet.configuration.settings.compilerArguments ?: return emptyList() return commonArgs.pluginOptions ?.filter { it.startsWith(prefix) } ?.map { it.substring(prefix.length) } ?: emptyList() } class CompilerPluginSetup(val options: List<PluginOption>, val classpath: List<String>) { class PluginOption(val key: String, val value: String) } fun File.toJpsVersionAgnosticKotlinBundledPath(): String { require(this.startsWith(KotlinArtifacts.instance.kotlincDirectory)) { "$this should start with ${KotlinArtifacts.instance.kotlincDirectory}" } return "\$$KOTLIN_BUNDLED\$/${this.relativeTo(KotlinArtifacts.instance.kotlincDirectory)}" } fun modifyCompilerArgumentsForPlugin( facet: KotlinFacet, setup: CompilerPluginSetup?, compilerPluginId: String, pluginName: String ) { val facetSettings = facet.configuration.settings // investigate why copyBean() sometimes throws exceptions val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl() /** See [CommonCompilerArguments.PLUGIN_OPTION_FORMAT] **/ val newOptionsForPlugin = setup?.options?.map { "plugin:$compilerPluginId:${it.key}=${it.value}" } ?: emptyList() val oldAllPluginOptions = (commonArguments.pluginOptions ?: emptyArray()).filterTo(mutableListOf()) { !it.startsWith("plugin:$compilerPluginId:") } val newAllPluginOptions = oldAllPluginOptions + newOptionsForPlugin val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) { val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar)) if (lastIndexOfFile < 0) { return@filterTo true } !it.drop(lastIndexOfFile + 1).matches("(kotlin-)?(maven-)?$pluginName-.*\\.jar".toRegex()) } val newPluginClasspaths = oldPluginClasspaths + (setup?.classpath ?: emptyList()) commonArguments.pluginOptions = newAllPluginOptions.toTypedArray() commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray() facetSettings.compilerArguments = commonArguments }
apache-2.0
dff84be74075cdcb916a96cfd44e172e
42.184615
158
0.747684
4.755932
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/EmptyRangeInspection.kt
1
2334
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.getArguments import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class EmptyRangeInspection : AbstractPrimitiveRangeToInspection() { override fun visitRangeToExpression(expression: KtExpression, holder: ProblemsHolder) { val (left, right) = expression.getArguments() ?: return val context = expression.analyze(BodyResolveMode.PARTIAL) val startValue = left?.longValueOrNull(context) ?: return val endValue = right?.longValueOrNull(context) ?: return if (startValue <= endValue) return holder.registerProblem( expression, KotlinBundle.message("this.range.is.empty.did.you.mean.to.use.downto"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceWithDownToFix() ) } class ReplaceWithDownToFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.down.to.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtExpression ?: return val (left, right) = element.getArguments() ?: return if (left == null || right == null) return element.replace(KtPsiFactory(element).createExpressionByPattern("$0 downTo $1", left, right)) } } private fun KtExpression.longValueOrNull(context: BindingContext): Long? { return (constantValueOrNull(context)?.value as? Number)?.toLong() } }
apache-2.0
7dea7fbda940dc9c494f7a1083be58d7
42.240741
158
0.739075
4.812371
false
false
false
false
kunalkanojia/tasks-teamcity-plugin
tasks-teamcity-plugin-agent/src/main/kotlin/org/kkanojia/tasks/teamcity/agent/AbstractBuildProcessAdapter.kt
1
1849
package org.kkanojia.tasks.teamcity.agent import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.BuildFinishedStatus import jetbrains.buildServer.agent.BuildProcessAdapter import jetbrains.buildServer.agent.BuildProgressLogger import jetbrains.buildServer.log.Loggers abstract class AbstractBuildProcessAdapter protected constructor(protected val progressLogger: BuildProgressLogger) : BuildProcessAdapter() { @Volatile private var isFinished: Boolean = false @Volatile private var isFailed: Boolean = false @Volatile private var isInterrupted: Boolean = false init { isFinished = false isFailed = false isInterrupted = false } override fun interrupt() { isInterrupted = true } override fun isInterrupted(): Boolean { return isInterrupted } override fun isFinished(): Boolean { return isFinished } @Throws(RunBuildException::class) override fun waitFor(): BuildFinishedStatus { while (!isInterrupted && !isFinished) { try { Thread.sleep(1000) } catch (e: InterruptedException) { throw RunBuildException(e) } } return if (isFinished){ if (isFailed) BuildFinishedStatus.FINISHED_FAILED else BuildFinishedStatus.FINISHED_SUCCESS } else BuildFinishedStatus.INTERRUPTED } @Throws(RunBuildException::class) override fun start() { try { runProcess() } catch (e: RunBuildException) { progressLogger.buildFailureDescription(e.message) Loggers.AGENT.error(e) isFailed = true } finally { isFinished = true } } @Throws(RunBuildException::class) protected abstract fun runProcess() }
mit
9e64d66a1235923749df9b6b3e5e84d6
27.461538
141
0.658734
5.375
false
false
false
false
sksamuel/ktest
kotest-runner/kotest-runner-junit5/src/jvmMain/kotlin/io/kotest/runner/junit/platform/descriptors.kt
1
6819
package io.kotest.runner.junit.platform import io.kotest.core.internal.KotestEngineProperties import io.kotest.core.plan.Descriptor import io.kotest.core.plan.DisplayName import io.kotest.core.test.Description import io.kotest.core.spec.Spec import io.kotest.core.spec.toDescription import io.kotest.core.test.TestCase import io.kotest.core.test.TestType import org.junit.platform.engine.TestDescriptor import org.junit.platform.engine.TestSource import org.junit.platform.engine.UniqueId import org.junit.platform.engine.support.descriptor.AbstractTestDescriptor import org.junit.platform.engine.support.descriptor.ClassSource import org.junit.platform.engine.support.descriptor.FilePosition import org.junit.platform.engine.support.descriptor.FileSource import org.junit.platform.engine.support.descriptor.MethodSource import java.io.File import kotlin.reflect.KClass fun engineId(): UniqueId = UniqueId.forEngine("kotest") /** * Returns a new [UniqueId] by appending this description to the receiver. */ fun UniqueId.append(description: Description): UniqueId { val segment = when (description) { is Description.Spec -> Segment.Spec is Description.Test -> Segment.Test } return this.append(segment.value, description.displayName()) } sealed class Segment { abstract val value: String object Spec : Segment() { override val value: String = "spec" } object Script : Segment() { override val value: String = "script" } object Test : Segment() { override val value: String = "test" } } /** * Creates a new spec-level [TestDescriptor] from the given class, appending it to the * parent [TestDescriptor]. The created descriptor will have segment type [Segment.Spec]. */ fun KClass<out Spec>.descriptor(parent: TestDescriptor): TestDescriptor { val source = ClassSource.from(java) return parent.append(toDescription(), TestDescriptor.Type.CONTAINER, source, Segment.Spec) } /** * Creates a new spec-level [TestDescriptor] from the given spec name, appending it to the * parent [TestDescriptor]. The created descriptor will have segment type [Segment.Spec]. */ fun Descriptor.SpecDescriptor.descriptor(parent: TestDescriptor): TestDescriptor { val source = ClassSource.from(this.classname ?: "") return parent.append(displayName.value, TestDescriptor.Type.CONTAINER, source, Segment.Script) } /** * Creates a [TestDescriptor] for the given [TestCase] and attaches it to the receiver as a child. * The created descriptor will have segment type [Segment.Test]. */ fun TestDescriptor.descriptor(testCase: TestCase): TestDescriptor { val pos = if (testCase.source.lineNumber <= 0) null else FilePosition.from(testCase.source.lineNumber) val source = FileSource.from(File(testCase.source.fileName), pos) // there is a bug in gradle 4.7+ whereby CONTAINER_AND_TEST breaks test reporting or hangs the build, as it is not handled // see https://github.com/gradle/gradle/issues/4912 // so we can't use CONTAINER_AND_TEST for our test scopes, but simply container // update jan 2020: Seems we can use CONTAINER_AND_TEST now in gradle 6, and CONTAINER is invisible in output val type = when (testCase.type) { TestType.Container -> if (System.getProperty(KotestEngineProperties.gradle5) == "true") TestDescriptor.Type.CONTAINER else TestDescriptor.Type.CONTAINER_AND_TEST TestType.Test -> TestDescriptor.Type.TEST } return append(testCase.description, type, source, Segment.Test) } /** * Creates a [TestDescriptor] for the given [Descriptor.TestDescriptor] and attaches it to the receiver as a child. * The created descriptor will have segment type [Segment.Test]. */ fun TestDescriptor.descriptor(desc: Descriptor.TestDescriptor): TestDescriptor { val source = FileSource.from(File(desc.source.filename), FilePosition.from(desc.source.lineNumber)) // there is a bug in gradle 4.7+ whereby CONTAINER_AND_TEST breaks test reporting or hangs the build, as it is not handled // see https://github.com/gradle/gradle/issues/4912 // so we can't use CONTAINER_AND_TEST for our test scopes, but simply container // update jan 2020: Seems we can use CONTAINER_AND_TEST now in gradle 6, and CONTAINER is invisible in output val type = when (desc.type) { TestType.Container -> if (System.getProperty(KotestEngineProperties.gradle5) == "true") TestDescriptor.Type.CONTAINER else TestDescriptor.Type.CONTAINER_AND_TEST TestType.Test -> TestDescriptor.Type.TEST } return append(desc.displayName, type, source, Segment.Test) } /** * Creates a new [TestDescriptor] appended to the receiver and adds it as a child of the receiver. */ fun TestDescriptor.append( description: Description, type: TestDescriptor.Type, source: TestSource?, segment: Segment ): TestDescriptor = append( description.displayName(), type, source, segment ) /** * Creates a new [TestDescriptor] appended to the receiver and adds it as a child of the receiver. */ fun TestDescriptor.append( displayName: DisplayName, type: TestDescriptor.Type, source: TestSource?, segment: Segment ): TestDescriptor = append( displayName.value, type, source, segment ) /** * Creates a new [TestDescriptor] appended to the receiver and adds it as a child of the receiver. */ fun TestDescriptor.append( name: String, type: TestDescriptor.Type, source: TestSource?, segment: Segment ): TestDescriptor { val descriptor = object : AbstractTestDescriptor(this.uniqueId.append(segment.value, name), name, source) { override fun getType(): TestDescriptor.Type = type override fun mayRegisterTests(): Boolean = type != TestDescriptor.Type.TEST } this.addChild(descriptor) return descriptor } /** * Returns a new [TestDescriptor] created from this [Description]. * The [TestSource] is fudged since JUnit makes assumptions that tests are methods. */ fun Description.toTestDescriptor(root: UniqueId): TestDescriptor { val id = this.chain().fold(root) { acc, op -> acc.append(op) } val source = when (this) { is Description.Spec -> ClassSource.from(this.kclass.java) // this isn't a method, but we can use MethodSource with the test name so it's at least // compatible for top level tests. is Description.Test -> MethodSource.from(this.spec().kclass.java.name, this.testPath().value) } val type = when (this) { is Description.Spec -> TestDescriptor.Type.CONTAINER is Description.Test -> when (this.type) { TestType.Container -> TestDescriptor.Type.CONTAINER TestType.Test -> TestDescriptor.Type.TEST } } return object : AbstractTestDescriptor(id, this.displayName(), source) { override fun getType(): TestDescriptor.Type = type } }
mit
3ef362c8b903fd3057ee740828cf0f3b
36.674033
167
0.737205
4.180871
false
true
false
false
mapzen/eraser-map
app/src/test/kotlin/com/mapzen/erasermap/controller/TestMainController.kt
1
10656
package com.mapzen.erasermap.controller import com.mapzen.android.lost.api.Status import com.mapzen.model.ValhallaLocation import com.mapzen.pelias.SimpleFeature import com.mapzen.pelias.gson.Feature import com.mapzen.tangram.LngLat import com.mapzen.tangram.MapController import com.mapzen.valhalla.Route class TestMainController : MainViewController { var searchResults: List<Feature>? = null var reverseGeoCodeResults: List<Feature>? = null var lngLat: LngLat? = null var zoom: Float = 0f var mapzenStyle: String = "" var tilt: Float = 0f var muted: Boolean = false var rotation: Float = 0f var routeLine: Route? = null var queryText: String = "" var reverseGeolocatePoint: LngLat? = null var placeSearchPoint: LngLat? = null var isProgressVisible: Boolean = false var isViewAllVisible: Boolean = false var isSearchVisible: Boolean = false var isRoutePreviewDestinationVisible: Boolean = false var isDirectionListVisible: Boolean = false var isRoutingModeVisible: Boolean = false var isSettingsVisible: Boolean = false var isFindMeTrackingEnabled: Boolean = false var popBackStack: Boolean = false var routeRequestCanceled: Boolean = false var isNew: Boolean = false var isCurrentLocationEnabled: Boolean = false var isAttributionAboveOptions = false var isFindMeAboveOptions = false var isRouting = false var isRouteBtnVisibleAndMapCentered = false var isOptionsMenuIconList = false var isShowingSearchResultsList = false var settingsApiTriggered: Boolean = false var isActionBarHidden = false var isRoutePreviewVisible: Boolean = false var isRoutePreviewDistanceTieVisible = false var routePreviewRoute: Route? = null var routePinLocations: Array<ValhallaLocation>? = null var isVoiceNavigationStopped = false var isRouteIconVisible = true var isRouteModeViewVisible = true var isRoutePreviewViewVisible = true var mapHasPanResponder = true var mapCameraType = MapController.CameraType.PERSPECTIVE var routePinsVisible = true var isAttributionAboveSearchResults = false var isFindMeAboveSearchResults = false var currentSearchItemPosition = 0 var currentSearchIndex = 0 var toastifyResId = 0 var focusSearchView = false var debugSettingsEnabled = false var compassRotated = false var compassShowing = false var reverseGeoPointOnMap: LngLat? = null var searchResultsViewHidden = false var attributionAlignedBottom = false var placeSearchResults: List<Feature>? = null var searchResultsPoints: List<LngLat>? = null var searchResultsCleared = false var speakerStopped = false var screenPosLngLat: LngLat? = null override fun showSearchResultsView(features: List<Feature>) { searchResultsViewHidden = false searchResults = features } override fun clearSearchResults() { searchResultsCleared = true searchResultsPoints = null } override fun drawSearchResults(points: List<LngLat>, activeIndex: Int) { searchResultsPoints = points currentSearchIndex = activeIndex } override fun hideSearchResults() { searchResults = null } override fun hideReverseGeolocateResult() { reverseGeoCodeResults = null } override fun showProgress() { isProgressVisible = true } override fun hideProgress() { isProgressVisible = false } override fun showActionViewAll() { isViewAllVisible = true } override fun hideActionViewAll() { isViewAllVisible = false } override fun toggleShowAllSearchResultsList(features: List<Feature>?) { } override fun collapseSearchView() { isSearchVisible = false } override fun expandSearchView() { } override fun clearQuery() { queryText = "" } override fun showRoutePreviewDestination(destination: SimpleFeature) { isRoutePreviewDestinationVisible = true } override fun route() { isRouting = true } override fun shutDown() { } override fun showDirectionsList() { isDirectionListVisible = true } override fun hideDirectionsList() { isDirectionListVisible = false } override fun hideRoutingMode() { isRoutingModeVisible = false } override fun startRoutingMode(feature: Feature, isNew: Boolean) { isRoutingModeVisible = true this.isNew = isNew } override fun resumeRoutingMode(feature: Feature) { isRoutingModeVisible = true } override fun resumeRoutingModeForMap() { isRouteBtnVisibleAndMapCentered = true } override fun centerMapOnLocation(lngLat: LngLat, zoom: Float) { this.lngLat = lngLat this.zoom = zoom } override fun setMapTilt(radians: Float) { tilt = radians } override fun resetMute() { muted = false } override fun toggleMute() { muted = !muted } override fun setMapRotation(radians: Float) { rotation = radians } // override fun showReverseGeocodeFeature(features: List<Feature>?) { // isReverseGeocodeVisible = true // reverseGeoCodeResults = features; // } override fun showPlaceSearchFeature(features: List<Feature>) { placeSearchResults = features // showReverseGeocodeFeature(features) } override fun drawRoute(route: Route) { routeLine = route } override fun clearRoute() { routeLine = null } override fun rotateCompass() { compassRotated = true } override fun showCompass() { compassShowing = true } override fun reverseGeolocate(screenX: Float, screenY: Float) { reverseGeolocatePoint = LngLat(screenX.toDouble(), screenY.toDouble()) } override fun placeSearch(gid: String) { placeSearchPoint = LngLat(0.0, 0.0) } // override fun emptyPlaceSearch() { // isReverseGeocodeVisible = true // } // override fun overridePlaceFeature(feature: Feature) { // isPlaceResultOverridden = true // } // override fun drawTappedPoiPin() { // //empty // } override fun hideSettingsBtn() { isSettingsVisible = false } override fun showSettingsBtn() { isSettingsVisible = true } override fun onBackPressed() { popBackStack = true } override fun stopSpeaker() { speakerStopped = true } override fun checkPermissionAndEnableLocation() { } override fun executeSearch(query: String) { queryText = query } override fun deactivateFindMeTracking() { isFindMeTrackingEnabled = false } override fun cancelRouteRequest() { routeRequestCanceled = true } override fun layoutAttributionAboveOptions() { isAttributionAboveOptions = true } override fun layoutFindMeAboveOptions() { isFindMeAboveOptions = true } override fun restoreRoutePreviewButtons() { } override fun onCloseAllSearchResultsList() { } override fun handleLocationResolutionRequired(status: Status) { settingsApiTriggered = true } override fun setMyLocationEnabled(enabled: Boolean) { isCurrentLocationEnabled = enabled } override fun setOptionsMenuIconToList() { isOptionsMenuIconList = true } override fun onShowAllSearchResultsList(features: List<Feature>) { isShowingSearchResultsList = true } override fun hideActionBar() { isActionBarHidden = true } override fun showRoutePreviewView() { isRoutePreviewVisible = true } override fun showRoutePreviewDistanceTimeLayout() { isRoutePreviewDistanceTieVisible = true } override fun setRoutePreviewViewRoute(route: Route) { routePreviewRoute = route } override fun showRoutePinsOnMap(locations: Array<ValhallaLocation>) { routePinLocations = locations } override fun updateRoutePreviewStartNavigation() { } override fun stopVoiceNavigationController() { isVoiceNavigationStopped = true } override fun hideRouteIcon() { isRouteIconVisible = false } override fun hideRouteModeView() { isRouteModeViewVisible = false } override fun showActionBar() { isActionBarHidden = false } override fun hideRoutePreviewView() { isRoutePreviewViewVisible = false } override fun resetMapPanResponder() { mapHasPanResponder = false } override fun setDefaultCamera() { mapCameraType = MapController.CameraType.ISOMETRIC } override fun layoutFindMeAlignBottom() { isFindMeAboveOptions = false } override fun hideMapRoutePins() { routePinsVisible = false } override fun layoutAttributionAboveSearchResults(features: List<Feature>) { isAttributionAboveSearchResults = true } override fun layoutFindMeAboveSearchResults(features: List<Feature>) { isFindMeAboveSearchResults = true } override fun setCurrentSearchItem(position: Int) { currentSearchItemPosition = position } override fun setMapPosition(lngLat: LngLat, duration: Int) { this.lngLat = lngLat } override fun setMapZoom(zoom: Float) { this.zoom = zoom } override fun setMapStyle(styleKey: String) { this.mapzenStyle = styleKey } override fun getCurrentSearchPosition(): Int { return currentSearchItemPosition } override fun toastify(resId: Int) { toastifyResId = resId } override fun focusSearchView() { focusSearchView = true } override fun toggleShowDebugSettings() { debugSettingsEnabled = !debugSettingsEnabled } override fun getMapPosition(): LngLat? { return lngLat } override fun getMapZoom(): Float? { return zoom } override fun showReverseGeoResult(lngLat: LngLat?) { reverseGeoPointOnMap = lngLat } override fun screenPositionToLngLat(x: Float, y: Float): LngLat? { if (screenPosLngLat != null) { return screenPosLngLat } return LngLat(0.0, 0.0) } override fun hideSearchResultsView() { searchResultsViewHidden = true } override fun layoutAttributionAlignBottom() { attributionAlignedBottom = true } override fun setMapZoom(zoom: Float, duration: Int) { this.zoom = zoom } }
gpl-3.0
ba8b630a129e5978e36ad38a80e8a058
24.191489
79
0.672673
4.651244
false
false
false
false
Commit451/Addendum
app/src/main/java/com/commit451/addendum/sample/MainActivity.kt
1
1792
package com.commit451.addendum.sample import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.view.* import com.commit451.addendum.bindView import com.commit451.addendum.getIntExtra import com.commit451.addendum.threetenabp.toDateAtStartOfDay import com.commit451.addendum.updateMargins import com.google.android.material.bottomnavigation.BottomNavigationView import org.threeten.bp.LocalDate import timber.log.Timber class MainActivity : AppCompatActivity() { val root by bindView<ViewGroup>(R.id.root) val buttonSecondActivity by bindView<Button>(R.id.buttonSecondActivity) val bottomNavigationView by bindView<BottomNavigationView>(R.id.bottomNavigationView) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val value = intent.getIntExtra("some_key") Timber.d("value $value") buttonSecondActivity.setOnClickListener { val intent = Main2Activity.intent(this) startActivity(intent) } root.forEach { view: View -> Timber.d("For each - view: $view") } root.forEachIndexed { i: Int, view: View -> Timber.d("For each indexed - view: $view index: $i") } val today = LocalDate.now() val date = today.toDateAtStartOfDay() root.doOnLayout { Timber.d("onGlobalLayout width: ${root.width}") } root.doOnPreDraw { Timber.d("onPreDraw width: ${root.width}") } buttonSecondActivity.updateMargins(top = 400) buttonSecondActivity.updatePadding(left = 200) } }
apache-2.0
0e866360aabd06f9c44685755bd6ac54
31
89
0.697545
4.548223
false
false
false
false
marktony/ZhiHuDaily
app/src/androidTest/java/com/marktony/zhihudaily/database/ZhihuDailyNewsDaoTest.kt
1
6967
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.database import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.marktony.zhihudaily.data.ZhihuDailyNewsQuestion import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ZhihuDailyNewsDaoTest { private lateinit var database: AppDatabase companion object { private val DEFAULT_IMAGES: List<String> = listOf("https:\\/pic1.zhimg.com\\/v2-5c5f75baa911c58f2476334180f5cda0.jpg") private val DEFAULT_TYPE: Int = 0 private val DEFAULT_ID: Int = 9683773 private val DEFAULT_GA_PREFIX: String = "052422" private val DEFAULT_TITLE: String = "小事 · 直到麻木了,就到了要走的时候" private val DEFAULT_IS_FAVORITE: Boolean = false private val DEFAULT_TIMESTAMP: Long = 1527333963L private val DEFAULT_ZHIHU_DAILY_NEWS_STORY = ZhihuDailyNewsQuestion(DEFAULT_IMAGES, DEFAULT_TYPE, DEFAULT_ID, DEFAULT_GA_PREFIX, DEFAULT_TITLE, DEFAULT_IS_FAVORITE, DEFAULT_TIMESTAMP) private val NEW_IS_FAVORITE = true private val NEW_TIMESTAMP = 1527337920L } @Before fun initDb() { // using an in-memory database because the information stored here disappears when the // process is killed database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), AppDatabase::class.java).build() } @After fun closeDb() = database.close() @Test fun insertZhihuDailyNewsAndGetById() { // When inserting a zhihu daily news story database.zhihuDailyNewsDao().insertAll(listOf(DEFAULT_ZHIHU_DAILY_NEWS_STORY)) // When getting the zhihu daily news story by id from the database val loaded = database.zhihuDailyNewsDao().queryItemById(DEFAULT_ZHIHU_DAILY_NEWS_STORY.id) // The loaded data contains the expected values assertItem(loaded, DEFAULT_IMAGES, DEFAULT_TYPE, DEFAULT_ID, DEFAULT_GA_PREFIX, DEFAULT_TITLE, DEFAULT_IS_FAVORITE, DEFAULT_TIMESTAMP) } @Test fun insertItemIgnoredOnConflict() { // Given that a zhihu daily news story is inserted database.zhihuDailyNewsDao().insertAll(listOf(DEFAULT_ZHIHU_DAILY_NEWS_STORY)) // When a zhihu daily news with the same id is inserted val newZhihuDailyNewsStory = ZhihuDailyNewsQuestion(DEFAULT_IMAGES, DEFAULT_TYPE, DEFAULT_ID, DEFAULT_GA_PREFIX, DEFAULT_TITLE, NEW_IS_FAVORITE, DEFAULT_TIMESTAMP) database.zhihuDailyNewsDao().insertAll(listOf(newZhihuDailyNewsStory)) // When getting the zhihu daily news story by id from the database val loaded = database.zhihuDailyNewsDao().queryItemById(DEFAULT_ID) // The loaded data contains the expected values assertItem(loaded, DEFAULT_IMAGES, DEFAULT_TYPE, DEFAULT_ID, DEFAULT_GA_PREFIX, DEFAULT_TITLE, DEFAULT_IS_FAVORITE, DEFAULT_TIMESTAMP) } @Test fun updateItemAndGetById() { // When inserting a zhihu daily news story database.zhihuDailyNewsDao().insertAll(listOf(DEFAULT_ZHIHU_DAILY_NEWS_STORY)) // When the zhihu daily news story is updated val updatedItem = ZhihuDailyNewsQuestion(DEFAULT_IMAGES, DEFAULT_TYPE, DEFAULT_ID, DEFAULT_GA_PREFIX, DEFAULT_TITLE, NEW_IS_FAVORITE, DEFAULT_TIMESTAMP) database.zhihuDailyNewsDao().update(updatedItem) val loaded = database.zhihuDailyNewsDao().queryItemById(DEFAULT_ID) // The loaded data contains the expected values assertItem(loaded, DEFAULT_IMAGES, DEFAULT_TYPE, DEFAULT_ID, DEFAULT_GA_PREFIX, DEFAULT_TITLE, NEW_IS_FAVORITE, DEFAULT_TIMESTAMP) } @Test fun favoriteItemByIdAndGettingFavorites() { // When inserting a zhihu daily news story database.zhihuDailyNewsDao().insertAll(listOf(DEFAULT_ZHIHU_DAILY_NEWS_STORY)) // Query all the favorites val stories = database.zhihuDailyNewsDao().queryAllFavorites() assertThat(stories.size, `is`(0)) // Favorite one item database.zhihuDailyNewsDao().queryItemById(DEFAULT_ID)?.let { it.isFavorite = true database.zhihuDailyNewsDao().update(it) } // The list size is 1 val newStories = database.zhihuDailyNewsDao().queryAllFavorites() assertThat(newStories.size, `is`(1)) } @Test fun insertAndGettingTimeoutItems() { // Given a zhihu daily news story inserted database.zhihuDailyNewsDao().insertAll(listOf(DEFAULT_ZHIHU_DAILY_NEWS_STORY)) // when querying the timeout stories by timestamp val stories = database.zhihuDailyNewsDao().queryAllTimeoutItems(NEW_TIMESTAMP) // The list size is 1 assertThat(stories.size, `is`(1)) } @Test fun deleteItemAndGettingItems() { // Given a zhihu daily news story inserted database.zhihuDailyNewsDao().insertAll(listOf(DEFAULT_ZHIHU_DAILY_NEWS_STORY)) // When deleting a zhihu daily news story by id database.zhihuDailyNewsDao().delete(DEFAULT_ZHIHU_DAILY_NEWS_STORY) // When getting the zhihu daily news stories val stories = database.zhihuDailyNewsDao().queryAllByDate(DEFAULT_TIMESTAMP) // The list is empty assertThat(stories.size, `is`(0)) } // Assert a zhihu daily news story private fun assertItem(item: ZhihuDailyNewsQuestion?, images: List<String>, type: Int, id: Int, gaPrefix: String, title: String, isFavorite: Boolean, timestamp: Long) { assertThat<ZhihuDailyNewsQuestion>(item as ZhihuDailyNewsQuestion, notNullValue()) assertThat(item.images, `is`(images)) assertThat(item.type, `is`(type)) assertThat(item.id, `is`(id)) assertThat(item.gaPrefix, `is`(gaPrefix)) assertThat(item.title, `is`(title)) assertThat(item.isFavorite, `is`(isFavorite)) assertThat(item.timestamp, `is`(timestamp)) } }
apache-2.0
058ac963c922bde01df5b86c5224ea27
39.794118
191
0.689645
4.235797
false
true
false
false
elpassion/el-abyrinth-android
app/src/main/java/pl/elpassion/elabyrinth/DirectionDispatcher.kt
1
1120
package pl.elpassion.elabyrinth import android.view.MotionEvent import android.view.View import pl.elpassion.elabyrinth.core.Direction import pl.elpassion.elabyrinth.core.Direction.* class DirectionDispatcher(val directionListener: (Direction) -> Unit) : View.OnTouchListener { var startX: Float = 0f var startY: Float = 0f override fun onTouch(v: View?, event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_DOWN) { saveStartPosition(event) } if (event.action == MotionEvent.ACTION_UP) { emitDirection(event) } return true } private fun saveStartPosition(event: MotionEvent) { startX = event.x; startY = event.y; } private fun emitDirection(event: MotionEvent) { val dx = event.x - startX; val dy = event.y - startY; if (Math.abs(dx) > Math.abs(dy)) { if (dx > 0) directionListener(RIGHT) else directionListener(LEFT) } else { if (dy > 0) directionListener(DOWN) else directionListener(UP) } } }
mit
8c31c5c504c91609f3bc96d0c166b356
27
94
0.617857
4.028777
false
false
false
false
Bambooin/trime
app/src/main/java/com/osfans/trime/util/InputMethodUtils.kt
2
1484
package com.osfans.trime.util import android.content.ComponentName import android.content.Context import android.content.Intent import android.provider.Settings import android.view.inputmethod.InputMethodManager import com.osfans.trime.TrimeImeService import timber.log.Timber object InputMethodUtils { private val serviceName = ComponentName(appContext, TrimeImeService::class.java).flattenToShortString() fun checkIsTrimeEnabled(): Boolean { val activeImeIds = Settings.Secure.getString( appContext.contentResolver, Settings.Secure.ENABLED_INPUT_METHODS ) ?: "(none)" Timber.i("List of active IMEs: $activeImeIds") return activeImeIds.split(":").contains(serviceName) } fun checkIsTrimeSelected(): Boolean { val selectedImeIds = Settings.Secure.getString( appContext.contentResolver, Settings.Secure.DEFAULT_INPUT_METHOD ) ?: "(none)" Timber.i("Selected IME: $selectedImeIds") return selectedImeIds == serviceName } fun showImeEnablerActivity(context: Context) = context.startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)) fun showImePicker(context: Context): Boolean { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager return if (imm != null) { imm.showInputMethodPicker() true } else { false } } }
gpl-3.0
c6386c0f8d19fa17496fd7e38aa30e30
31.26087
95
0.682615
4.623053
false
false
false
false
solokot/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/EditActivity.kt
1
33672
package com.simplemobiletools.gallery.pro.activities import android.annotation.TargetApi import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat import android.graphics.Color import android.graphics.Point import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.provider.MediaStore import android.view.Menu import android.view.MenuItem import android.widget.RelativeLayout import androidx.exifinterface.media.ExifInterface import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.simplemobiletools.commons.dialogs.ColorPickerDialog import com.simplemobiletools.commons.dialogs.ConfirmationDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.REAL_FILE_PATH import com.simplemobiletools.commons.helpers.ensureBackgroundThread import com.simplemobiletools.commons.helpers.isNougatPlus import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.gallery.pro.BuildConfig import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.adapters.FiltersAdapter import com.simplemobiletools.gallery.pro.dialogs.OtherAspectRatioDialog import com.simplemobiletools.gallery.pro.dialogs.ResizeDialog import com.simplemobiletools.gallery.pro.dialogs.SaveAsDialog import com.simplemobiletools.gallery.pro.extensions.config import com.simplemobiletools.gallery.pro.extensions.copyNonDimensionAttributesTo import com.simplemobiletools.gallery.pro.extensions.fixDateTaken import com.simplemobiletools.gallery.pro.extensions.openEditor import com.simplemobiletools.gallery.pro.helpers.* import com.simplemobiletools.gallery.pro.models.FilterItem import com.theartofdev.edmodo.cropper.CropImageView import com.zomato.photofilters.FilterPack import com.zomato.photofilters.imageprocessors.Filter import kotlinx.android.synthetic.main.activity_edit.* import kotlinx.android.synthetic.main.bottom_actions_aspect_ratio.* import kotlinx.android.synthetic.main.bottom_editor_actions_filter.* import kotlinx.android.synthetic.main.bottom_editor_crop_rotate_actions.* import kotlinx.android.synthetic.main.bottom_editor_draw_actions.* import kotlinx.android.synthetic.main.bottom_editor_primary_actions.* import java.io.* class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener { companion object { init { System.loadLibrary("NativeImageProcessor") } } private val TEMP_FOLDER_NAME = "images" private val ASPECT_X = "aspectX" private val ASPECT_Y = "aspectY" private val CROP = "crop" // constants for bottom primary action groups private val PRIMARY_ACTION_NONE = 0 private val PRIMARY_ACTION_FILTER = 1 private val PRIMARY_ACTION_CROP_ROTATE = 2 private val PRIMARY_ACTION_DRAW = 3 private val CROP_ROTATE_NONE = 0 private val CROP_ROTATE_ASPECT_RATIO = 1 private lateinit var saveUri: Uri private var uri: Uri? = null private var resizeWidth = 0 private var resizeHeight = 0 private var drawColor = 0 private var lastOtherAspectRatio: Pair<Float, Float>? = null private var currPrimaryAction = PRIMARY_ACTION_NONE private var currCropRotateAction = CROP_ROTATE_ASPECT_RATIO private var currAspectRatio = ASPECT_RATIO_FREE private var isCropIntent = false private var isEditingWithThirdParty = false private var isSharingBitmap = false private var wasDrawCanvasPositioned = false private var oldExif: ExifInterface? = null private var filterInitialBitmap: Bitmap? = null private var originalUri: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit) if (checkAppSideloading()) { return } initEditActivity() } override fun onResume() { super.onResume() isEditingWithThirdParty = false bottom_draw_width.setColors(config.textColor, getAdjustedPrimaryColor(), config.backgroundColor) } override fun onStop() { super.onStop() if (isEditingWithThirdParty) { finish() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_editor, menu) updateMenuItemColors(menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.save_as -> saveImage() R.id.edit -> editWith() R.id.share -> shareImage() else -> return super.onOptionsItemSelected(item) } return true } private fun initEditActivity() { if (intent.data == null) { toast(R.string.invalid_image_path) finish() return } uri = intent.data!! originalUri = uri if (uri!!.scheme != "file" && uri!!.scheme != "content") { toast(R.string.unknown_file_location) finish() return } if (intent.extras?.containsKey(REAL_FILE_PATH) == true) { val realPath = intent.extras!!.getString(REAL_FILE_PATH) uri = when { isPathOnOTG(realPath!!) -> uri realPath.startsWith("file:/") -> Uri.parse(realPath) else -> Uri.fromFile(File(realPath)) } } else { (getRealPathFromURI(uri!!))?.apply { uri = Uri.fromFile(File(this)) } } saveUri = when { intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true -> intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri else -> uri!! } isCropIntent = intent.extras?.get(CROP) == "true" if (isCropIntent) { bottom_editor_primary_actions.beGone() (bottom_editor_crop_rotate_actions.layoutParams as RelativeLayout.LayoutParams).addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1) } loadDefaultImageView() setupBottomActions() if (config.lastEditorCropAspectRatio == ASPECT_RATIO_OTHER) { if (config.lastEditorCropOtherAspectRatioX == 0f) { config.lastEditorCropOtherAspectRatioX = 1f } if (config.lastEditorCropOtherAspectRatioY == 0f) { config.lastEditorCropOtherAspectRatioY = 1f } lastOtherAspectRatio = Pair(config.lastEditorCropOtherAspectRatioX, config.lastEditorCropOtherAspectRatioY) } updateAspectRatio(config.lastEditorCropAspectRatio) crop_image_view.guidelines = CropImageView.Guidelines.ON bottom_aspect_ratios.beVisible() } private fun loadDefaultImageView() { default_image_view.beVisible() crop_image_view.beGone() editor_draw_canvas.beGone() val options = RequestOptions() .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) Glide.with(this) .asBitmap() .load(uri) .apply(options) .listener(object : RequestListener<Bitmap> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean { if (uri != originalUri) { uri = originalUri Handler().post { loadDefaultImageView() } } return false } override fun onResourceReady( bitmap: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { val currentFilter = getFiltersAdapter()?.getCurrentFilter() if (filterInitialBitmap == null) { loadCropImageView() bottomCropRotateClicked() } if (filterInitialBitmap != null && currentFilter != null && currentFilter.filter.name != getString(R.string.none)) { default_image_view.onGlobalLayout { applyFilter(currentFilter) } } else { filterInitialBitmap = bitmap } if (isCropIntent) { bottom_primary_filter.beGone() bottom_primary_draw.beGone() } return false } }).into(default_image_view) } private fun loadCropImageView() { default_image_view.beGone() editor_draw_canvas.beGone() crop_image_view.apply { beVisible() setOnCropImageCompleteListener(this@EditActivity) setImageUriAsync(uri) guidelines = CropImageView.Guidelines.ON if (isCropIntent && shouldCropSquare()) { currAspectRatio = ASPECT_RATIO_ONE_ONE setFixedAspectRatio(true) bottom_aspect_ratio.beGone() } } } private fun loadDrawCanvas() { default_image_view.beGone() crop_image_view.beGone() editor_draw_canvas.beVisible() if (!wasDrawCanvasPositioned) { wasDrawCanvasPositioned = true editor_draw_canvas.onGlobalLayout { ensureBackgroundThread { fillCanvasBackground() } } } } private fun fillCanvasBackground() { val size = Point() windowManager.defaultDisplay.getSize(size) val options = RequestOptions() .format(DecodeFormat.PREFER_ARGB_8888) .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) .fitCenter() try { val builder = Glide.with(applicationContext) .asBitmap() .load(uri) .apply(options) .into(editor_draw_canvas.width, editor_draw_canvas.height) val bitmap = builder.get() runOnUiThread { editor_draw_canvas.apply { updateBackgroundBitmap(bitmap) layoutParams.width = bitmap.width layoutParams.height = bitmap.height y = (height - bitmap.height) / 2f requestLayout() } } } catch (e: Exception) { showErrorToast(e) } } @TargetApi(Build.VERSION_CODES.N) private fun saveImage() { setOldExif() if (crop_image_view.isVisible()) { crop_image_view.getCroppedImageAsync() } else if (editor_draw_canvas.isVisible()) { val bitmap = editor_draw_canvas.getBitmap() if (saveUri.scheme == "file") { SaveAsDialog(this, saveUri.path!!, true) { saveBitmapToFile(bitmap, it, true) } } else if (saveUri.scheme == "content") { val filePathGetter = getNewFilePath() SaveAsDialog(this, filePathGetter.first, filePathGetter.second) { saveBitmapToFile(bitmap, it, true) } } } else { val currentFilter = getFiltersAdapter()?.getCurrentFilter() ?: return val filePathGetter = getNewFilePath() SaveAsDialog(this, filePathGetter.first, filePathGetter.second) { toast(R.string.saving) // clean up everything to free as much memory as possible default_image_view.setImageResource(0) crop_image_view.setImageBitmap(null) bottom_actions_filter_list.adapter = null bottom_actions_filter_list.beGone() ensureBackgroundThread { try { val originalBitmap = Glide.with(applicationContext).asBitmap().load(uri).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get() currentFilter.filter.processFilter(originalBitmap) saveBitmapToFile(originalBitmap, it, false) } catch (e: OutOfMemoryError) { toast(R.string.out_of_memory_error) } } } } } @TargetApi(Build.VERSION_CODES.N) private fun setOldExif() { var inputStream: InputStream? = null try { if (isNougatPlus()) { inputStream = contentResolver.openInputStream(uri!!) oldExif = ExifInterface(inputStream!!) } } catch (e: Exception) { } finally { inputStream?.close() } } private fun shareImage() { ensureBackgroundThread { when { default_image_view.isVisible() -> { val currentFilter = getFiltersAdapter()?.getCurrentFilter() if (currentFilter == null) { toast(R.string.unknown_error_occurred) return@ensureBackgroundThread } val originalBitmap = Glide.with(applicationContext).asBitmap().load(uri).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get() currentFilter.filter.processFilter(originalBitmap) shareBitmap(originalBitmap) } crop_image_view.isVisible() -> { isSharingBitmap = true runOnUiThread { crop_image_view.getCroppedImageAsync() } } editor_draw_canvas.isVisible() -> shareBitmap(editor_draw_canvas.getBitmap()) } } } private fun getTempImagePath(bitmap: Bitmap, callback: (path: String?) -> Unit) { val bytes = ByteArrayOutputStream() bitmap.compress(CompressFormat.PNG, 0, bytes) val folder = File(cacheDir, TEMP_FOLDER_NAME) if (!folder.exists()) { if (!folder.mkdir()) { callback(null) return } } val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: "tmp.jpg" val newPath = "$folder/$filename" val fileDirItem = FileDirItem(newPath, filename) getFileOutputStream(fileDirItem, true) { if (it != null) { try { it.write(bytes.toByteArray()) callback(newPath) } catch (e: Exception) { } finally { it.close() } } else { callback("") } } } private fun shareBitmap(bitmap: Bitmap) { getTempImagePath(bitmap) { if (it != null) { sharePathIntent(it, BuildConfig.APPLICATION_ID) } else { toast(R.string.unknown_error_occurred) } } } private fun getFiltersAdapter() = bottom_actions_filter_list.adapter as? FiltersAdapter private fun setupBottomActions() { setupPrimaryActionButtons() setupCropRotateActionButtons() setupAspectRatioButtons() setupDrawButtons() } private fun setupPrimaryActionButtons() { bottom_primary_filter.setOnClickListener { bottomFilterClicked() } bottom_primary_crop_rotate.setOnClickListener { bottomCropRotateClicked() } bottom_primary_draw.setOnClickListener { bottomDrawClicked() } } private fun bottomFilterClicked() { currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_FILTER) { PRIMARY_ACTION_NONE } else { PRIMARY_ACTION_FILTER } updatePrimaryActionButtons() } private fun bottomCropRotateClicked() { currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) { PRIMARY_ACTION_NONE } else { PRIMARY_ACTION_CROP_ROTATE } updatePrimaryActionButtons() } private fun bottomDrawClicked() { currPrimaryAction = if (currPrimaryAction == PRIMARY_ACTION_DRAW) { PRIMARY_ACTION_NONE } else { PRIMARY_ACTION_DRAW } updatePrimaryActionButtons() } private fun setupCropRotateActionButtons() { bottom_rotate.setOnClickListener { crop_image_view.rotateImage(90) } bottom_resize.beGoneIf(isCropIntent) bottom_resize.setOnClickListener { resizeImage() } bottom_flip_horizontally.setOnClickListener { crop_image_view.flipImageHorizontally() } bottom_flip_vertically.setOnClickListener { crop_image_view.flipImageVertically() } bottom_aspect_ratio.setOnClickListener { currCropRotateAction = if (currCropRotateAction == CROP_ROTATE_ASPECT_RATIO) { crop_image_view.guidelines = CropImageView.Guidelines.OFF bottom_aspect_ratios.beGone() CROP_ROTATE_NONE } else { crop_image_view.guidelines = CropImageView.Guidelines.ON bottom_aspect_ratios.beVisible() CROP_ROTATE_ASPECT_RATIO } updateCropRotateActionButtons() } } private fun setupAspectRatioButtons() { bottom_aspect_ratio_free.setOnClickListener { updateAspectRatio(ASPECT_RATIO_FREE) } bottom_aspect_ratio_one_one.setOnClickListener { updateAspectRatio(ASPECT_RATIO_ONE_ONE) } bottom_aspect_ratio_four_three.setOnClickListener { updateAspectRatio(ASPECT_RATIO_FOUR_THREE) } bottom_aspect_ratio_sixteen_nine.setOnClickListener { updateAspectRatio(ASPECT_RATIO_SIXTEEN_NINE) } bottom_aspect_ratio_other.setOnClickListener { OtherAspectRatioDialog(this, lastOtherAspectRatio) { lastOtherAspectRatio = it config.lastEditorCropOtherAspectRatioX = it.first config.lastEditorCropOtherAspectRatioY = it.second updateAspectRatio(ASPECT_RATIO_OTHER) } } updateAspectRatioButtons() } private fun setupDrawButtons() { updateDrawColor(config.lastEditorDrawColor) bottom_draw_width.progress = config.lastEditorBrushSize updateBrushSize(config.lastEditorBrushSize) bottom_draw_color_clickable.setOnClickListener { ColorPickerDialog(this, drawColor) { wasPositivePressed, color -> if (wasPositivePressed) { updateDrawColor(color) } } } bottom_draw_width.onSeekBarChangeListener { config.lastEditorBrushSize = it updateBrushSize(it) } bottom_draw_undo.setOnClickListener { editor_draw_canvas.undo() } } private fun updateBrushSize(percent: Int) { editor_draw_canvas.updateBrushSize(percent) val scale = Math.max(0.03f, percent / 100f) bottom_draw_color.scaleX = scale bottom_draw_color.scaleY = scale } private fun updatePrimaryActionButtons() { if (crop_image_view.isGone() && currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) { loadCropImageView() } else if (default_image_view.isGone() && currPrimaryAction == PRIMARY_ACTION_FILTER) { loadDefaultImageView() } else if (editor_draw_canvas.isGone() && currPrimaryAction == PRIMARY_ACTION_DRAW) { loadDrawCanvas() } arrayOf(bottom_primary_filter, bottom_primary_crop_rotate, bottom_primary_draw).forEach { it.applyColorFilter(Color.WHITE) } val currentPrimaryActionButton = when (currPrimaryAction) { PRIMARY_ACTION_FILTER -> bottom_primary_filter PRIMARY_ACTION_CROP_ROTATE -> bottom_primary_crop_rotate PRIMARY_ACTION_DRAW -> bottom_primary_draw else -> null } currentPrimaryActionButton?.applyColorFilter(getAdjustedPrimaryColor()) bottom_editor_filter_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_FILTER) bottom_editor_crop_rotate_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_CROP_ROTATE) bottom_editor_draw_actions.beVisibleIf(currPrimaryAction == PRIMARY_ACTION_DRAW) if (currPrimaryAction == PRIMARY_ACTION_FILTER && bottom_actions_filter_list.adapter == null) { ensureBackgroundThread { val thumbnailSize = resources.getDimension(R.dimen.bottom_filters_thumbnail_size).toInt() val bitmap = try { Glide.with(this) .asBitmap() .load(uri).listener(object : RequestListener<Bitmap> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean { showErrorToast(e.toString()) return false } override fun onResourceReady( resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean ) = false }) .submit(thumbnailSize, thumbnailSize) .get() } catch (e: GlideException) { showErrorToast(e) finish() return@ensureBackgroundThread } runOnUiThread { val filterThumbnailsManager = FilterThumbnailsManager() filterThumbnailsManager.clearThumbs() val noFilter = Filter(getString(R.string.none)) filterThumbnailsManager.addThumb(FilterItem(bitmap, noFilter)) FilterPack.getFilterPack(this).forEach { val filterItem = FilterItem(bitmap, it) filterThumbnailsManager.addThumb(filterItem) } val filterItems = filterThumbnailsManager.processThumbs() val adapter = FiltersAdapter(applicationContext, filterItems) { val layoutManager = bottom_actions_filter_list.layoutManager as LinearLayoutManager applyFilter(filterItems[it]) if (it == layoutManager.findLastCompletelyVisibleItemPosition() || it == layoutManager.findLastVisibleItemPosition()) { bottom_actions_filter_list.smoothScrollBy(thumbnailSize, 0) } else if (it == layoutManager.findFirstCompletelyVisibleItemPosition() || it == layoutManager.findFirstVisibleItemPosition()) { bottom_actions_filter_list.smoothScrollBy(-thumbnailSize, 0) } } bottom_actions_filter_list.adapter = adapter adapter.notifyDataSetChanged() } } } if (currPrimaryAction != PRIMARY_ACTION_CROP_ROTATE) { bottom_aspect_ratios.beGone() currCropRotateAction = CROP_ROTATE_NONE } updateCropRotateActionButtons() } private fun applyFilter(filterItem: FilterItem) { val newBitmap = Bitmap.createBitmap(filterInitialBitmap!!) default_image_view.setImageBitmap(filterItem.filter.processFilter(newBitmap)) } private fun updateAspectRatio(aspectRatio: Int) { currAspectRatio = aspectRatio config.lastEditorCropAspectRatio = aspectRatio updateAspectRatioButtons() crop_image_view.apply { if (aspectRatio == ASPECT_RATIO_FREE) { setFixedAspectRatio(false) } else { val newAspectRatio = when (aspectRatio) { ASPECT_RATIO_ONE_ONE -> Pair(1f, 1f) ASPECT_RATIO_FOUR_THREE -> Pair(4f, 3f) ASPECT_RATIO_SIXTEEN_NINE -> Pair(16f, 9f) else -> Pair(lastOtherAspectRatio!!.first, lastOtherAspectRatio!!.second) } setAspectRatio(newAspectRatio.first.toInt(), newAspectRatio.second.toInt()) } } } private fun updateAspectRatioButtons() { arrayOf( bottom_aspect_ratio_free, bottom_aspect_ratio_one_one, bottom_aspect_ratio_four_three, bottom_aspect_ratio_sixteen_nine, bottom_aspect_ratio_other ).forEach { it.setTextColor(Color.WHITE) } val currentAspectRatioButton = when (currAspectRatio) { ASPECT_RATIO_FREE -> bottom_aspect_ratio_free ASPECT_RATIO_ONE_ONE -> bottom_aspect_ratio_one_one ASPECT_RATIO_FOUR_THREE -> bottom_aspect_ratio_four_three ASPECT_RATIO_SIXTEEN_NINE -> bottom_aspect_ratio_sixteen_nine else -> bottom_aspect_ratio_other } currentAspectRatioButton.setTextColor(getAdjustedPrimaryColor()) } private fun updateCropRotateActionButtons() { arrayOf(bottom_aspect_ratio).forEach { it.applyColorFilter(Color.WHITE) } val primaryActionView = when (currCropRotateAction) { CROP_ROTATE_ASPECT_RATIO -> bottom_aspect_ratio else -> null } primaryActionView?.applyColorFilter(getAdjustedPrimaryColor()) } private fun updateDrawColor(color: Int) { drawColor = color bottom_draw_color.applyColorFilter(color) config.lastEditorDrawColor = color editor_draw_canvas.updateColor(color) } private fun resizeImage() { val point = getAreaSize() if (point == null) { toast(R.string.unknown_error_occurred) return } ResizeDialog(this, point) { resizeWidth = it.x resizeHeight = it.y crop_image_view.getCroppedImageAsync() } } private fun shouldCropSquare(): Boolean { val extras = intent.extras return if (extras != null && extras.containsKey(ASPECT_X) && extras.containsKey(ASPECT_Y)) { extras.getInt(ASPECT_X) == extras.getInt(ASPECT_Y) } else { false } } private fun getAreaSize(): Point? { val rect = crop_image_view.cropRect ?: return null val rotation = crop_image_view.rotatedDegrees return if (rotation == 0 || rotation == 180) { Point(rect.width(), rect.height()) } else { Point(rect.height(), rect.width()) } } override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) { if (result.error == null) { setOldExif() val bitmap = result.bitmap if (isSharingBitmap) { isSharingBitmap = false shareBitmap(bitmap) return } if (isCropIntent) { if (saveUri.scheme == "file") { saveBitmapToFile(bitmap, saveUri.path!!, true) } else { var inputStream: InputStream? = null var outputStream: OutputStream? = null try { val stream = ByteArrayOutputStream() bitmap.compress(CompressFormat.JPEG, 100, stream) inputStream = ByteArrayInputStream(stream.toByteArray()) outputStream = contentResolver.openOutputStream(saveUri) inputStream.copyTo(outputStream!!) } finally { inputStream?.close() outputStream?.close() } Intent().apply { data = saveUri addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) setResult(RESULT_OK, this) } finish() } } else if (saveUri.scheme == "file") { SaveAsDialog(this, saveUri.path!!, true) { saveBitmapToFile(bitmap, it, true) } } else if (saveUri.scheme == "content") { val filePathGetter = getNewFilePath() SaveAsDialog(this, filePathGetter.first, filePathGetter.second) { saveBitmapToFile(bitmap, it, true) } } else { toast(R.string.unknown_file_location) } } else { toast("${getString(R.string.image_editing_failed)}: ${result.error.message}") } } private fun getNewFilePath(): Pair<String, Boolean> { var newPath = applicationContext.getRealPathFromURI(saveUri) ?: "" if (newPath.startsWith("/mnt/")) { newPath = "" } var shouldAppendFilename = true if (newPath.isEmpty()) { val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: "" if (filename.isNotEmpty()) { val path = if (intent.extras?.containsKey(REAL_FILE_PATH) == true) intent.getStringExtra(REAL_FILE_PATH)?.getParentPath() else internalStoragePath newPath = "$path/$filename" shouldAppendFilename = false } } if (newPath.isEmpty()) { newPath = "$internalStoragePath/${getCurrentFormattedDateTime()}.${saveUri.toString().getFilenameExtension()}" shouldAppendFilename = false } return Pair(newPath, shouldAppendFilename) } private fun saveBitmapToFile(bitmap: Bitmap, path: String, showSavingToast: Boolean) { if (!packageName.contains("slootelibomelpmis".reversed(), true)) { if (baseConfig.appRunCount > 100) { val label = "sknahT .moc.slootelibomelpmis.www morf eno lanigiro eht daolnwod ytefas nwo ruoy roF .ppa eht fo noisrev ekaf a gnisu era uoY".reversed() runOnUiThread { ConfirmationDialog(this, label, positive = com.simplemobiletools.commons.R.string.ok, negative = 0) { launchViewIntent("6629852208836920709=di?ved/sppa/erots/moc.elgoog.yalp//:sptth".reversed()) } } return } } try { ensureBackgroundThread { val file = File(path) val fileDirItem = FileDirItem(path, path.getFilenameFromPath()) getFileOutputStream(fileDirItem, true) { if (it != null) { saveBitmap(file, bitmap, it, showSavingToast) } else { toast(R.string.image_editing_failed) } } } } catch (e: Exception) { showErrorToast(e) } catch (e: OutOfMemoryError) { toast(R.string.out_of_memory_error) } } @TargetApi(Build.VERSION_CODES.N) private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream, showSavingToast: Boolean) { if (showSavingToast) { toast(R.string.saving) } if (resizeWidth > 0 && resizeHeight > 0) { val resized = Bitmap.createScaledBitmap(bitmap, resizeWidth, resizeHeight, false) resized.compress(file.absolutePath.getCompressionFormat(), 90, out) } else { bitmap.compress(file.absolutePath.getCompressionFormat(), 90, out) } try { if (isNougatPlus()) { val newExif = ExifInterface(file.absolutePath) oldExif?.copyNonDimensionAttributesTo(newExif) } } catch (e: Exception) { } setResult(Activity.RESULT_OK, intent) scanFinalPath(file.absolutePath) out.close() } private fun editWith() { openEditor(uri.toString(), true) isEditingWithThirdParty = true } private fun scanFinalPath(path: String) { val paths = arrayListOf(path) rescanPaths(paths) { fixDateTaken(paths, false) setResult(Activity.RESULT_OK, intent) toast(R.string.file_saved) finish() } } }
gpl-3.0
e712dd9be86b35fd34fdd5faf5c155ec
35.719738
158
0.579205
5.020426
false
false
false
false
blhps/lifeograph-android
app/src/main/java/net/sourceforge/lifeograph/FragmentListDiaries.kt
1
10072
/* ********************************************************************************* Copyright (C) 2012-2021 Ahmet Öztürk ([email protected]) This file is part of Lifeograph. Lifeograph 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. Lifeograph 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 Lifeograph. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************************/ package net.sourceforge.lifeograph import android.content.DialogInterface import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.navigation.Navigation import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import net.sourceforge.lifeograph.DialogPassword.DPAction import net.sourceforge.lifeograph.helpers.Result import java.io.File import java.util.* class FragmentListDiaries : Fragment(), RViewAdapterBasic.Listener, DialogInquireText.Listener, DialogPassword.Listener { // VARIABLES =================================================================================== private val mColumnCount = 1 private var mFlagOpenReady = false private var mPasswordAttemptNo = 0 private val mDiaryItems: MutableList<RViewAdapterBasic.Item> = ArrayList() // METHODS ===================================================================================== override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_list_diaries, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // Set the adapter val recyclerView: RecyclerView = view.findViewById(R.id.list_diaries) val context = view.context if(mColumnCount <= 1) { recyclerView.layoutManager = LinearLayoutManager(context) } else { recyclerView.layoutManager = GridLayoutManager(context, mColumnCount) } recyclerView.adapter = RViewAdapterBasic(mDiaryItems, this) val fab: FloatingActionButton = view.findViewById(R.id.fab_add_diary) fab.setOnClickListener { createNewDiary() } if(Lifeograph.mActivityMain.mStartUpPath != null) { Log.d(Lifeograph.TAG, Lifeograph.mActivityMain.mStartUpPath!!.path!!) val file = File(Lifeograph.mActivityMain.mStartUpPath!!.path!!) if(file.exists()) openDiary1(file.path) else Lifeograph.showToast("File not found!") } } override fun onResume() { Log.d(Lifeograph.TAG, "FragmentDiaryList.onResume()") super.onResume() if(Diary.d.is_open) { Diary.d.writeAtLogout() Diary.d.remove_lock_if_necessary() Diary.d.clear() } val actionbar = (requireActivity() as AppCompatActivity).supportActionBar if(actionbar != null) { actionbar.subtitle = "" } (activity as FragmentHost?)!!.updateDrawerMenu(R.id.nav_diaries) populateDiaries() } // DIARY OPERATIONS ============================================================================ private fun populateDiaries() { mDiaryItems.clear() val dir = diariesDir Log.d(Lifeograph.TAG, dir.path) if(!dir.exists()) { if(!dir.mkdirs()) Lifeograph.showToast("Failed to create the diary folder") } else { val dirs = dir.listFiles() if(dirs != null) { for(ff in dirs) { if(!ff.isDirectory && !ff.path.endsWith("~")) { mDiaryItems.add(RViewAdapterBasic.Item(ff.name, ff.path, R.drawable.ic_diary)) } } } } mDiaryItems.add( RViewAdapterBasic.Item(Diary.sExampleDiaryName, Diary.sExampleDiaryPath, R.drawable.ic_diary)) } private fun openDiary1(path: String) { mFlagOpenReady = false when(Diary.d.set_path(path, Diary.SetPathType.NORMAL)) { Result.SUCCESS -> mFlagOpenReady = true Result.FILE_NOT_FOUND -> Lifeograph.showToast("File is not found") Result.FILE_NOT_READABLE -> Lifeograph.showToast("File is not readable") Result.FILE_LOCKED -> Lifeograph.showConfirmationPrompt( requireContext(), R.string.continue_from_lock_prompt, R.string.continue_from_lock, { _: DialogInterface?, _: Int -> openDiary2() }, R.string.discard_lock ) { _: DialogInterface?, _: Int -> openDiary3() } else -> Lifeograph.showToast("Failed to open the diary") } if(mFlagOpenReady) openDiary3() } private fun openDiary2() { Diary.d.enableWorkingOnLockfile(true) openDiary3() } private fun openDiary3() { mFlagOpenReady = false when(Diary.d.read_header(requireContext().assets)) { Result.SUCCESS -> mFlagOpenReady = true Result.INCOMPATIBLE_FILE_OLD -> Lifeograph.showToast("Incompatible diary version (TOO OLD)") Result.INCOMPATIBLE_FILE_NEW -> Lifeograph.showToast("Incompatible diary version (TOO NEW)") Result.CORRUPT_FILE -> Lifeograph.showToast("Corrupt file") else -> Log.e(Lifeograph.TAG, "Unprocessed return value from read_header") } if(!mFlagOpenReady) return if(Diary.d.is_encrypted) askPassword() else readBody() } private val diariesDir: File get() { if(sStoragePref == "C") { return File(sDiaryPath) } else if(sStoragePref == "E") { // when(Environment.getExternalStorageState()) { // Environment.MEDIA_MOUNTED -> { // // We can read and write the media // return File(context?.getExternalFilesDir(null), sDiaryPath) // } // Environment.MEDIA_MOUNTED_READ_ONLY -> { // // We can only read the media (we may do something else here) // Lifeograph.showToast(R.string.storage_not_available) // Log.d(Lifeograph.TAG, "Storage is read-only") // } // else -> { // // Something else is wrong. It may be one of many other states, but // // all we need to know is we can neither read nor write // Lifeograph.showToast(R.string.storage_not_available) // } // } Lifeograph.showToast( "External Storage Option is removed. Please use the custom path picker!") } return File(requireContext().filesDir, sDiaryPath) } private fun createNewDiary() { // ask for name DialogInquireText(requireContext(), R.string.create_diary, Lifeograph.getStr(R.string.new_diary), R.string.create, this).show() } private fun askPassword() { DialogPassword(requireContext(), Diary.d, DPAction.DPA_LOGIN, this).show() mPasswordAttemptNo++ } private fun readBody() { when(Diary.d.read_body()) { Result.SUCCESS -> navigateToDiary() Result.WRONG_PASSWORD -> Lifeograph.showToast(R.string.wrong_password) Result.CORRUPT_FILE -> Lifeograph.showToast("Corrupt file") else -> { } } mPasswordAttemptNo = 0 } private fun navigateToDiary() { Navigation.findNavController(requireView()).navigate(R.id.nav_entries) } // INTERFACE METHODS =========================================================================== // RecyclerViewAdapterDiaries.DiaryItemListener INTERFACE METHODS override fun onItemClick(item: RViewAdapterBasic.Item) { openDiary1(item.mId) Log.d(Lifeograph.TAG, "Diary clicked") } // DialogPassword INTERFACE METHODS override fun onDPAction(action: DPAction) { if(action === DPAction.DPA_LOGIN) readBody() } // InquireListener INTERFACE METHODS override fun onInquireAction(id: Int, text: String) { if(id == R.string.create_diary) { if(Diary.d.init_new(Lifeograph.joinPath(diariesDir.path, text), "") == Result.SUCCESS) { navigateToDiary() } // TODO else inform the user about the problem } } override fun onInquireTextChanged(id: Int, text: String): Boolean { if(id == R.string.create_diary) { val fp = File(diariesDir.path, text) return !fp.exists() } return true } companion object { @JvmField var sStoragePref = "" @JvmField var sDiaryPath = "" } }
gpl-3.0
c5aa501b321579467d0852e701aada48
38.960317
104
0.566733
4.900243
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/optional/FlexibleGene.kt
1
4809
package org.evomaster.core.search.gene.optional import org.evomaster.core.Lazy import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.root.CompositeGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory /** * This represents a flexible gene which does not stick to a specific type * the type can be dynamically updated, * ie, [gene] can be replaced with [replaceGeneTo] method * * this gene is now mainly used to support array and map whose template * might not follow a fixed typed. FlexibleMap is added, might need it for * array gene */ class FlexibleGene(name: String, gene: Gene, private var replaceable: Boolean = true ) : CompositeGene(name, mutableListOf(gene)) { init { geneCheck(gene) } companion object{ private val log: Logger = LoggerFactory.getLogger(FlexibleGene::class.java) fun wrapWithFlexibleGene(gene: Gene, replaceable: Boolean = true) : FlexibleGene{ if (gene is FlexibleGene) { if (gene.replaceable != replaceable) return FlexibleGene(gene.name, gene.gene, replaceable) return gene } return FlexibleGene(gene.name, gene, replaceable) } } val gene: Gene get() {return children.first()} /** * forbid replacing gene to other */ fun forbidReplace(){ replaceable = false } fun replaceGeneTo(geneToUpdate: Gene){ if (!replaceable) throw IllegalStateException("attempt to replace the gene which is not replaceable") geneCheck(geneToUpdate) Lazy.assert { children.size == 1 } killAllChildren() geneToUpdate.resetLocalIdRecursively() addChild(geneToUpdate) } override fun <T> getWrappedGene(klass: Class<T>) : T? where T : Gene{ if(this.javaClass == klass){ return this as T } return gene.getWrappedGene(klass) } override fun copyContent(): FlexibleGene { return FlexibleGene(name, gene.copy(), replaceable) } override fun isLocallyValid(): Boolean { return gene.isLocallyValid() } override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { gene.randomize(randomness, tryToForceNewValue) } override fun isMutable(): Boolean { return gene.isMutable() } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { /* do not develop shallowMutation yet TODO we might employ shallowMutation to replace gene with different genes */ return false } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return gene.getValueAsPrintableString(previousGenes, mode, targetFormat, extraCheck) } override fun copyValueFrom(other: Gene) { if (other !is FlexibleGene) throw IllegalArgumentException("Invalid gene type ${other.javaClass}") if (replaceable){ val replaced = other.gene.copy() replaced.resetLocalIdRecursively() replaceGeneTo(replaced) }else{ // TODO need to refactor log.warn("TOCHECK, attempt to copyValueFrom when it is not replaceable") } } override fun containsSameValueAs(other: Gene): Boolean { if (other is FlexibleGene){ return try { gene.containsSameValueAs(other.gene) }catch (e : Exception){ return false } } return false } override fun bindValueBasedOn(gene: Gene): Boolean { return false } override fun isPrintable(): Boolean { return gene.isPrintable() } override fun getValueAsRawString(): String { return gene.getValueAsRawString() } private fun geneCheck(geneToBeUpdated : Gene){ if (geneToBeUpdated is FlexibleGene){ throw IllegalArgumentException("For a FlexibleGene, its gene to be employed or updated cannot be FlexibleGene") } } }
lgpl-3.0
41635f6deccc5647578522ae7e486c26
29.833333
123
0.652319
4.988589
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/db/ChatRoomDao.kt
2
5169
package chat.rocket.android.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import chat.rocket.android.db.model.ChatRoom import chat.rocket.android.db.model.ChatRoomEntity @Dao abstract class ChatRoomDao : BaseDao<ChatRoomEntity> { @Transaction @Query(""" $BASE_QUERY WHERE chatrooms.id = :id """) abstract fun get(id: String): LiveData<ChatRoom> @Transaction @Query(""" $BASE_QUERY WHERE chatrooms.id = :id """) abstract fun getSync(id: String): ChatRoom? @Transaction @Query("$BASE_QUERY $FILTER_NOT_OPENED") abstract fun getAllSync(): List<ChatRoom> @Transaction @Query("""$BASE_QUERY WHERE chatrooms.name LIKE '%' || :query || '%' OR users.name LIKE '%' || :query || '%' """) abstract fun searchSync(query: String): List<ChatRoom> @Query("SELECT COUNT(id) FROM chatrooms WHERE open = 1") abstract fun count(): Long @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY CASE WHEN lastMessageTimeStamp IS NOT NULL THEN lastMessageTimeStamp ELSE updatedAt END DESC """) abstract fun getAll(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY $TYPE_ORDER, CASE WHEN lastMessageTimeStamp IS NOT NULL THEN lastMessageTimeStamp ELSE updatedAt END DESC """) abstract fun getAllGrouped(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY $UNREAD, CASE WHEN lastMessageTimeStamp IS NOT NULL THEN lastMessageTimeStamp ELSE updatedAt END DESC """) abstract fun getAllUnread(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY $UNREAD, name COLLATE NOCASE """) abstract fun getAllAlphabeticallyUnread(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY $TYPE_ORDER, $UNREAD, name COLLATE NOCASE """) abstract fun getAllAlphabeticallyGroupedUnread(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY $TYPE_ORDER, $UNREAD, CASE WHEN lastMessageTimeStamp IS NOT NULL THEN lastMessageTimeStamp ELSE updatedAt END DESC """) abstract fun getAllGroupedUnread(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY name COLLATE NOCASE """) abstract fun getAllAlphabetically(): LiveData<List<ChatRoom>> @Transaction @Query(""" $BASE_QUERY $FILTER_NOT_OPENED ORDER BY $TYPE_ORDER, name COLLATE NOCASE """) abstract fun getAllAlphabeticallyGrouped(): LiveData<List<ChatRoom>> @Query("DELETE FROM chatrooms WHERE ID = :id") abstract fun delete(id: String) @Query("DELETE FROM chatrooms") abstract fun delete() @Transaction open fun cleanInsert(chatRooms: List<ChatRoomEntity>) { delete() insert(chatRooms) } @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertOrReplace(chatRooms: List<ChatRoomEntity>) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertOrReplace(chatRoom: ChatRoomEntity) @Update abstract fun update(list: List<ChatRoomEntity>) @Transaction open fun update(toInsert: List<ChatRoomEntity>, toUpdate: List<ChatRoomEntity>, toRemove: List<String>) { insertOrReplace(toInsert) update(toUpdate) toRemove.forEach { id -> delete(id) } } companion object { const val BASE_QUERY = """ SELECT chatrooms.*, users.username as username, users.name as userFullname, users.status, lmUsers.username as lastMessageUserName, lmUsers.name as lastMessageUserFullName FROM chatrooms LEFT JOIN users ON chatrooms.userId = users.id LEFT JOIN users AS lmUsers ON chatrooms.lastMessageUserId = lmUsers.id """ const val FILTER_NOT_OPENED = """ WHERE chatrooms.open = 1 """ const val TYPE_ORDER = """ CASE WHEN type = 'c' THEN 1 WHEN type = 'p' THEN 2 WHEN type = 'd' THEN 3 WHEN type = 'l' THEN 4 ELSE 5 END """ const val UNREAD = """ CASE WHEN alert OR unread > 0 THEN 1 ELSE 2 END """ } }
mit
f93b47b49514c1756e81cef41878b408
25.243655
109
0.58135
4.759669
false
false
false
false
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imagepipeline/systrace/DefaultFrescoSystrace.kt
2
2267
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.systrace import android.os.Build import android.os.Trace import com.facebook.imagepipeline.systrace.FrescoSystrace.ArgsBuilder import com.facebook.imagepipeline.systrace.FrescoSystrace.Systrace import com.facebook.imagepipelinebase.BuildConfig class DefaultFrescoSystrace : Systrace { override fun beginSection(name: String) { if (isTracing()) { Trace.beginSection(name) } } override fun beginSectionWithArgs(name: String): ArgsBuilder = if (isTracing()) { DefaultArgsBuilder(name) } else { FrescoSystrace.NO_OP_ARGS_BUILDER } override fun endSection() { if (isTracing()) { Trace.endSection() } } override fun isTracing(): Boolean = BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 /** * Handles adding args to a systrace section by naively appending them to the section name. This * functionality has a more intelligent implementation when using a tracer that writes directly to * ftrace instead of using Android's Trace class. */ private class DefaultArgsBuilder(name: String) : ArgsBuilder { private val stringBuilder: StringBuilder = StringBuilder(name) override fun flush() { // 127 is the max name length according to // https://developer.android.com/reference/android/os/Trace.html if (stringBuilder.length > 127) { stringBuilder.setLength(127) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Trace.beginSection(stringBuilder.toString()) } } override fun arg(key: String, value: Any) = apply { appendArgument(key, value) } override fun arg(key: String, value: Int) = apply { appendArgument(key, value) } override fun arg(key: String, value: Long) = apply { appendArgument(key, value) } override fun arg(key: String, value: Double) = apply { appendArgument(key, value) } private fun appendArgument(key: String, value: Any) = stringBuilder.append(';').append("$key=$value") } }
mit
3ebca65326ee1ceb2b46dff5bd833fc8
30.486111
100
0.69828
3.991197
false
false
false
false
ThomasGaubert/zephyr
android/app/src/main/java/com/texasgamer/zephyr/util/analytics/ZephyrEvent.kt
1
1402
package com.texasgamer.zephyr.util.analytics /** * Analytics events. */ class ZephyrEvent { /** * Navigation events. */ object Navigation { const val BASE = "nav" /* Hamburger menu */ const val MANAGE_NOTIFICATIONS = "manage_notifications" const val HELP = "help" const val ABOUT = "about" /* Connection menu */ const val SCAN_QR_CODE = "scan_qr_code" const val ENTER_CODE = "enter_code" /* About */ const val GITHUB = "github" const val LICENSES = "licenses" } /** * Action events. */ object Action { const val BASE = "action" /* Hamburger menu */ const val OPEN_HAMBURGER_MENU = "open_hamburger_menu" /* Connection menu */ const val OPEN_CONNECTION_MENU = "open_connection_menu" const val TAP_QR_CODE = "tap_qr_code" const val TAP_ENTER_CODE = "tap_entercode" const val TAP_DISCOVERED_SERVER = "tap_discovered_server" /* Connection button */ const val TAP_CONNECTION_BUTTON = "tap_connection_button" const val LONG_PRESS_CONNECTION_BUTTON = "long_press_connection_button" } /** * Event parameters. */ object Parameter { /* Connection button */ const val JOIN_CODE_SET = "join_code_set" const val CONNECTED = "connected" } }
mit
048fa4b8a25deb0cc525422022c59fbf
24.509091
79
0.57632
4.028736
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/messages/CharactersMessages.kt
1
11855
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.messages import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.field.HideableCharacterCardField import com.rpkit.characters.bukkit.race.RPKRace import com.rpkit.core.bukkit.message.BukkitMessages import com.rpkit.core.message.ParameterizedMessage import com.rpkit.core.message.to import com.rpkit.players.bukkit.profile.RPKProfile class CharactersMessages(plugin: RPKCharactersBukkit) : BukkitMessages(plugin) { class CharacterSetAgeInvalidValidationMessage(private val message: ParameterizedMessage) { fun withParameters( minAge: Int, maxAge: Int ) = message.withParameters( "min_age" to minAge.toString(), "max_age" to maxAge.toString() ) } class CharacterHideInvalidFieldMessage(private val message: ParameterizedMessage) { fun withParameters(fields: List<HideableCharacterCardField>) = message.withParameters("fields" to fields.joinToString(transform = HideableCharacterCardField::name)) } class CharacterHideValidMessage(private val message: ParameterizedMessage) { fun withParameters(field: HideableCharacterCardField) = message.withParameters("field" to field.name) } class CharacterUnhideInvalidFieldMessage(private val message: ParameterizedMessage) { fun withParameters(fields: List<HideableCharacterCardField>) = message.withParameters("fields" to fields.joinToString(transform = HideableCharacterCardField::name)) } class CharacterUnhideValidMessage(private val message: ParameterizedMessage) { fun withParameters(field: HideableCharacterCardField) = message.withParameters("field" to field.name) } class CharacterCardOwnerMessage(val messages: List<ParameterizedMessage>) { fun withParameters( name: String, profile: RPKProfile, gender: String, age: Int, race: RPKRace, description: String, dead: Boolean, health: Double, maxHealth: Double, food: Int, maxFood: Int, thirst: Int, maxThirst: Int ) = messages.map { message -> message.withParameters( "name" to name, "profile" to profile.name + profile.discriminator, "gender" to gender, "age" to age.toString(), "race" to race.name.value, "description" to description, "dead" to if (dead) "Yes" else "No", "health" to health.toString(), "max_health" to maxHealth.toString(), "food" to food.toString(), "max_food" to maxFood.toString(), "thirst" to thirst.toString(), "max_thirst" to maxThirst.toString() ) } } class CharacterCardNotOwnerMessage(val messages: List<ParameterizedMessage>) { fun withParameters( name: String, profile: RPKProfile, gender: String, age: Int, race: RPKRace, description: String, dead: Boolean, health: Double, maxHealth: Double, food: Int, maxFood: Int, thirst: Int, maxThirst: Int ) = messages.map { message -> message.withParameters( "name" to name, "profile" to profile.name + profile.discriminator, "gender" to gender, "age" to age.toString(), "race" to race.name.value, "description" to description, "dead" to if (dead) "Yes" else "No", "health" to health.toString(), "max_health" to maxHealth.toString(), "food" to food.toString(), "max_food" to maxFood.toString(), "thirst" to thirst.toString(), "max_thirst" to maxThirst.toString() ) } } class CharacterListItem(private val message: ParameterizedMessage) { fun withParameters(character: RPKCharacter) = message.withParameters( "character" to character.name ) } class RaceListItem(private val message: ParameterizedMessage) { fun withParameters(race: RPKRace) = message.withParameters( "race" to race.name.value ) } class NoPermissionCharacterHideMessage(private val message: ParameterizedMessage) { fun withParameters(field: HideableCharacterCardField) = message.withParameters( "field" to field.name ) } class NoPermissionCharacterUnhideMessage(private val message: ParameterizedMessage) { fun withParameters(field: HideableCharacterCardField) = message.withParameters( "field" to field.name ) } val characterUsage = get("character-usage") val characterSetUsage = get("character-set-usage") val characterSetAgePrompt = get("character-set-age-prompt") val characterSetAgeInvalidValidation = getParameterized("character-set-age-invalid-validation") .let(::CharacterSetAgeInvalidValidationMessage) val characterSetAgeInvalidNumber = get("character-set-age-invalid-number") val characterSetAgeValid = get("character-set-age-valid") val characterSetDeadPrompt = get("character-set-dead-prompt") val characterSetDeadInvalidBoolean = get("character-set-dead-invalid-boolean") val characterSetDeadValid = get("character-set-dead-valid") val characterSetProfilePrompt = get("character-set-profile-prompt") val characterSetProfileInvalidNoDiscriminator = get("character-set-profile-invalid-no-discriminator") val characterSetProfileInvalidDiscriminator = get("character-set-profile-invalid-discriminator") val characterSetProfileValid = get("character-set-profile-valid") val characterSetGenderPrompt = get("character-set-gender-prompt") val characterSetGenderNotSet = get("character-set-gender-not-set") val characterSetGenderValid = get("character-set-gender-valid") val characterSetRacePrompt = get("character-set-race-prompt") val characterSetRaceInvalidRace = get("character-set-race-invalid-race") val characterSetRaceValid = get("character-set-race-valid") val characterHideUsage = get("character-hide-usage") val characterHideInvalidField = getParameterized("character-hide-invalid-field") .let(::CharacterHideInvalidFieldMessage) val characterHideValid = getParameterized("character-hide-valid") .let(::CharacterHideValidMessage) val characterUnhideUsage = get("character-unhide-usage") val characterUnhideInvalidField = getParameterized("character-unhide-invalid-field") .let(::CharacterUnhideInvalidFieldMessage) val characterUnhideValid = getParameterized("character-unhide-valid") .let(::CharacterUnhideValidMessage) val characterCardOwner = getParameterizedList("character-card-owner").let(::CharacterCardOwnerMessage) val characterCardNotOwner = getParameterizedList("character-card-not-owner").let(::CharacterCardNotOwnerMessage) val characterListTitle = get("character-list-title") val characterListItem = getParameterized("character-list-item").let(::CharacterListItem) val characterSwitchPrompt = get("character-switch-prompt") val characterSwitchInvalidCharacter = get("character-switch-invalid-character") val characterSwitchInvalidCharacterOtherAccount = get("character-switch-invalid-character-other-account") val characterSwitchValid = get("character-switch-valid") val characterSwitchUsage = get("character-switch-usage") val characterNewValid = get("character-new-valid") val characterNewInvalidCooldown = get("character-new-invalid-cooldown") val characterDeletePrompt = get("character-delete-prompt") val characterDeleteInvalidCharacter = get("character-delete-invalid-character") val characterDeleteConfirmation = get("character-delete-confirmation") val characterDeleteConfirmationInvalidBoolean = get("character-delete-confirmation-invalid-boolean") val characterDeleteValid = get("character-delete-valid") val characterDeleteUsage = get("character-delete-usage") val raceUsage = get("race-usage") val raceAddPrompt = get("race-add-prompt") val raceAddInvalidRace = get("race-add-invalid-race") val raceAddValid = get("race-add-valid") val raceRemovePrompt = get("race-remove-prompt") val raceRemoveInvalidRace = get("race-remove-invalid-race") val raceRemoveValid = get("race-remove-valid") val raceListTitle = get("race-list-title") val raceListItem = getParameterized("race-list-item").let(::RaceListItem) val notFromConsole = get("not-from-console") val operationCancelled = get("operation-cancelled") val noCharacter = get("no-character") val noCharacterOther = get("no-character-other") val noProfile = get("no-profile") val noMinecraftProfile = get("no-minecraft-profile") val noPermissionCharacterCardSelf = get("no-permission-character-card-self") val noPermissionCharacterCardOther = get("no-permission-character-card-other") val noPermissionCharacterList = get("no-permission-character-list") val noPermissionCharacterNew = get("no-permission-character-new") val noPermissionCharacterSetAge = get("no-permission-character-set-age") val noPermissionCharacterSetDead = get("no-permission-character-set-dead") val noPermissionCharacterSetDeadYes = get("no-permission-character-set-dead-yes") val noPermissionCharacterSetDeadNo = get("no-permission-character-set-dead-no") val noPermissionCharacterSetDescription = get("no-permission-character-set-description") val noPermissionCharacterSetGender = get("no-permission-character-set-gender") val noPermissionCharacterSetName = get("no-permission-character-set-name") val noPermissionCharacterSetRace = get("no-permission-character-set-race") val noPermissionCharacterHide = getParameterized("no-permission-character-hide") .let(::NoPermissionCharacterHideMessage) val noPermissionCharacterUnhide = getParameterized("no-permission-character-unhide") .let(::NoPermissionCharacterUnhideMessage) val noPermissionCharacterSwitch = get("no-permission-character-switch") val noPermissionCharacterDelete = get("no-permission-character-delete") val noPermissionRaceAdd = get("no-permission-race-add") val noPermissionRaceRemove = get("no-permission-race-remove") val noPermissionRaceList = get("no-permission-race-list") val deadCharacter = get("dead-character") val noProfileService = get("no-profile-service") val noMinecraftProfileService = get("no-minecraft-profile-service") val noCharacterService = get("no-character-service") val noCharacterCardFieldService = get("no-character-card-field-service") val noNewCharacterCooldownService = get("no-new-character-cooldown-service") val noRaceService = get("no-race-service") }
apache-2.0
5121508185a4bc948346f4ccf18a3d04
47.991736
116
0.698946
4.500759
false
false
false
false
hea3ven/Malleable
src/main/java/com/hea3ven/malleable/util/RecipesUtil.kt
1
3422
package com.hea3ven.malleable.util import com.hea3ven.malleable.metal.Metal import net.minecraft.block.Block import net.minecraft.init.Blocks import net.minecraft.init.Items import net.minecraft.item.* import net.minecraft.item.crafting.CraftingManager import net.minecraft.item.crafting.IRecipe import net.minecraftforge.fml.relauncher.ReflectionHelper import net.minecraftforge.oredict.OreDictionary import net.minecraftforge.oredict.ShapedOreRecipe import java.util.* fun getMetalRecipes(): List<IRecipe> { var recipes = mutableListOf<IRecipe>() val recipeList = CraftingManager.getInstance().recipeList!! for (recipe in ArrayList(recipeList)) { val output = recipe.recipeOutput if (output == null) continue if (recipe !is ShapedOreRecipe) continue if (output.item is ItemTool || output.item is ItemArmor || output.item is ItemHoe || output.item is ItemSword) continue val found = recipe.input.any { (it is ItemStack && it.item == Items.IRON_INGOT) || (it is List<*> && it.any { (it as ItemStack).item == Items.IRON_INGOT }) } if (!found) continue if (output.item == Items.IRON_INGOT || output.item == Item.getItemFromBlock(Blocks.IRON_BLOCK)) continue recipes.add(convertRecipe(recipe, Items.IRON_INGOT, Blocks.IRON_BLOCK, Metal.COPPER)) recipes.add(convertRecipe(recipe, Items.IRON_INGOT, Blocks.IRON_BLOCK, Metal.TIN)) recipes.add(convertRecipe(recipe, Items.IRON_INGOT, Blocks.IRON_BLOCK, Metal.COBALT)) recipes.add(convertRecipe(recipe, Items.IRON_INGOT, Blocks.IRON_BLOCK, Metal.TUNGSTEN)) } return recipes } private fun convertRecipe(recipe: ShapedOreRecipe, ingot: Item, block: Block, metal: Metal): IRecipe { return convertRecipe(recipe, mapOf(Pair("ingotIron", metal.ingotName), Pair("blockIron", metal.blockName)), mapOf(Pair(ingot, metal.ingotName), Pair(Item.getItemFromBlock(block)!!, metal.blockName))) } private fun convertRecipe(recipe: ShapedOreRecipe, oreTranslations: Map<String, String>, itemTranslations: Map<Item, String>): IRecipe { val width: Int = ReflectionHelper.getPrivateValue(ShapedOreRecipe::class.java, recipe, "width") val height: Int = ReflectionHelper.getPrivateValue(ShapedOreRecipe::class.java, recipe, "height") val recipeShape = Array(height, { "" }) val ingredientsMapping: MutableMap<Any, Char> = mutableMapOf() var c = 'a' var row = 0 var col = 0 for (input in recipe.input) { var resultInput = input if (input is List<*>) resultInput = getOreDictName(input) if (resultInput is ItemStack && itemTranslations.containsKey(resultInput.item)) resultInput = itemTranslations[resultInput.item] else if (resultInput is String && oreTranslations.containsKey(resultInput)) resultInput = oreTranslations[resultInput] var key = ingredientsMapping[resultInput] if (key == null) { if (resultInput != null) { key = c ingredientsMapping.put(resultInput, c++) } else { key = ' ' } } recipeShape[row] += key.toString() if (++col >= width) { row++ col = 0 } } val input = recipeShape.map { it }.plus(ingredientsMapping.flatMap { listOf(it.value, it.key) }) return ShapedOreRecipe(recipe.recipeOutput, *Array(input.size, { input[it] })) } private fun getOreDictName(input: List<*>): String { for (name in OreDictionary.getOreNames()) { if (OreDictionary.getOres(name) == input) return name } throw RuntimeException("Could not find ore name") }
mit
1360788d9e7bff9bf54d113825851d64
34.278351
102
0.734074
3.425425
false
false
false
false
luxons/seven-wonders
sw-server/src/main/kotlin/org/luxons/sevenwonders/server/repositories/LobbyRepository.kt
1
1090
package org.luxons.sevenwonders.server.repositories import org.luxons.sevenwonders.engine.data.GameDefinition import org.luxons.sevenwonders.server.lobby.Lobby import org.luxons.sevenwonders.server.lobby.Player import org.springframework.stereotype.Repository import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong @Repository class LobbyRepository { private val lobbies = ConcurrentHashMap<Long, Lobby>() private var lastGameId: AtomicLong = AtomicLong(0) fun list(): Collection<Lobby> = lobbies.values fun create(gameName: String, owner: Player): Lobby { val id = lastGameId.getAndIncrement() val lobby = Lobby(id, gameName, owner, GameDefinition.load()) lobbies[id] = lobby return lobby } fun find(lobbyId: Long): Lobby = lobbies[lobbyId] ?: throw LobbyNotFoundException(lobbyId) fun remove(lobbyId: Long): Lobby = lobbies.remove(lobbyId) ?: throw LobbyNotFoundException(lobbyId) } internal class LobbyNotFoundException(id: Long) : RuntimeException("Lobby not found for id '$id'")
mit
46c68200a955140b6fef76cbadbcb0c4
34.16129
103
0.756881
4.160305
false
false
false
false
stbanlol/Flash-torch-kotlin
app/src/main/java/com/example/egaviria/lintkotlin/MainActivity.kt
1
5666
package com.example.egaviria.lintkotlin import android.annotation.TargetApi import android.app.Activity import android.content.pm.PackageManager import android.hardware.Camera import android.os.Bundle import android.media.MediaPlayer import android.widget.ImageButton import android.hardware.Camera.Parameters import android.app.AlertDialog import android.content.Context import android.util.Log import android.widget.Toast import android.hardware.camera2.CameraManager import android.hardware.camera2.CameraAccessException import android.os.Build class MainActivity : Activity() { var btnSwitch: ImageButton? = null private var camera: Camera? = null private var isFlashOn: Boolean = false private var hasFlash: Boolean = false var params: Parameters? = null var mp: MediaPlayer? = null private var mCameraManager: CameraManager? = null private var mCameraId: String? = null @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) /* * First check if device is supporting flashlight or not */ hasFlash = getApplicationContext().getPackageManager() .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); if (!hasFlash) { // device doesn't support flash // Show alert message and close the application val alert = AlertDialog.Builder(this@MainActivity) .create() alert.setTitle("Error") alert.setMessage("Sorry, your device doesn't support flash light!") alert.setButton("OK") { dialog, which -> // closing the application finish() } alert.show() return } mCameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager try { mCameraId = mCameraManager!!.cameraIdList[0] } catch (e: CameraAccessException) { e.printStackTrace() } // flash switch button btnSwitch = findViewById(R.id.imageButtonLigth) /* * Switch click event to toggle flash on/off */ btnSwitch!!.setOnClickListener({ view -> changeState() }) } private fun changeState(){ // Toast.makeText(this@MainActivity, "cambio" + isFlashOn, Toast.LENGTH_SHORT).show() if (isFlashOn) { // turn off flash turnOffFlash() } else { // turn on flash turnOnFlash() } } // getting camera parameters private fun getCamera() { if (camera == null) { try { camera = Camera.open() params = camera!!.parameters } catch (e: RuntimeException) { Log.e("Failed to Open. Error: ", e.message) } } } /* * Turning On flash */ private fun turnOnFlash() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mCameraManager!!.setTorchMode(mCameraId, true) // playSound() }else{ if (camera == null || params == null) { return } // play sound // playSound() params = camera!!.parameters params!!.setFlashMode(Parameters.FLASH_MODE_TORCH) camera!!.parameters = params camera!!.startPreview() // changing button/switch image } isFlashOn = true toggleButtonImage() } catch (e: Exception) { e.printStackTrace() } } /* * Turning Off flash */ private fun turnOffFlash() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mCameraManager!!.setTorchMode(mCameraId, false) // playOnOffSound() }else{ if (camera == null || params == null) { return } // play sound // playSound() params = camera!!.getParameters() params!!.setFlashMode(Parameters.FLASH_MODE_OFF) camera!!.setParameters(params) camera!!.stopPreview() // changing button/switch image } isFlashOn = false toggleButtonImage() } catch (e: Exception) { e.printStackTrace() } } /* * Toggle switch button images * changing image states to on / off * */ private fun toggleButtonImage() { if (isFlashOn) { btnSwitch!!.setImageResource(R.mipmap.ic_ligth_on) } else { btnSwitch!!.setImageResource(R.mipmap.ic_ligth_off) } } override fun onDestroy() { super.onDestroy() turnOffFlash() } override fun onPause() { super.onPause() // on pause turn off the flash turnOffFlash() } override fun onRestart() { super.onRestart() } override fun onResume() { super.onResume() // on resume turn on the flash if (isFlashOn) turnOnFlash() } override fun onStart() { super.onStart() // on starting the app get the camera params getCamera() } override fun onStop() { super.onStop() // on stop release the camera if (camera != null) { camera!!.release() camera = null } } }
mit
c339c684754875510b6ca71923c119f2
24.408072
92
0.553477
4.888697
false
false
false
false
cketti/okhttp
okhttp/src/main/kotlin/okhttp3/Authenticator.kt
1
5578
/* * Copyright (C) 2015 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 okhttp3 import java.io.IOException import okhttp3.internal.authenticator.JavaNetAuthenticator /** * Performs either **preemptive** authentication before connecting to a proxy server, or * **reactive** authentication after receiving a challenge from either an origin web server or proxy * server. * * ## Preemptive Authentication * * To make HTTPS calls using an HTTP proxy server OkHttp must first negotiate a connection with * the proxy. This proxy connection is called a "TLS Tunnel" and is specified by * [RFC 2817][1]. The HTTP CONNECT request that creates this tunnel connection is special: it * does not participate in any [interceptors][Interceptor] or [event listeners][EventListener]. It * doesn't include the motivating request's HTTP headers or even its full URL; only the target * server's hostname is sent to the proxy. * * Prior to sending any CONNECT request OkHttp always calls the proxy authenticator so that it may * prepare preemptive authentication. OkHttp will call [authenticate] with a fake `HTTP/1.1 407 * Proxy Authentication Required` response that has a `Proxy-Authenticate: OkHttp-Preemptive` * challenge. The proxy authenticator may return either an authenticated request, or null to * connect without authentication. * * ``` * for (Challenge challenge : response.challenges()) { * // If this is preemptive auth, use a preemptive credential. * if (challenge.scheme().equalsIgnoreCase("OkHttp-Preemptive")) { * return response.request().newBuilder() * .header("Proxy-Authorization", "secret") * .build(); * } * } * return null; // Didn't find a preemptive auth scheme. * ``` * * ## Reactive Authentication * * Implementations authenticate by returning a follow-up request that includes an authorization * header, or they may decline the challenge by returning null. In this case the unauthenticated * response will be returned to the caller that triggered it. * * Implementations should check if the initial request already included an attempt to * authenticate. If so it is likely that further attempts will not be useful and the authenticator * should give up. * * When reactive authentication is requested by an origin web server, the response code is 401 * and the implementation should respond with a new request that sets the "Authorization" header. * * ``` * if (response.request().header("Authorization") != null) { * return null; // Give up, we've already failed to authenticate. * } * * String credential = Credentials.basic(...) * return response.request().newBuilder() * .header("Authorization", credential) * .build(); * ``` * * When reactive authentication is requested by a proxy server, the response code is 407 and the * implementation should respond with a new request that sets the "Proxy-Authorization" header. * * ``` * if (response.request().header("Proxy-Authorization") != null) { * return null; // Give up, we've already failed to authenticate. * } * * String credential = Credentials.basic(...) * return response.request().newBuilder() * .header("Proxy-Authorization", credential) * .build(); * ``` * * The proxy authenticator may implement preemptive authentication, reactive authentication, or * both. * * Applications may configure OkHttp with an authenticator for origin servers, or proxy servers, * or both. * * ## Authentication Retries * * If your authentication may be flaky and requires retries you should apply some policy * to limit the retries by the class of errors and number of attempts. To get the number of * attempts to the current point use this function. * * ``` * private int responseCount(Response response) { * int result = 1; * while ((response = response.priorResponse()) != null) { * result++; * } * return result; * } * ``` * * [1]: https://tools.ietf.org/html/rfc2817 */ interface Authenticator { /** * Returns a request that includes a credential to satisfy an authentication challenge in * [response]. Returns null if the challenge cannot be satisfied. * * The route is best effort, it currently may not always be provided even when logically * available. It may also not be provided when an authenticator is re-used manually in an * application interceptor, such as when implementing client-specific retries. */ @Throws(IOException::class) fun authenticate(route: Route?, response: Response): Request? companion object { /** An authenticator that knows no credentials and makes no attempt to authenticate. */ @JvmField val NONE: Authenticator = AuthenticatorNone() private class AuthenticatorNone : Authenticator { override fun authenticate(route: Route?, response: Response): Request? = null } /** An authenticator that uses the java.net.Authenticator global authenticator. */ @JvmField val JAVA_NET_AUTHENTICATOR: Authenticator = JavaNetAuthenticator() } }
apache-2.0
7aa2e4c1ae4c1102b21ee0dd94e76874
39.129496
100
0.723915
4.347623
false
false
false
false
sav007/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/GraphQLCompiler.kt
1
3422
package com.apollographql.apollo.compiler import com.apollographql.apollo.compiler.ir.CodeGenerationContext import com.apollographql.apollo.compiler.ir.CodeGenerationIR import com.apollographql.apollo.compiler.ir.ScalarType import com.apollographql.apollo.compiler.ir.TypeDeclaration import com.squareup.javapoet.JavaFile import com.squareup.moshi.Moshi import java.io.File class GraphQLCompiler { private val moshi = Moshi.Builder().build() private val irAdapter = moshi.adapter(CodeGenerationIR::class.java) fun write(args: Arguments) { val ir = irAdapter.fromJson(args.irFile.readText())!! val irPackageName = args.irFile.absolutePath.formatPackageName() val fragmentsPackage = if (irPackageName.isNotEmpty()) "$irPackageName.fragment" else "fragment" val typesPackage = if (irPackageName.isNotEmpty()) "$irPackageName.type" else "type" val customTypeMap = args.customTypeMap.supportedTypeMap(ir.typesUsed) val context = CodeGenerationContext( reservedTypeNames = emptyList(), typeDeclarations = ir.typesUsed, fragmentsPackage = fragmentsPackage, typesPackage = typesPackage, customTypeMap = customTypeMap, nullableValueType = args.nullableValueType, generateAccessors = args.generateAccessors, ir = ir, useSemanticNaming = args.useSemanticNaming) ir.writeJavaFiles(context, args.outputDir) } private fun CodeGenerationIR.writeJavaFiles(context: CodeGenerationContext, outputDir: File) { fragments.forEach { val typeSpec = it.toTypeSpec(context.copy()) JavaFile.builder(context.fragmentsPackage, typeSpec).build().writeTo(outputDir) } typesUsed.supportedTypeDeclarations().forEach { val typeSpec = it.toTypeSpec(context.copy()) JavaFile.builder(context.typesPackage, typeSpec).build().writeTo(outputDir) } if (context.customTypeMap.isNotEmpty()) { val typeSpec = CustomEnumTypeSpecBuilder(context.copy()).build() JavaFile.builder(context.typesPackage, typeSpec).build().writeTo(outputDir) } operations.map { OperationTypeSpecBuilder(it, fragments, context.useSemanticNaming) } .forEach { val packageName = it.operation.filePath.formatPackageName() val typeSpec = it.toTypeSpec(context.copy()) JavaFile.builder(packageName, typeSpec).build().writeTo(outputDir) } } private fun List<TypeDeclaration>.supportedTypeDeclarations() = filter { it.kind == TypeDeclaration.KIND_ENUM || it.kind == TypeDeclaration.KIND_INPUT_OBJECT_TYPE } private fun Map<String, String>.supportedTypeMap(typeDeclarations: List<TypeDeclaration>): Map<String, String> { val idScalarTypeMap = ScalarType.ID.name to (this[ScalarType.ID.name] ?: ClassNames.STRING.toString()) return typeDeclarations.filter { it.kind == TypeDeclaration.KIND_SCALAR_TYPE } .associate { it.name to (this[it.name] ?: ClassNames.OBJECT.toString()) } .plus(idScalarTypeMap) } companion object { const val FILE_EXTENSION = "graphql" val OUTPUT_DIRECTORY = listOf("generated", "source", "apollo") const val APOLLOCODEGEN_VERSION = "0.15.2" } data class Arguments( val irFile: File, val outputDir: File, val customTypeMap: Map<String, String>, val nullableValueType: NullableValueType, val generateAccessors: Boolean, val useSemanticNaming: Boolean) }
mit
e31ec30a9b05713ef57f7909fe41763e
41.246914
114
0.729398
4.320707
false
false
false
false
christophpickl/kpotpourri
common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/collection/CachedEntity.kt
1
405
package com.github.christophpickl.kpotpourri.common.collection class CachedEntity<T>( private val loader: () -> T ) { private var isValid = false private var cached: T? = null fun get(): T { if (!isValid || cached == null) { cached = loader() isValid = true } return cached!! } fun invalidate() { isValid = false } }
apache-2.0
f883778efa95528b09ec27ab11122d16
18.285714
62
0.54321
4.354839
false
false
false
false
kotlintest/kotlintest
kotest-core/src/commonMain/kotlin/io/kotest/core/spec/style/FunSpecDsl.kt
1
2884
package io.kotest.core.spec.style import io.kotest.core.Tag import io.kotest.core.extensions.TestCaseExtension import io.kotest.core.spec.SpecDsl import io.kotest.core.test.EnabledIf import io.kotest.core.test.TestContext import io.kotest.core.test.TestType import io.kotest.core.test.deriveTestConfig import kotlin.time.Duration import kotlin.time.ExperimentalTime /** * Defines the DSL for creating tests in the 'FunSpec' style */ @UseExperimental(ExperimentalTime::class) interface FunSpecDsl : SpecDsl { class TestBuilder( private val name: String, private val spec: FunSpecDsl ) { fun config( enabled: Boolean? = null, invocations: Int? = null, threads: Int? = null, tags: Set<Tag>? = null, timeout: Duration? = null, extensions: List<TestCaseExtension>? = null, enabledIf: EnabledIf? = null, test: suspend TestContext.() -> Unit ) { val config = spec.defaultConfig().deriveTestConfig(enabled, tags, extensions, timeout, enabledIf, invocations, threads) spec.addTest(name, test, config, TestType.Test) } } fun context(name: String, init: suspend ContextScope.() -> Unit) { addTest(name, { ContextScope(this, this@FunSpecDsl).init() }, defaultConfig(), TestType.Container) } @KotestDsl class ContextScope(private val context: TestContext, private val spec: FunSpecDsl) { suspend fun context(name: String, init: suspend ContextScope.() -> Unit) { context.registerTestCase( name, { ContextScope(this, [email protected]).init() }, spec.defaultConfig(), TestType.Container ) } inner class TestBuilder(val name: String) { @UseExperimental(ExperimentalTime::class) suspend fun config( enabled: Boolean? = null, tags: Set<Tag>? = null, timeout: Duration? = null, extensions: List<TestCaseExtension>? = null, enabledIf: EnabledIf?, test: suspend TestContext.() -> Unit ) { val config = spec.defaultConfig() .deriveTestConfig(enabled, tags, extensions, timeout, enabledIf) context.registerTestCase(name, test, config, TestType.Test) } } fun test(name: String) = TestBuilder(name) suspend fun test(name: String, test: suspend TestContext.() -> Unit) = context.registerTestCase(name, test, spec.defaultConfig(), TestType.Test) } fun test(name: String) = TestBuilder(name, this) /** * Adds a new root test case, with the given name and test function, using * the default test case config for this builder. */ fun test(name: String, test: suspend TestContext.() -> Unit) = addTest(name, test, defaultConfig(), TestType.Test) }
apache-2.0
c41f9d1becdbbcb127bd89c085b7e20f
32.534884
118
0.638696
4.349925
false
true
false
false
HughG/partial-order
partial-order-app/src/main/kotlin/org/tameter/kotlin/collections/MutableMultiSet.kt
1
1677
package org.tameter.kotlin.collections /** * Copyright (c) 2017 Hugh Greene ([email protected]). */ class MutableMultiSet<E>( wrapped: MutableMap<E, Int> = mutableMapOf() ) : Set<E> by wrapped.keys, MutableSet<E> { private val counts = wrapped.withDefaultValue { 0 } override fun add(element: E): Boolean = add(element, 1) override fun addAll(elements: Collection<E>): Boolean { return elements.fold(false) { added, element -> add(element) || added } } override fun clear() = counts.clear() override fun remove(element: E): Boolean = remove(element, 1) override fun removeAll(elements: Collection<E>): Boolean { return elements.fold(false) { removed, element -> remove(element) || removed } } override fun retainAll(elements: Collection<E>): Boolean { return elements.fold(false) { removed, element -> (elements.contains(element) && remove(element)) || removed } } override fun iterator(): MutableIterator<E> = counts.keys.iterator() fun count(element: E): Int = counts[element] fun addAndCount(element: E): Int { add(element) return counts[element] } fun add(element: E, count: Int): Boolean { val oldCount = counts[element] counts[element] = oldCount + count return oldCount == 0 } fun remove(element: E, count: Int): Boolean { if (!counts.containsKey(element)) { return false } val oldCount = counts[element] counts[element] = minOf(0, oldCount - count) return oldCount <= count } } fun <E> mutableMultiSetOf() = MutableMultiSet<E>()
mit
e36b77aaa702dbb2f5242e00a9630fdd
27.931034
86
0.623733
4.080292
false
false
false
false
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/features/widget/TriggerWidgetOnChange.kt
1
1788
package de.ph1b.audiobook.features.widget import androidx.datastore.core.DataStore import de.ph1b.audiobook.common.pref.CurrentBook import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.repo.BookRepo2 import de.ph1b.audiobook.playback.playstate.PlayStateManager import kotlinx.coroutines.MainScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.merge import kotlinx.coroutines.launch import javax.inject.Inject import javax.inject.Singleton @Singleton class TriggerWidgetOnChange @Inject constructor( @CurrentBook private val currentBook: DataStore<Book2.Id?>, private val repo: BookRepo2, private val playStateManager: PlayStateManager, private val widgetUpdater: WidgetUpdater ) { fun init() { MainScope().launch { anythingChanged().collect { widgetUpdater.update() } } } private fun anythingChanged(): Flow<Any?> { return merge(currentBookChanged(), playStateChanged(), bookIdChanged()) } private fun bookIdChanged(): Flow<Book2.Id?> { return currentBook.data.distinctUntilChanged() } private fun playStateChanged(): Flow<PlayStateManager.PlayState> { return playStateManager.playStateFlow().distinctUntilChanged() } private fun currentBookChanged(): Flow<Book2> { return currentBook.data.filterNotNull() .flatMapLatest { id -> repo.flow(id) } .filterNotNull() .distinctUntilChanged { previous, current -> previous.id == current.id && previous.content.chapters == current.content.chapters && previous.content.currentChapter == current.content.currentChapter } } }
lgpl-3.0
a5e011bd25eb536f58ce056e6d878e42
28.8
75
0.749441
4.425743
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/parser/grammar/module.kt
1
2745
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.parser.grammar import compiler.lexer.Keyword import compiler.lexer.Operator import compiler.matching.ResultCertainty import compiler.parser.grammar.dsl.describeAs import compiler.parser.grammar.dsl.postprocess import compiler.parser.grammar.dsl.sequence import compiler.parser.postproc.ImportPostprocessor import compiler.parser.postproc.ModuleDeclarationPostProcessor import compiler.parser.postproc.ModuleNamePostProcessor import compiler.parser.postproc.ModulePostProcessor val ModuleName = sequence { identifier() certainty = ResultCertainty.OPTIMISTIC atLeast(0) { operator(Operator.DOT) certainty = ResultCertainty.MATCHED identifier() } } .describeAs("module or package name") .postprocess(::ModuleNamePostProcessor) val ModuleDeclaration = sequence { keyword(Keyword.MODULE) certainty = ResultCertainty.MATCHED ref(ModuleName) operator(Operator.NEWLINE) } .describeAs("module declaration") .postprocess(::ModuleDeclarationPostProcessor) val ImportDeclaration = sequence { keyword(Keyword.IMPORT) certainty = ResultCertainty.MATCHED atLeast(1) { identifier() operator(Operator.DOT) } certainty = ResultCertainty.OPTIMISTIC identifier(acceptedOperators = listOf(Operator.TIMES)) operator(Operator.NEWLINE) } .describeAs("import declaration") .postprocess(::ImportPostprocessor) val Module = sequence { certainty = ResultCertainty.MATCHED atLeast(0) { optionalWhitespace() eitherOf(mismatchCertainty = ResultCertainty.DEFINITIVE) { ref(ModuleDeclaration) ref(ImportDeclaration) ref(VariableDeclaration) ref(StandaloneFunctionDeclaration) ref(StructDefinition) endOfInput() } certainty = ResultCertainty.DEFINITIVE } } .describeAs("module") .postprocess(::ModulePostProcessor)
lgpl-3.0
2098dc0438657a758560984e3b345fb9
29.853933
77
0.731148
4.807356
false
false
false
false
android/trackr
app-compose/src/main/java/com/example/android/trackr/compose/ui/TagChip.kt
1
1933
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trackr.compose.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.android.trackr.data.SeedData import com.example.android.trackr.data.Tag @Composable fun TagChip( tag: Tag, modifier: Modifier = Modifier ) { Text( text = tag.label, color = TrackrTheme.colors.tagText(tag.color), modifier = modifier .background( color = TrackrTheme.colors.tagBackground(tag.color), shape = MaterialTheme.shapes.small ) .padding(horizontal = 6.dp), ) } @Preview(showBackground = true) @Composable private fun PreviewTagChip() { TrackrTheme { Column { for (tag in SeedData.Tags) { TagChip(tag = tag) Spacer(modifier = Modifier.height(4.dp)) } } } }
apache-2.0
08b8fe8634106598e588fc751b48e436
30.688525
75
0.706156
4.148069
false
false
false
false
gravidence/gravifon
lastfm4k/src/main/kotlin/org/gravidence/lastfm4k/resilience/Retry.kt
1
2790
package org.gravidence.lastfm4k.resilience import kotlinx.datetime.* import mu.KotlinLogging import org.gravidence.lastfm4k.api.error.LastfmApiError import org.gravidence.lastfm4k.exception.LastfmApiException import org.gravidence.lastfm4k.exception.LastfmException import org.gravidence.lastfm4k.exception.LastfmNetworkException import org.gravidence.lastfm4k.misc.toLocalDateTime import kotlin.time.Duration import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes private val logger = KotlinLogging.logger {} /** * Retry implementation per Last.fm API [guideline](https://www.last.fm/api/scrobbling#error-handling-2). */ class Retry( val minWaitDuration: Duration = 1.minutes, val waitDurationMultiplier: Double = 2.toDouble(), val maxWaitDuration: Duration = 8.hours, val maxAttempts: Int = Int.MAX_VALUE ) { private var retryAfter: Instant? = null private var currentWaitDuration: Duration? = null private var currentAttempt: Int? = null @Synchronized fun <V> wrap(block: () -> V): V { val retryAfterFixed = retryAfter if (retryAfterFixed == null || Clock.System.now() >= retryAfterFixed) { try { return block() .also { success() } } catch (exc: LastfmApiException) { when (exc.response.error) { // TODO LastfmApiError.INVALID_SESSION_KEY also should be part of retry, but the nuance that kind of error won't be fixed by itself LastfmApiError.SERVICE_OFFLINE, LastfmApiError.TEMPORARY_UNAVAILABLE -> { failure() } else -> { logger.debug { "Not entering retry flow" } } } throw exc } catch (exc: LastfmNetworkException) { failure() throw exc } } else { throw LastfmException("Last.fm service call skipped, next retry after ${retryAfterFixed.toLocalDateTime()}") } } private fun success() { retryAfter = null currentWaitDuration = null currentAttempt = null } private fun failure() { val nextWaitDuration = currentWaitDuration?.times(waitDurationMultiplier) ?: minWaitDuration val nextAttempt = currentAttempt?.plus(1) ?: 1 if (nextWaitDuration < maxWaitDuration && nextAttempt < maxAttempts) { currentWaitDuration = nextWaitDuration currentAttempt = nextAttempt } retryAfter = Clock.System.now().plus(nextWaitDuration).also { logger.info { "Last.fm service call failed, next retry after ${it.toLocalDateTime()}" } } } }
mit
eff38c2478c9b8394239bdcc733243dc
34.329114
151
0.631541
4.596376
false
false
false
false
linuxyz/FirstExamples
src/main/kotlin/task-htmlbuilder.kt
1
1136
/** * Created by sysop on 6/28/2017. */ package com.ytzb.kotlin fun renderProductTable(): String { return html { table { tr (color = getTitleColor()){ td { text("Product") } td { text("Price") } td { text("Popularity") } } val products = getProducts() for ((idx, it) in products.withIndex()) { tr { td (color = getCellColor(idx, 0), align = "left") { text(it.description) } td (color = getCellColor(idx, 1), align = "right") { text(it.price) } td (color = getCellColor(idx, 2), align = "right") { text(it.popularity) } } } } }.toString() } fun getTitleColor() = "#b9c9fe" fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"
gpl-2.0
06daa37dc8cc12b75ec2f7a42260e0a3
28.128205
94
0.37588
4.580645
false
false
false
false
Kotlin/dokka
plugins/base/src/main/kotlin/transformers/pages/samples/SamplesTransformer.kt
1
7893
package org.jetbrains.dokka.base.transformers.pages.samples import com.intellij.psi.PsiElement import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet import org.jetbrains.dokka.Platform import org.jetbrains.dokka.analysis.AnalysisEnvironment import org.jetbrains.dokka.analysis.DokkaMessageCollector import org.jetbrains.dokka.analysis.DokkaResolutionFacade import org.jetbrains.dokka.analysis.EnvironmentAndFacade import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.renderers.sourceSets import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.DisplaySourceSet import org.jetbrains.dokka.model.doc.Sample import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.plugin import org.jetbrains.dokka.plugability.querySingle import org.jetbrains.dokka.transformers.pages.PageTransformer import org.jetbrains.kotlin.idea.kdoc.resolveKDocLink import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils internal const val KOTLIN_PLAYGROUND_SCRIPT = "<script src=\"https://unpkg.com/kotlin-playground@1\"></script>" abstract class SamplesTransformer(val context: DokkaContext) : PageTransformer { abstract fun processBody(psiElement: PsiElement): String abstract fun processImports(psiElement: PsiElement): String final override fun invoke(input: RootPageNode): RootPageNode = /** * Run from the thread of [Dispatchers.Default]. It can help to avoid a memory leaks in `ThreadLocal`s (that keep `URLCLassLoader`) * since we shut down Dispatchers. Default at the end of each task (see [org.jetbrains.dokka.DokkaConfiguration.finalizeCoroutines]). * Currently, all `ThreadLocal`s are in a compiler/IDE codebase. */ runBlocking(Dispatchers.Default) { val analysis = setUpAnalysis(context) input.transformContentPagesTree { page -> val samples = (page as? WithDocumentables)?.documentables?.flatMap { it.documentation.entries.flatMap { entry -> entry.value.children.filterIsInstance<Sample>().map { entry.key to it } } } samples?.fold(page as ContentPage) { acc, (sampleSourceSet, sample) -> acc.modified( content = acc.content.addSample(page, sampleSourceSet, sample.name, analysis), embeddedResources = acc.embeddedResources + KOTLIN_PLAYGROUND_SCRIPT ) } ?: page } } private fun setUpAnalysis(context: DokkaContext) = context.configuration.sourceSets.associateWith { sourceSet -> if (sourceSet.samples.isEmpty()) context.plugin<DokkaBase>() .querySingle { kotlinAnalysis }[sourceSet] // from sourceSet.sourceRoots else AnalysisEnvironment(DokkaMessageCollector(context.logger), sourceSet.analysisPlatform).run { if (analysisPlatform == Platform.jvm) { configureJdkClasspathRoots() } sourceSet.classpath.forEach(::addClasspath) addSources(sourceSet.samples.toList()) loadLanguageVersionSettings(sourceSet.languageVersion, sourceSet.apiVersion) val environment = createCoreEnvironment() val (facade, _) = createResolutionFacade(environment) EnvironmentAndFacade(environment, facade) } } private fun ContentNode.addSample( contentPage: ContentPage, sourceSet: DokkaSourceSet, fqName: String, analysis: Map<DokkaSourceSet, EnvironmentAndFacade> ): ContentNode { val facade = analysis[sourceSet]?.facade ?: return this.also { context.logger.warn("Cannot resolve facade for platform ${sourceSet.sourceSetID}") } val psiElement = fqNameToPsiElement(facade, fqName) ?: return this.also { context.logger.warn("Cannot find PsiElement corresponding to $fqName") } val imports = processImports(psiElement) val body = processBody(psiElement) val node = contentCode(contentPage.sourceSets(), contentPage.dri, createSampleBody(imports, body), "kotlin") return dfs(fqName, node) } protected open fun createSampleBody(imports: String, body: String) = """ |$imports |fun main() { | //sampleStart | $body | //sampleEnd |}""".trimMargin() private fun ContentNode.dfs(fqName: String, node: ContentCodeBlock): ContentNode { return when (this) { is ContentHeader -> copy(children.map { it.dfs(fqName, node) }) is ContentDivergentGroup -> @Suppress("UNCHECKED_CAST") copy(children.map { it.dfs(fqName, node) } as List<ContentDivergentInstance>) is ContentDivergentInstance -> copy( before.let { it?.dfs(fqName, node) }, divergent.dfs(fqName, node), after.let { it?.dfs(fqName, node) }) is ContentCodeBlock -> copy(children.map { it.dfs(fqName, node) }) is ContentCodeInline -> copy(children.map { it.dfs(fqName, node) }) is ContentDRILink -> copy(children.map { it.dfs(fqName, node) }) is ContentResolvedLink -> copy(children.map { it.dfs(fqName, node) }) is ContentEmbeddedResource -> copy(children.map { it.dfs(fqName, node) }) is ContentTable -> copy(children = children.map { it.dfs(fqName, node) as ContentGroup }) is ContentList -> copy(children.map { it.dfs(fqName, node) }) is ContentGroup -> copy(children.map { it.dfs(fqName, node) }) is PlatformHintedContent -> copy(inner.dfs(fqName, node)) is ContentText -> if (text == fqName) node else this is ContentBreakLine -> this else -> this.also { context.logger.error("Could not recognize $this ContentNode in SamplesTransformer") } } } private fun fqNameToPsiElement(resolutionFacade: DokkaResolutionFacade, functionName: String): PsiElement? { val packageName = functionName.takeWhile { it != '.' } val descriptor = resolutionFacade.resolveSession.getPackageFragment(FqName(packageName)) ?: return null.also { context.logger.warn("Cannot find descriptor for package $packageName") } val symbol = resolveKDocLink( BindingContext.EMPTY, resolutionFacade, descriptor, null, functionName.split(".") ).firstOrNull() ?: return null.also { context.logger.warn("Unresolved function $functionName in @sample") } return DescriptorToSourceUtils.descriptorToDeclaration(symbol) } private fun contentCode( sourceSets: Set<DisplaySourceSet>, dri: Set<DRI>, content: String, language: String, styles: Set<Style> = emptySet(), extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) = ContentCodeBlock( children = listOf( ContentText( text = content, dci = DCI(dri, ContentKind.Sample), sourceSets = sourceSets, style = emptySet(), extra = PropertyContainer.empty() ) ), language = language, dci = DCI(dri, ContentKind.Sample), sourceSets = sourceSets, style = styles + ContentStyle.RunnableSample + TextStyle.Monospace, extra = extra ) }
apache-2.0
f25177fad00c54d67cbf05a658618a63
46.263473
141
0.65273
4.930044
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/get/MovieGetExternalIds.kt
1
847
package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder("imdb_id", "facebook_id", "instagram_id", "twitter_id") class MovieGetExternalIds { @get:JsonProperty("imdb_id") @set:JsonProperty("imdb_id") @JsonProperty("imdb_id") var imdbId: String? = null @get:JsonProperty("facebook_id") @set:JsonProperty("facebook_id") @JsonProperty("facebook_id") var facebookId: Any? = null @get:JsonProperty("instagram_id") @set:JsonProperty("instagram_id") @JsonProperty("instagram_id") var instagramId: Any? = null @get:JsonProperty("twitter_id") @set:JsonProperty("twitter_id") @JsonProperty("twitter_id") var twitterId: Any? = null }
apache-2.0
c116457b4b14e8a55ebd2b21cd1262bf
29.285714
74
0.704841
3.731278
false
false
false
false
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/widget/FlowLayout.kt
1
4228
package io.noties.markwon.app.widget import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import io.noties.markwon.app.R import io.noties.markwon.app.utils.hidden import kotlin.math.max class FlowLayout(context: Context, attrs: AttributeSet) : ViewGroup(context, attrs) { private val spacingVertical: Int private val spacingHorizontal: Int init { val array = context.obtainStyledAttributes(attrs, R.styleable.FlowLayout) try { val spacing = array.getDimensionPixelSize(R.styleable.FlowLayout_fl_spacing, 0) spacingVertical = array.getDimensionPixelSize(R.styleable.FlowLayout_fl_spacingVertical, spacing) spacingHorizontal = array.getDimensionPixelSize(R.styleable.FlowLayout_fl_spacingHorizontal, spacing) } finally { array.recycle() } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { for (i in 0 until childCount) { val child = getChildAt(i) val params = child.layoutParams as LayoutParams val left = paddingLeft + params.x val top = paddingTop + params.y child.layout( left, top, left + child.measuredWidth, top + child.measuredHeight ) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val width = MeasureSpec.getSize(widthMeasureSpec) // we must have width (match_parent or exact dimension) if (width <= 0) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) return } val availableWidth = width - paddingLeft - paddingRight // child must not exceed our width val childWidthSpec = MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST) // we also could enforce flexible height here (instead of exact one) val childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) var x = 0 var y = 0 var lineHeight = 0 for (i in 0 until childCount) { val child = getChildAt(i) if (child.hidden) { continue } // measure child.measure(childWidthSpec, childHeightSpec) val params = child.layoutParams as LayoutParams val measuredWidth = child.measuredWidth if (measuredWidth > (availableWidth - x)) { // new line // make next child start at child measure width (starting at x = 0) params.x = 0 params.y = y + lineHeight + spacingVertical x = measuredWidth + spacingHorizontal // move vertically by max value of child height on this line y += lineHeight + spacingVertical lineHeight = child.measuredHeight } else { // we fit this line params.x = x params.y = y x += measuredWidth + spacingHorizontal lineHeight = max(lineHeight, child.measuredHeight) } } val height = y + lineHeight + paddingTop + paddingBottom setMeasuredDimension(width, height) } override fun generateDefaultLayoutParams(): ViewGroup.LayoutParams { return LayoutParams() } override fun checkLayoutParams(p: ViewGroup.LayoutParams?): Boolean { return p is LayoutParams } override fun generateLayoutParams(attrs: AttributeSet): ViewGroup.LayoutParams { return LayoutParams(context, attrs) } override fun generateLayoutParams(p: ViewGroup.LayoutParams): ViewGroup.LayoutParams { return LayoutParams(p) } class LayoutParams : ViewGroup.LayoutParams { constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(width: Int, height: Int) : super(width, height) constructor(params: ViewGroup.LayoutParams) : super(params) constructor() : this(WRAP_CONTENT, WRAP_CONTENT) var x: Int = 0 var y: Int = 0 } }
apache-2.0
7366a37c1194af1fee5341133c207224
32.299213
113
0.613056
5.162393
false
false
false
false
roylanceMichael/yaorm
yaorm.android/src/main/java/org/roylance/yaorm/android/AndroidProtoCursor.kt
1
3319
package org.roylance.yaorm.android import android.database.Cursor import android.util.Log import org.roylance.yaorm.YaormModel import org.roylance.yaorm.services.ICursor import org.roylance.yaorm.services.IStreamer import org.roylance.yaorm.utilities.YaormUtils import java.util.* import kotlin.collections.HashMap class AndroidProtoCursor( private val definitionModel: YaormModel.TableDefinition, private val cursor: Cursor) : ICursor { private val namesToAvoid = HashSet<String>() private val columnNamesNormalized = HashMap<String, String>() fun moveNext() : Boolean { return cursor.moveToNext() } fun getRecord(): YaormModel.Record { val newInstance = YaormModel.Record.newBuilder() definitionModel .columnDefinitionsList .distinctBy { it.name } .forEach { if (this.namesToAvoid.contains(it.name)) { val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it) newInstance.addColumns(propertyHolder) } else if (columnNamesNormalized.containsKey(it.name)) { try { val index = cursor.getColumnIndex(columnNamesNormalized[it.name]!!) val newValue = cursor.getString(index) val propertyHolder = YaormUtils.buildColumn(newValue, it) newInstance.addColumns(propertyHolder) } catch (e: Exception) { // if we can't see this name for w/e reason, we'll print to the console, but continue on // e.printStackTrace() Log.e("sqlite", e.message) this.namesToAvoid.add(it.name) val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it) newInstance.addColumns(propertyHolder) } } else { val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it) newInstance.addColumns(propertyHolder) } } return newInstance.build() } override fun getRecords(): YaormModel.Records { var i = 0 while (i < cursor.columnCount) { val sqliteColumnName = cursor.getColumnName(i) val sqliteColumnNameNormalized = sqliteColumnName.toLowerCase() definitionModel.columnDefinitionsList .filter { it.name.toLowerCase() == sqliteColumnNameNormalized } .forEach { columnNamesNormalized[it.name] = sqliteColumnName } i++ } val returnItems = YaormModel.Records.newBuilder() while (this.moveNext()) { returnItems.addRecords(this.getRecord()) } this.cursor.close() return returnItems.build() } override fun getRecordsStream(streamer: IStreamer) { while (this.moveNext()) { streamer.stream(this.getRecord()) } this.cursor.close() } }
mit
96bebed7ea48aea15f5a1967e834680b
38.058824
116
0.558301
5.405537
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/search/renderers/CodexAlertEmailRenderer.kt
1
4989
package com.openlattice.search.renderers import com.google.common.collect.Lists import com.google.common.collect.Maps import com.openlattice.data.requests.NeighborEntityDetails import com.openlattice.mail.RenderableEmailRequest import com.openlattice.search.requests.PersistentSearch import jodd.mail.EmailAttachment import org.apache.olingo.commons.api.edm.FullQualifiedName import java.io.ByteArrayOutputStream import java.io.IOException import java.net.URL import java.time.LocalDate import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.util.* import javax.imageio.ImageIO private const val FROM_EMAIL = "[email protected]" private const val TEMPLATE_PATH = "mail/templates/shared/CodexMessageAlertTemplate.mustache" private val PERSON_ENTITY_TYPE_ID = UUID.fromString("31cf5595-3fe9-4d3e-a9cf-39355a4b8cab") private val PHONE_NUMBER_FQN = FullQualifiedName("contact.phonenumber") private val MESSAGE_TEXT_FQN = FullQualifiedName("ol.text") private val DATETIME_FQN = FullQualifiedName("general.datetime") private val ATTACHMENT_FQN = FullQualifiedName("ol.imagedata") private val FIRST_NAME_FQN = FullQualifiedName("nc.PersonGivenName") private val LAST_NAME_FQN = FullQualifiedName("nc.PersonSurName") /* * * Search metadata is expected to contain the following fields: * { * "personEntitySetId": <UUID>, * "staffEntitySetId": <UUID>, * "timezone": <BHRTimeZone> * } * */ private const val TIME_ZONE_METADATA = "timezone" private const val CONVERSATION_URL_METADATA = "conversationURL" private const val TEXT_FIELD = "text" private const val PHONE_NUMBER_FIELD = "phoneNumber" private const val DATE_TIME_FIELD = "dateTime" class CodexAlertEmailRenderer { companion object { private fun getStringValue(entity: Map<FullQualifiedName, Set<Any>>, fqn: FullQualifiedName): String { return (entity[fqn] ?: emptySet()).joinToString(", ") } private fun getMessageDetails(message: Map<FullQualifiedName, Set<Any>>, timezone: MessageFormatters.TimeZones): Map<String, Any> { val tags = mutableMapOf<String, Any>() tags[TEXT_FIELD] = getStringValue(message, MESSAGE_TEXT_FQN) tags[PHONE_NUMBER_FIELD] = getStringValue(message, PHONE_NUMBER_FQN) (message[DATETIME_FQN] ?: emptySet()).map { val dateTime = OffsetDateTime.parse(it.toString()) tags[DATE_TIME_FIELD] = "${MessageFormatters.formatDate(dateTime, timezone)} at ${MessageFormatters.formatTime(dateTime, timezone)}" } return tags } fun getMetadataTemplateObjects(alertMetadata: Map<String, Any>): Map<String, Any> { val tags = mutableMapOf<String, Any>() tags[CONVERSATION_URL_METADATA] = alertMetadata[CONVERSATION_URL_METADATA]?.let { "<a href=\"$it\">$it</a>" } ?: "" return tags } private fun getSenderFromNeighbors(phoneNumber: String, neighbors: List<NeighborEntityDetails>): String { val personNeighbors = neighbors .filter { it.neighborEntitySet.isPresent && it.neighborEntitySet.get().entityTypeId == PERSON_ENTITY_TYPE_ID } .map { it.neighborDetails.get() } if (personNeighbors.isEmpty()) { return phoneNumber } val names = personNeighbors.joinToString(", ") { val first = it[FIRST_NAME_FQN]?.first() ?: "" val last = it[LAST_NAME_FQN]?.first() ?: "" arrayOf(first, last).joinToString(" ") } return "$names ($phoneNumber)" } fun renderEmail( persistentSearch: PersistentSearch, message: Map<FullQualifiedName, Set<Any>>, userEmail: String, neighbors: List<NeighborEntityDetails> ): RenderableEmailRequest { val templateObjects: MutableMap<String, Any> = mutableMapOf() val timezone = MessageFormatters.TimeZones.valueOf(persistentSearch.alertMetadata[TIME_ZONE_METADATA].toString()) templateObjects.putAll(getMessageDetails(message, timezone)) templateObjects.putAll(getMetadataTemplateObjects(persistentSearch.alertMetadata)) val sender = getSenderFromNeighbors(templateObjects[PHONE_NUMBER_FIELD].toString(), neighbors) val subject = "New Text Message From $sender" templateObjects["subscriber"] = userEmail return RenderableEmailRequest( Optional.of(FROM_EMAIL), arrayOf(userEmail) + persistentSearch.additionalEmailAddresses, Optional.empty(), Optional.empty(), TEMPLATE_PATH, Optional.of(subject), Optional.of(templateObjects), Optional.empty(), Optional.empty() ) } } }
gpl-3.0
8fb0d9bfd250c8a80a823017d688c127
36.80303
148
0.661455
4.577064
false
false
false
false
orbit/orbit
src/orbit-client/src/main/kotlin/orbit/client/addressable/CapabilitiesScanner.kt
1
4028
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.client.addressable import io.github.classgraph.ClassGraph import mu.KotlinLogging import orbit.client.OrbitClientConfig import orbit.util.time.Clock import orbit.util.time.stopwatch internal class CapabilitiesScanner( private val clock: Clock, config: OrbitClientConfig ) { private val logger = KotlinLogging.logger {} private val packagePaths = config.packages.toTypedArray() lateinit var addressableInterfaces: List<AddressableClass> private set lateinit var addressableClasses: List<AddressableClass> private set lateinit var interfaceLookup: Map<AddressableClass, AddressableClass> private set fun scan() { logger.info("Scanning for node capabilities...") stopwatch(clock) { val classGraph = ClassGraph() .enableAllInfo() .whitelistPackages(*packagePaths) classGraph.scan().use { scan -> addressableInterfaces = scan .getClassesImplementing(Addressable::class.java.name) .interfaces .filter { !it.hasAnnotation(NonConcrete::class.java.name) } .map { @Suppress("UNCHECKED_CAST") it.loadClass() as AddressableClass } addressableClasses = scan .getClassesImplementing(Addressable::class.java.name) .standardClasses .filter { !it.hasAnnotation(NonConcrete::class.java.name) } .filter { !it.isAbstract } .map { @Suppress("UNCHECKED_CAST") it.loadClass() as AddressableClass } interfaceLookup = mutableMapOf<AddressableClass, AddressableClass>().apply { addressableClasses.forEach { implClass -> resolveMapping(implClass).also { mapped -> check(!mapped.isEmpty()) { "Could not find mapping for ${implClass.name}" } mapped.forEach { iface -> check(!this.containsKey(iface)) { "Multiple implementations of concrete interface ${iface.name} found." } this[iface] = implClass } } } } } }.also { (elapsed, _) -> logger.debug { "Addressable Interfaces: $addressableInterfaces" } logger.debug { "Addressable Classes: $addressableClasses" } logger.debug { "Implemented Addressables: $interfaceLookup" } logger.info { "Node capabilities scan complete in ${elapsed}ms. " + "${interfaceLookup.size} implemented addressable(s) found. " + "${addressableInterfaces.size} addressable interface(s) found. " + "${addressableClasses.size} addressable class(es) found. " } } } private fun resolveMapping( crawl: Class<*>, list: MutableList<AddressableClass> = mutableListOf() ): Collection<AddressableClass> { if (crawl.interfaces.isEmpty()) return list for (iface in crawl.interfaces) { if (Addressable::class.java.isAssignableFrom(iface)) { if (!iface.isAnnotationPresent(NonConcrete::class.java)) { @Suppress("UNCHECKED_CAST") list.add(iface as AddressableClass) } if (iface.interfaces.isNotEmpty()) resolveMapping(iface, list) } } return list } }
bsd-3-clause
ad0b79b90645d52f0425fc3d9dcd0c8a
37.740385
137
0.540715
5.586685
false
false
false
false
pnemonic78/RemoveDuplicates
duplicates-android/app/src/main/java/com/github/duplicates/bookmark/BookmarkViewHolder.kt
1
4209
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.duplicates.bookmark import android.content.Context import android.text.format.DateUtils import android.view.ViewGroup import com.github.android.removeduplicates.BuildConfig import com.github.android.removeduplicates.R import com.github.android.removeduplicates.databinding.SameBookmarkBinding import com.github.duplicates.DuplicateItemPair import com.github.duplicates.DuplicateViewHolder import com.github.duplicates.SHOW_DATE_TIME import com.github.duplicates.bookmark.BookmarkComparator.Companion.CREATED import com.github.duplicates.bookmark.BookmarkComparator.Companion.DATE import com.github.duplicates.bookmark.BookmarkComparator.Companion.FAVICON import com.github.duplicates.bookmark.BookmarkComparator.Companion.TITLE import com.github.duplicates.bookmark.BookmarkComparator.Companion.URL /** * View holder of a duplicate bookmark. * * @author moshe.w */ class BookmarkViewHolder( itemView: ViewGroup, binding: SameBookmarkBinding, onCheckedChangeListener: OnItemCheckedChangeListener<BookmarkItem>? = null ) : DuplicateViewHolder<BookmarkItem>(itemView, onCheckedChangeListener) { private val match = binding.match private val checkbox1 = binding.item1.checkbox private val created1 = binding.item1.created private val date1 = binding.item1.date private val icon1 = binding.item1.icon private val title1 = binding.item1.title private val url1 = binding.item1.url private val checkbox2 = binding.item2.checkbox private val created2 = binding.item2.created private val date2 = binding.item2.date private val icon2 = binding.item2.icon private val title2 = binding.item2.title private val url2 = binding.item2.url init { checkbox1.setOnClickListener { onCheckedChangeListener?.onItemCheckedChangeListener(item1, checkbox1.isChecked) } checkbox2.setOnClickListener { onCheckedChangeListener?.onItemCheckedChangeListener(item2, checkbox2.isChecked) } } override fun bindHeader(context: Context, pair: DuplicateItemPair<BookmarkItem>) { match.text = context.getString(R.string.match, percentFormatter.format(pair.match.toDouble())) } override fun bindItem1(context: Context, item: BookmarkItem) { checkbox1.isChecked = item.isChecked checkbox1.text = if (BuildConfig.DEBUG) item.id.toString() else "" created1.text = DateUtils.formatDateTime(context, item.created, SHOW_DATE_TIME) date1.text = DateUtils.formatDateTime(context, item.date, SHOW_DATE_TIME) icon1.setImageBitmap(item.icon) title1.text = item.title url1.text = item.uri?.toString() } override fun bindItem2(context: Context, item: BookmarkItem) { checkbox2.isChecked = item.isChecked checkbox2.text = if (BuildConfig.DEBUG) item.id.toString() else "" created2.text = DateUtils.formatDateTime(context, item.created, SHOW_DATE_TIME) date2.text = DateUtils.formatDateTime(context, item.date, SHOW_DATE_TIME) icon2.setImageBitmap(item.icon) title2.text = item.title url2.text = item.uri?.toString() } override fun bindDifference(context: Context, pair: DuplicateItemPair<BookmarkItem>) { val difference = pair.difference bindDifference(created1, created2, difference[CREATED]) bindDifference(date1, date2, difference[DATE]) bindDifference(icon1, icon2, difference[FAVICON]) bindDifference(title1, title2, difference[TITLE]) bindDifference(url1, url2, difference[URL]) } }
apache-2.0
e0099656ba8ef2ce03febb5f3d065941
39.864078
93
0.742219
4.264438
false
false
false
false
http4k/http4k
src/docs/guide/reference/contracts/example.kt
1
4085
package guide.reference.contracts // for this example we're using Jackson - note that the auto method imported is an extension // function that is defined on the Jackson instance import org.http4k.contract.ContractRoute import org.http4k.contract.bind import org.http4k.contract.contract import org.http4k.contract.div import org.http4k.contract.meta import org.http4k.contract.openapi.ApiInfo import org.http4k.contract.openapi.v3.OpenApi3 import org.http4k.contract.security.ApiKeySecurity import org.http4k.core.Body import org.http4k.core.ContentType.Companion.TEXT_PLAIN import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.with import org.http4k.format.Jackson import org.http4k.format.Jackson.auto import org.http4k.lens.Path import org.http4k.lens.Query import org.http4k.lens.int import org.http4k.lens.string import org.http4k.routing.routes // this route has a dynamic path segment fun greetRoute(): ContractRoute { // these lenses define the dynamic parts of the request that will be used in processing val ageQuery = Query.int().required("age") val stringBody = Body.string(TEXT_PLAIN).toLens() // this specifies the route contract, with the desired contract of path, headers, queries and body parameters. val spec = "/greet" / Path.of("name") meta { summary = "tells the user hello!" queries += ageQuery receiving(stringBody) } bindContract GET // the this function will dynamically supply a new HttpHandler for each call. The number of parameters // matches the number of dynamic sections in the path (1) fun greet(nameFromPath: String): HttpHandler = { request: Request -> val age = ageQuery(request) val sentMessage = stringBody(request) Response(OK).with(stringBody of "hello $nameFromPath you are $age. You sent $sentMessage") } return spec to ::greet } data class NameAndMessage(val name: String, val message: String) // this route uses auto-marshalling to convert the JSON body directly to/from a data class instance fun echoRoute(): ContractRoute { // the body lens here is imported as an extension function from the Jackson instance val body = Body.auto<NameAndMessage>().toLens() // this specifies the route contract, including examples of the input and output body objects - they will // get exploded into JSON schema in the OpenAPI docs val spec = "/echo" meta { summary = "echoes the name and message sent to it" receiving(body to NameAndMessage("jim", "hello!")) returning(OK, body to NameAndMessage("jim", "hello!")) } bindContract POST // note that because we don't have any dynamic parameters, we can use a HttpHandler instance instead of a function val echo: HttpHandler = { request: Request -> val received: NameAndMessage = body(request) Response(OK).with(body of received) } return spec to echo } // use another Lens to set up the API-key - the answer is 42! val mySecurity = ApiKeySecurity(Query.int().required("reference/api"), { it == 42 }) // Combine the Routes into a contract and bind to a context, defining a renderer (in this example // OpenApi/Swagger) and a security model (in this case an API-Key): val contract = contract { renderer = OpenApi3(ApiInfo("My great API", "v1.0"), Jackson) descriptionPath = "/swagger.json" security = mySecurity routes += greetRoute() routes += echoRoute() } val handler: HttpHandler = routes("/reference/api/v1" bind contract) // by default, the OpenAPI docs live at the root of the contract context, but we can override it.. fun main() { println(handler(Request(GET, "/reference/api/v1/swagger.json"))) println( handler( Request(POST, "/reference/api/v1/echo") .query("reference/api", "42") .body("""{"name":"Bob","message":"Hello"}""") ) ) }
apache-2.0
6dfc89b7c5a2caffe41655914934a2b9
36.824074
118
0.716524
3.912835
false
false
false
false
square/duktape-android
zipline-bytecode/src/main/kotlin/app/cash/zipline/bytecode/SourceMap.kt
1
4897
/* * Copyright (C) 2021 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 * * 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 app.cash.zipline.bytecode import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import okio.Buffer import okio.BufferedSource import okio.IOException @Serializable internal data class SourceMapJson( val version: Int, val file: String? = null, val sources: List<String>, val sourcesContent: List<String?>, val names: List<String>, val mappings: String, ) internal data class Group( val segments: List<Segment>, ) internal data class Segment( val startingColumn: Long, val source: String?, val sourceLine: Long, val sourceColumn: Long, val name: String?, ) internal data class SourceMap( val version: Int, val file: String?, val sourcesContent: List<String?>, val groups: List<Group>, ) { fun find(lineNumber: Int): Segment? { if (lineNumber < 1 || lineNumber > groups.size) return null return groups[lineNumber - 1].segments.firstOrNull() } companion object { /** * Parses the contents of a source map file to enable mapping from the elements in the * transformed (e.g. minified) source to the elements in the original source. This is an * implementation of the [Source Map Revision 3 Proposal](https://sourcemaps.info/spec.html). * * @param sourceMapJson contents of the source map file in JSON format. */ fun parse(sourceMapJson: String): SourceMap { val sourceMap = Json.decodeFromString(SourceMapJson.serializer(), sourceMapJson) val buffer = Buffer() var sourceIndex = 0 var sourceLine = 0L var sourceColumn = 0L var nameIndex = 0 val groups = mutableListOf<Group>() for (group in sourceMap.mappings.split(";")) { var startingColumn = 0L val segments = mutableListOf<Segment>() for (segment in group.split(",")) { if (segment.isEmpty()) continue buffer.writeUtf8(segment) startingColumn += buffer.readVarint() // Read an optional updated source file, column, and row. if (!buffer.exhausted()) { sourceIndex += buffer.readVarint().toInt() sourceLine += buffer.readVarint() sourceColumn += buffer.readVarint() } // Read an optional name. if (!buffer.exhausted()) { nameIndex += buffer.readVarint().toInt() } if (!buffer.exhausted()) { throw IOException("unexpected part: $segment") } check(sourceIndex >= -1) check(nameIndex >= -1) check(sourceLine >= -1) { "unexpected source line: $sourceLine" } check(sourceColumn >= -1) val source = sourceMap.sources.elementAtOrNull(sourceIndex) val name = sourceMap.names.elementAtOrNull(nameIndex) segments += Segment( startingColumn = startingColumn + 1, source = source, sourceLine = sourceLine + 1, sourceColumn = sourceColumn + 1, name = name, ) } groups += Group(segments) } return SourceMap( version = sourceMap.version, file = sourceMap.file, sourcesContent = sourceMap.sourcesContent, groups = groups, ) } } } internal fun BufferedSource.readVarint(): Long { var shift = 0 var result = 0L while (!exhausted()) { val b = readBase64Character() result += (b and 0x1F) shl shift if ((b and 0x20) == 0) { val unsigned = result ushr 1 return when { (result and 0x1) == 0x1L -> -unsigned else -> unsigned } } shift += 5 } throw IOException("malformed varint") } internal fun BufferedSource.readBase64Character(): Int { return when (val c = readByte().toInt().toChar()) { in 'A'..'Z' -> { // char ASCII value // A 65 0 // Z 90 25 (ASCII - 65) c.code - 65 } in 'a'..'z' -> { // char ASCII value // a 97 26 // z 122 51 (ASCII - 71) c.code - 71 } in '0'..'9' -> { // char ASCII value // 0 48 52 // 9 57 61 (ASCII + 4) c.code + 4 } '+', '-' -> 62 '/', '_' -> 63 else -> throw IOException("Unexpected character") } }
apache-2.0
47613518ae8784bcd3a2cf939a038905
26.982857
97
0.603022
4.214286
false
false
false
false
kareez/dahgan
core/src/main/kotlin/io/dahgan/parser/Token.kt
1
2610
package io.dahgan.parser /** * Result tokens * * The parsing result is a stream of tokens rather than a parse tree. The idea is to * convert the YAML input into byte codes. These byte codes are intended to be written * into a byte codes file (or more likely a UNIX pipe) for further processing. */ /** * Parsed token. */ data class Token( /** * 0-base byte offset in stream. */ val byteOffset: Int, /** * 0-base character offset in stream. */ val charOffset: Int, /** * 1-based line number. */ val line: Int, /** * 0-based character in line. */ val lineChar: Int, /** * Specific token 'Code'. */ val code: Code, /** * Contained input chars, if any. */ val text: Escapable ) { /** * Converts a 'Token' to two YEAST lines: a comment with the position numbers and the actual token line. */ override fun toString() = "# B: $byteOffset, C: $charOffset, L: $line, c: $lineChar\n$code$text\n" } /** * A container to keep the input, as normal text or array of codes, and lazily escape them if needed. */ sealed class Escapable { companion object { fun of(text: IntArray): Escapable = Code(text) fun of(text: String): Escapable = Text(text) } class Code(private val codes: IntArray) : Escapable() { override fun toString(): String = escape(codes, "") } class Text(val text: String) : Escapable() { override fun toString(): String = text } } /** * Escapes the given character (code) if needed. */ fun escape(code: Int): String = when { ' '.toInt() <= code && code != '\\'.toInt() && code <= '~'.toInt() -> "${code.toChar()}" code <= 0xFF -> "\\x${toHex(2, code)}" code in 256..0xFFFF -> "\\u${toHex(4, code)}" else -> "\\U${toHex(8, code)}" } /** * Escapes all the non-ASCII characters in the given text, as well as escaping * the \\ character, using the \\xXX, \\uXXXX and \\UXXXXXXXX escape sequences. */ fun escape(text: IntArray, separator: String = ", "): String = text.joinToString(separator, transform = ::escape) /** * Converts the int to the specified number of hexadecimal digits. */ fun toHex(digits: Int, n: Int): String = if (digits == 1) "${intToDigit(n)}" else "${toHex(digits - 1, n / 16)}${intToDigit(n % 16)}" fun intToDigit(n: Int): Char = if (n < 10) (48 + n).toChar() else (87 + n).toChar() /** * Converts a list of tokens to a multi-line YEAST text. */ fun showTokens(tokens: List<Token>): String = tokens.fold("") { text, token -> text + token.toString() }
apache-2.0
fa50fa3258e6cb769d4b9e8f7f921d11
25.1
113
0.601533
3.5318
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/Note.kt
1
880
package de.westnordost.streetcomplete.data.osmnotes import de.westnordost.streetcomplete.data.osm.mapdata.LatLon import de.westnordost.streetcomplete.data.user.User import kotlinx.serialization.Serializable @Serializable data class Note( val position: LatLon, val id: Long, val timestampCreated: Long, val timestampClosed: Long?, val status: Status, val comments: List<NoteComment>, ) { val isOpen get() = status == Status.OPEN val isClosed get() = status == Status.CLOSED val isHidden get() = status == Status.HIDDEN enum class Status { OPEN, CLOSED, HIDDEN } } @Serializable data class NoteComment( val timestamp: Long, val action: Action, val text: String?, val user: User?, ) { val isAnonymous get() = user == null enum class Action { OPENED, COMMENTED, CLOSED, REOPENED, HIDDEN } }
gpl-3.0
cb3ee2b250ca39fd68fcb398dc5bc4d9
22.783784
60
0.686364
4.074074
false
false
false
false
pdvrieze/ProcessManager
PMEditor/src/main/java/nl/adaptivity/diagram/android/AndroidPen.kt
1
6177
/* * Copyright (c) 2017. * * 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.diagram.android import android.graphics.Paint import android.graphics.Paint.* import android.graphics.Typeface import android.support.annotation.ColorInt import android.support.annotation.FloatRange import android.support.annotation.IntRange import android.support.annotation.NonNull import nl.adaptivity.diagram.Pen import nl.adaptivity.diagram.Rectangle import kotlin.math.abs class AndroidPen(paint: Paint) : Pen<AndroidPen> { val paint: Paint = paint.apply { style = Style.STROKE } override var strokeWidth: Double = 0.0 set(@FloatRange(from = 0.0, to = java.lang.Float.MAX_VALUE.toDouble(), fromInclusive = false) value) { field = value paint.strokeWidth = value.toFloat() } private var shadowRadius = -1f private var shadowColor = 0 private var shadowDx = 0f private var shadowDy = 0f override var fontSize: Double = Double.NaN set(@FloatRange(from = 0.0, fromInclusive = false) fontSize) { paint.textAlign = Align.LEFT paint.textSize = fontSize.toFloat() field = fontSize } private var _fontMetrics: FontMetrics? = null private val fontMetrics: FontMetrics get() { return _fontMetrics ?: kotlin.run { val ts = paint.textSize paint.textSize = fontSize.toFloat() paint.fontMetrics.also { _fontMetrics = it paint.textSize = ts } } } override val textMaxAscent: Double get() = abs(fontMetrics.top).toDouble() override val textAscent: Double get() = abs(fontMetrics.ascent).toDouble() override val textMaxDescent: Double get() = abs(fontMetrics.bottom).toDouble() override val textDescent: Double get() { return abs(fontMetrics.descent).toDouble() } override val textLeading: Double get() = fontMetrics.run { abs(top).toDouble() + abs(bottom) - abs(ascent) - abs(descent) } override var isTextItalics: Boolean get() = paint.typeface.isItalic set(italics) = updateStyle(italics, Typeface.ITALIC) override var isTextBold: Boolean get() = paint.typeface.isBold set(bold) = updateStyle(bold, Typeface.BOLD) override fun setColor(@IntRange(from = 0, to = 255) red: Int, @IntRange(from = 0, to = 255) green: Int, @IntRange(from = 0, to = 255) blue: Int): AndroidPen = apply { paint.setARGB(255, red, green, blue) } override fun setColor(@IntRange(from = 0, to = 255) red: Int, @IntRange(from = 0, to = 255) green: Int, @IntRange(from = 0, to = 255) blue: Int, @IntRange(from = 0, to = 255) alpha: Int): AndroidPen = apply { paint.setARGB(alpha, red, green, blue) } override fun setStrokeWidth(strokeWidth: Double): AndroidPen = apply { this.strokeWidth = strokeWidth } override fun setFontSize(fontSize: Double): AndroidPen = apply { this.fontSize = fontSize } fun setShadowLayer(@FloatRange(from = 0.0, fromInclusive = false) radius: Float, @ColorInt color: Int) { shadowRadius = radius shadowColor = color shadowDx = 0f shadowDy = 0f paint.setShadowLayer(radius, shadowDx, shadowDy, color) } @NonNull fun scale(@FloatRange(from = 0.0, fromInclusive = false) scale: Double) = apply { paint.strokeWidth = (strokeWidth * scale).toFloat() if (shadowRadius > 0f) { paint.setShadowLayer((shadowRadius * scale).toFloat(), (shadowDx * scale).toFloat(), (shadowDy * scale).toFloat(), shadowColor) } if (!fontSize.isNaN()) { paint.textSize = (fontSize * scale).toFloat() } } override fun measureTextWidth(text: String, @FloatRange(from = 0.0, fromInclusive = false) foldWidth: Double): Double { paint.withTextSize(fontSize * FONT_MEASURE_FACTOR) { return paint.measureText(text).toDouble() / FONT_MEASURE_FACTOR } } @NonNull @Override override fun measureTextSize(dest: Rectangle, x: Double, y: Double, text: String, foldWidth: Double) = dest.apply { paint.withTextSize(fontSize * FONT_MEASURE_FACTOR) { val left = x val width = paint.measureText(text).toDouble() / FONT_MEASURE_FACTOR val fm = fontMetrics val top = y + fm.top - fm.leading / 2 val height = fm.leading.toDouble() + fm.top + fm.bottom set(left, top, width, height) } } private fun updateStyle(enabled: Boolean, styleBits: Int) { val oldTypeface = paint.typeface val style: Int = when (oldTypeface) { null -> if (enabled) styleBits else Typeface.NORMAL else -> (oldTypeface.style and styleBits.inv()) or (if (enabled) styleBits else Typeface.NORMAL) } paint.typeface = Typeface.create(oldTypeface, style) } companion object { private const val FONT_MEASURE_FACTOR = 3f } } private inline fun <R> Paint.withTextSize(size: Double, body: () -> R): R { val origSize = textSize textSize = size.toFloat() try { return body() } finally { textSize = origSize } }
lgpl-3.0
393578f241e152b11533d6301328400d
33.132597
119
0.618585
4.337781
false
false
false
false
IntershopCommunicationsAG/scmversion-gradle-plugin
src/main/kotlin/com/intershop/gradle/scm/utils/PrefixConfig.kt
1
3830
/* * Copyright 2020 Intershop Communications AG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intershop.gradle.scm.utils import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import javax.inject.Inject /** * This is the configuration class for the necessary prefixes * on special branches, so that it is possible to identify the * relevant branches and tags for version calculation. */ abstract class PrefixConfig: IPrefixConfig { /** * Inject service of ObjectFactory (See "Service injection" in Gradle documentation. */ @get:Inject abstract val objectFactory: ObjectFactory private val stabilizationPrefixProperty: Property<String> = objectFactory.property(String::class.java) private val featurePrefixxProperty: Property<String> = objectFactory.property(String::class.java) private val hotfixPrefixProperty: Property<String> = objectFactory.property(String::class.java) private val bugfixPrefixProperty: Property<String> = objectFactory.property(String::class.java) private val tagPrefixProperty: Property<String> = objectFactory.property(String::class.java) private val prefixSeperatorProperty: Property<String> = objectFactory.property(String::class.java) private val branchPrefixSeperatorProperty: Property<String> = objectFactory.property(String::class.java) private val tagPrefixSeperatorProperty: Property<String> = objectFactory.property(String::class.java) init { stabilizationPrefixProperty.convention("SB") featurePrefixxProperty.convention("FB") hotfixPrefixProperty.convention("HB") bugfixPrefixProperty.convention("BB") tagPrefixProperty.convention("RELEASE") prefixSeperatorProperty.convention("_") } /** * Prefix for stabilization branches. * * @property stabilizationPrefix */ override var stabilizationPrefix: String by stabilizationPrefixProperty /** * Prefix for feature branches. * * @property featurePrefix */ override var featurePrefix: String by featurePrefixxProperty /** * Prefix for hotfix branches. * * @property stabilizationPrefix */ override var hotfixPrefix: String by hotfixPrefixProperty /** * Prefix for bugfix branches. * * @property bugfixPrefixProperty */ override var bugfixPrefix: String by bugfixPrefixProperty /** * Prefix for release tags. * * @property tagPrefixProperty */ override var tagPrefix: String by tagPrefixProperty /** * Separator between prefix and version. * * @property prefixSeperatorProperty */ override var prefixSeperator: String by prefixSeperatorProperty /** * Separator between prefix and version for branches. * * @property branchPrefixSeperator */ override var branchPrefixSeperator: String? get() = branchPrefixSeperatorProperty.orNull set(value) = branchPrefixSeperatorProperty.set(value) /** * Separator between prefix and version for tags. * * @property tagPrefixSeperator */ override var tagPrefixSeperator: String? get() = tagPrefixSeperatorProperty.orNull set(value) = tagPrefixSeperatorProperty.set(value) }
apache-2.0
cafc65e70c95f1fba280b865bce5ee42
32.596491
108
0.718016
4.811558
false
false
false
false
dafi/commonutils
app/src/main/java/com/ternaryop/utils/network/Resolver.kt
1
1739
package com.ternaryop.utils.network import java.io.IOException import java.io.OutputStream import java.net.HttpURLConnection import java.net.URL import java.net.URLConnection private const val BUFFER_SIZE = 100 * 1024 /* Resolve a possible shorten url to the original one */ fun URL.resolveShorten(): URL { val conn: URLConnection return try { conn = openConnection() conn.headerFields conn.url } catch (e: Exception) { this } } /** * Handle the case the url is redirected to a location with different protocol (eg from http to https or viceversa) * @return the open connection * @throws java.io.IOException */ @Throws(IOException::class) fun URL.openConnectionFollowingDifferentProtocols(): HttpURLConnection { var url = this var conn: HttpURLConnection var location: String var continueFollow = true do { conn = url.openConnection() as HttpURLConnection conn.instanceFollowRedirects = false when (conn.responseCode) { HttpURLConnection.HTTP_MOVED_PERM, HttpURLConnection.HTTP_MOVED_TEMP -> { location = conn.getHeaderField("Location") // Deal with relative URLs url = URL(url, location) } else -> continueFollow = false } } while (continueFollow) return conn } @Throws(IOException::class) fun URL.saveURL(os: OutputStream) { var connection: HttpURLConnection? = null try { connection = openConnection() as HttpURLConnection connection.inputStream?.use { it.copyTo(os, BUFFER_SIZE) } } finally { try { connection?.disconnect() } catch (ignored: Exception) { } } }
mit
3c93ce84abe992855875cf67378dc34b
25.348485
115
0.650949
4.588391
false
false
false
false
Nearsoft/nearbooks-android
app/src/main/java/com/nearsoft/nearbooks/view/fragments/RegisterBookFragment.kt
2
6586
package com.nearsoft.nearbooks.view.fragments import android.app.ProgressDialog import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.zxing.integration.android.IntentIntegrator import com.nearsoft.nearbooks.R import com.nearsoft.nearbooks.databinding.FragmentRegisterBookBinding import com.nearsoft.nearbooks.databinding.ItemGoogleBooksVolumeBinding import com.nearsoft.nearbooks.models.BookModel import com.nearsoft.nearbooks.models.GoogleBooksModel import com.nearsoft.nearbooks.util.ErrorUtil import com.nearsoft.nearbooks.util.ViewUtil import com.nearsoft.nearbooks.view.activities.zxing.CaptureActivityAnyOrientation import com.nearsoft.nearbooks.view.adapters.GoogleBooksVolumeAdapter import com.nearsoft.nearbooks.ws.bodies.GoogleBookBody import com.nearsoft.nearbooks.ws.responses.MessageResponse import rx.Subscriber class RegisterBookFragment : BaseFragment(), GoogleBooksVolumeAdapter.OnGoogleBookItemClickListener { companion object { private val KEY_CODE = "KEY_CODE" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment RegisterBookFragment. */ fun newInstance(): RegisterBookFragment { val fragment = RegisterBookFragment() val args = Bundle() fragment.arguments = args return fragment } } private lateinit var mBinding: FragmentRegisterBookBinding private var mCode: String? = null private val mGoogleBooksVolumeAdapter: GoogleBooksVolumeAdapter by lazy { GoogleBooksVolumeAdapter(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null && savedInstanceState.containsKey(KEY_CODE)) { mCode = savedInstanceState.getString(KEY_CODE) findBooksByIsbn() } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_register_book, container, false) mBinding.fabScanQrCode.setOnClickListener { v -> startQRScanner() } mBinding.recyclerViewBooks.setHasFixedSize(true) val layoutManager = LinearLayoutManager(context) mBinding.recyclerViewBooks.layoutManager = layoutManager mBinding.recyclerViewBooks.adapter = mGoogleBooksVolumeAdapter return mBinding.root } override fun onSaveInstanceState(outState: Bundle) { outState.putString(KEY_CODE, mCode) super.onSaveInstanceState(outState) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (scanResult != null && scanResult.contents != null) { mCode = scanResult.contents findBooksByIsbn() } else { super.onActivityResult(requestCode, resultCode, data) } } private fun findBooksByIsbn() { val progressDialog = ProgressDialog.show(context, getString(R.string.message_getting_book_info), null, true) subscribeToFragment(GoogleBooksModel.findGoogleBooksByIsbn(mCode!!).subscribe(object : Subscriber<List<GoogleBookBody>>() { override fun onCompleted() { } override fun onError(t: Throwable) { progressDialog.dismiss() ViewUtil.showSnackbarMessage(mBinding, ErrorUtil.getMessageFromThrowable(t, context)!!) } override fun onNext(googleBookBodies: List<GoogleBookBody>) { progressDialog.dismiss() mGoogleBooksVolumeAdapter.setGoogleBookBodies(googleBookBodies) showResults(!googleBookBodies.isEmpty()) } })) } private fun showResults(showResults: Boolean) { if (showResults) { mBinding.recyclerViewBooks.visibility = View.VISIBLE mBinding.tvEmpty.visibility = View.GONE } else { mBinding.recyclerViewBooks.visibility = View.GONE mBinding.tvEmpty.visibility = View.VISIBLE } } private fun startQRScanner() { val integrator = IntentIntegrator.forSupportFragment(this) integrator.captureActivity = CaptureActivityAnyOrientation::class.java integrator.setOrientationLocked(false) integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES) integrator.setPrompt(getString(R.string.message_scan_book_isbn_bar_code)) integrator.setCameraId(0) // Use a specific camera of the device integrator.setBeepEnabled(true) integrator.setBarcodeImageEnabled(false) integrator.initiateScan() } override fun onGoogleBookItemClicked(binding: ItemGoogleBooksVolumeBinding) { val googleBookBody = binding.book AlertDialog.Builder(context).setTitle(R.string.question_register_new_book).setMessage( getString(R.string.message_book_resume, googleBookBody.title, googleBookBody.authors, googleBookBody.publishedDate)).setPositiveButton(android.R.string.ok) { dialog, which -> subscribeToFragment(BookModel.registerNewBook(googleBookBody).doOnError { t -> ViewUtil.showSnackbarMessage(mBinding, t.message!!) }.subscribe { response -> if (response.isSuccessful) { ViewUtil.showToastMessage(context, R.string.message_done) } else { val messageResponse = ErrorUtil.parseError(MessageResponse::class.java, response) if (messageResponse != null) { ViewUtil.showSnackbarMessage(mBinding, messageResponse.message!!) } else { ViewUtil.showSnackbarMessage(mBinding, ErrorUtil.getGeneralExceptionMessage(context, response.code())!!) } } }) }.setNegativeButton(android.R.string.cancel, null).show() } }
mit
2894b083fcb977feba09b56d02cebb29
40.949045
136
0.677042
4.97432
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/test/kotlin/org/wfanet/measurement/eventdataprovider/privacybudgetmanagement/PrivacyBucketFilterTest.kt
1
9784
/** * Copyright 2022 The Cross-Media Measurement 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.wfanet.measurement.eventdataprovider.privacybudgetmanagement import com.google.common.truth.Truth.assertThat import java.time.LocalDate import java.time.ZoneId import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.api.v2alpha.MeasurementSpecKt.reachAndFrequency import org.wfanet.measurement.api.v2alpha.MeasurementSpecKt.vidSamplingInterval import org.wfanet.measurement.api.v2alpha.measurementSpec import org.wfanet.measurement.eventdataprovider.privacybudgetmanagement.testing.TestPrivacyBucketMapper private const val MEASUREMENT_CONSUMER_ID = "ACME" private val MEASUREMENT_SPEC = measurementSpec { vidSamplingInterval = vidSamplingInterval { start = 0.0f width = PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH } reachAndFrequency = reachAndFrequency {} } @RunWith(JUnit4::class) class PrivacyBucketFilterTest { private val privacyBucketFilter = PrivacyBucketFilter(TestPrivacyBucketMapper()) @Test fun `Mapper fails for invalid filter expression`() { val privacyLandscapeMask = LandscapeMask( listOf( EventGroupSpec( "privacy_budget.age.value", LocalDate.now(ZoneId.of("UTC")).minusDays(1).atStartOfDay().toLocalDate(), LocalDate.now(ZoneId.of("UTC")).atStartOfDay().toLocalDate() ) ), 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, ) assertFailsWith<PrivacyBudgetManagerException> { privacyBucketFilter.getPrivacyBucketGroups(MEASUREMENT_CONSUMER_ID, privacyLandscapeMask) } } @Test fun `Filter succeeds for filter expression with only privacy budget Fields`() { val privacyLandscapeMask = LandscapeMask( listOf( EventGroupSpec( "privacy_budget.age.value in [1] && privacy_budget.gender.value == 2", LocalDate.now(ZoneId.of("UTC")).minusDays(1).atStartOfDay().toLocalDate(), LocalDate.now(ZoneId.of("UTC")).atStartOfDay().toLocalDate() ) ), 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, ) assertThat( privacyBucketFilter.getPrivacyBucketGroups(MEASUREMENT_CONSUMER_ID, privacyLandscapeMask) ) .containsExactly( PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.FEMALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.FEMALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.FEMALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.FEMALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), ) } @Test fun `Mapper succeeds with privacy budget Field and non Privacy budget fields`() { val privacyLandscapeMask = LandscapeMask( listOf( EventGroupSpec( "privacy_budget.age.value in [1] && privacy_budget.gender.value == 2 && " + "banner_ad.gender.value == 1", LocalDate.now(ZoneId.of("UTC")).minusDays(1).atStartOfDay().toLocalDate(), LocalDate.now(ZoneId.of("UTC")).atStartOfDay().toLocalDate() ) ), 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, ) assertThat( privacyBucketFilter.getPrivacyBucketGroups(MEASUREMENT_CONSUMER_ID, privacyLandscapeMask) ) .containsExactly( PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.FEMALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.FEMALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.FEMALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.FEMALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), ) } @Test fun `Mapper succeeds with left out privacy budget Fields`() { val privacyLandscapeMask = LandscapeMask( listOf( EventGroupSpec( "privacy_budget.age.value in [1] ", LocalDate.now(ZoneId.of("UTC")).minusDays(1).atStartOfDay().toLocalDate(), LocalDate.now(ZoneId.of("UTC")).atStartOfDay().toLocalDate() ) ), 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, ) assertThat( privacyBucketFilter.getPrivacyBucketGroups(MEASUREMENT_CONSUMER_ID, privacyLandscapeMask) ) .containsExactly( PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.FEMALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.FEMALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.FEMALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.FEMALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.MALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.MALE, 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now(), LocalDate.now(), AgeGroup.RANGE_18_34, Gender.MALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), PrivacyBucketGroup( MEASUREMENT_CONSUMER_ID, LocalDate.now().minusDays(1), LocalDate.now().minusDays(1), AgeGroup.RANGE_18_34, Gender.MALE, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH ), ) } @Test fun `Non Privacy Budget Fields may charge more bucgkets than necessary`() { val privacyLandscapeMask = LandscapeMask( listOf( EventGroupSpec( "privacy_budget.age.value in [0] && privacy_budget.gender.value == 1 || " + "banner_ad.gender.value == 1", LocalDate.now(ZoneId.of("UTC")).minusDays(1).atStartOfDay().toLocalDate(), LocalDate.now(ZoneId.of("UTC")).atStartOfDay().toLocalDate() ) ), 0.0f, PrivacyLandscape.PRIVACY_BUCKET_VID_SAMPLE_WIDTH, ) assertThat( privacyBucketFilter.getPrivacyBucketGroups(MEASUREMENT_CONSUMER_ID, privacyLandscapeMask) ) .hasSize(24) } }
apache-2.0
da07a77a96f01dd253c7f67d96e33d79
31.722408
103
0.623569
4.35425
false
false
false
false
ursjoss/scipamato
core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/JooqReadOnlyRepoTest.kt
1
4819
@file:Suppress("SpellCheckingInspection") package ch.difty.scipamato.core.persistence import ch.difty.scipamato.common.config.ApplicationProperties import ch.difty.scipamato.common.entity.filter.ScipamatoFilter import ch.difty.scipamato.common.persistence.GenericFilterConditionMapper import ch.difty.scipamato.common.persistence.JooqSortMapper import ch.difty.scipamato.common.persistence.paging.PaginationContext import ch.difty.scipamato.common.persistence.paging.Sort import ch.difty.scipamato.core.entity.IdScipamatoEntity import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.amshove.kluent.shouldBeEqualTo import org.jooq.Condition import org.jooq.DSLContext import org.jooq.Record import org.jooq.Record1 import org.jooq.RecordMapper import org.jooq.SelectConditionStep import org.jooq.SelectJoinStep import org.jooq.SelectSeekStepN import org.jooq.SelectSelectStep import org.jooq.SelectWhereStep import org.jooq.SortField import org.jooq.Table import org.jooq.TableField import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test abstract class JooqReadOnlyRepoTest< R : Record, T : IdScipamatoEntity<ID>, ID : Number, TI : Table<R>, M : RecordMapper<R, T>, F : ScipamatoFilter> { protected val dsl = mockk<DSLContext>() protected var filterConditionMapper = mockk<GenericFilterConditionMapper<F>>() protected val sortMapper = mockk<JooqSortMapper<R, T, TI>>() private val selectWhereStepMock = mockk<SelectWhereStep<R>>() private val selectConditionStepMock = mockk<SelectConditionStep<R>>() private val selectSelectStepMock = mockk<SelectSelectStep<Record1<Int>>>() private val selectJoinStepMock = mockk<SelectJoinStep<Record1<Int>>>() private val selectConditionStepMock2 = mockk<SelectConditionStep<Record1<Int>>>() private val paginationContextMock = mockk<PaginationContext>() private val sortMock = mockk<Sort>() private val sortFieldsMock = mockk<Collection<SortField<T>>>() private val selectSeekStepNMock = mockk<SelectSeekStepN<R>>() protected val conditionMock = mockk<Condition>() protected val applicationProperties = mockk<ApplicationProperties>() protected abstract val persistedEntity: T protected abstract val unpersistedEntity: T protected abstract val persistedRecord: R protected abstract val unpersistedRecord: R protected abstract val mapper: M protected abstract val table: TI protected abstract val tableId: TableField<R, ID> protected abstract val filter: F protected abstract val repo: ReadOnlyRepository<T, ID, F> /** * Hand-rolled spy that returns the provided entity in the method `findById(ID id)` */ protected abstract fun makeRepoFindingEntityById(entity: T): ReadOnlyRepository<T, ID, F> protected abstract fun expectEntityIdsWithValues() protected abstract fun expectUnpersistedEntityIdNull() protected abstract fun verifyUnpersistedEntityId() protected abstract fun verifyPersistedRecordId() private val entities = mutableListOf<T>() private val records = mutableListOf<R>() @BeforeEach internal fun setUp() { entities.add(persistedEntity) entities.add(persistedEntity) records.add(persistedRecord) records.add(persistedRecord) specificSetUp() } protected open fun specificSetUp() {} @AfterEach internal fun tearDown() { specificTearDown() confirmVerified(dsl, mapper, sortMapper) confirmVerified(unpersistedEntity, persistedEntity, unpersistedRecord, persistedRecord) confirmVerified(selectWhereStepMock, selectConditionStepMock) confirmVerified(selectSelectStepMock, selectJoinStepMock) confirmVerified(paginationContextMock, sortMock, sortFieldsMock, selectSeekStepNMock) confirmVerified(filter, conditionMock) confirmVerified(applicationProperties) } protected open fun specificTearDown() {} protected open fun specificNullCheck() {} @Test internal fun countingByFilter() { every { filterConditionMapper.map(filter) } returns conditionMock every { dsl.selectOne() } returns selectSelectStepMock every { selectSelectStepMock.from(table) } returns selectJoinStepMock every { selectJoinStepMock.where(any<Condition>()) } returns selectConditionStepMock2 every { dsl.fetchCount(selectConditionStepMock2) } returns 2 repo.countByFilter(filter) shouldBeEqualTo 2 verify { dsl.selectOne() } verify { selectSelectStepMock.from(table) } verify { selectJoinStepMock.where(any<Condition>()) } verify { dsl.fetchCount(selectConditionStepMock2) } } }
bsd-3-clause
16b7913071a95dfbd99b47e956086d63
34.433824
95
0.756796
4.62476
false
false
false
false
ntlv/BasicLauncher2
app/src/main/java/se/ntlv/basiclauncher/AppPageLayout.kt
1
1366
package se.ntlv.basiclauncher import android.view.View import android.view.ViewGroup import org.jetbrains.anko.find import org.jetbrains.anko.forEachChild import se.ntlv.basiclauncher.appgrid.AppGridFactory import se.ntlv.basiclauncher.database.AppDetail class AppPageLayout { private val view: ViewGroup constructor (isDockLayout: Boolean, page: Int, controller: View.OnDragListener?, factory: AppGridFactory, items: List<AppDetail>, gridDimens: GridDimensions, cellDimens: CellDimensions) { assert(items.size > gridDimens.size, { "Icons will not fit on screen." }) view = if (!isDockLayout) { val rows = items.groupBy { it.row } factory.makePage(page, gridDimens, cellDimens, rows) } else { factory.makeDock(gridDimens, cellDimens, items) } controller?.let { view.setOnDragListener(it) } } fun getView(): ViewGroup = view fun unload() = view.find<ViewGroup>(R.id.app_icons_container).forEachChild { it.find<AppIconImageView>(R.id.app_icon_view).recycle() } } data class GridDimensions(val rowCount: Int, val columnCount: Int) { val size: Int get() = rowCount * columnCount } data class CellDimensions(val width: Int, val height: Int)
mit
1e82934c3cc669da4a0aacb906e98fd8
26.32
81
0.649341
4.190184
false
false
false
false
PaulWoitaschek/Voice
app/src/main/kotlin/voice/app/mvp/Presenter.kt
1
1144
package voice.app.mvp import android.os.Bundle import androidx.annotation.CallSuper import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import voice.common.checkMainThread import voice.logging.core.Logger abstract class Presenter<V : Any> { protected val scope = MainScope() protected var onAttachScope = MainScope().also { it.cancel() } val view: V get() { checkMainThread() return internalView!! } val attached: Boolean get() { checkMainThread() return internalView != null } private var internalView: V? = null @CallSuper open fun onRestore(savedState: Bundle) { checkMainThread() } fun attach(view: V) { Logger.i("attach $view") checkMainThread() check(internalView == null) { "$internalView already bound." } internalView = view onAttachScope = MainScope() onAttach(view) } fun detach() { Logger.i("detach $internalView") checkMainThread() onAttachScope.cancel() internalView = null } @CallSuper open fun onSave(state: Bundle) { checkMainThread() } open fun onAttach(view: V) {} }
gpl-3.0
8b34cbcc900abbd842ae1ceb2615da60
18.724138
64
0.672203
4.316981
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/fragments/AdViewHolder.kt
1
3534
package com.pr0gramm.app.ui.fragments import android.content.Context import android.net.Uri import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView import com.pr0gramm.app.Duration import com.pr0gramm.app.Logger import com.pr0gramm.app.R import com.pr0gramm.app.model.config.Config import com.pr0gramm.app.ui.AdService import com.pr0gramm.app.ui.base.onAttachedScope import com.pr0gramm.app.util.BrowserHelper import com.pr0gramm.app.util.delay import com.pr0gramm.app.util.di.injector import com.pr0gramm.app.util.dp import com.pr0gramm.app.util.trace import kotlin.math.roundToInt class AdViewHolder private constructor(val adView: AdView, itemView: View) : RecyclerView.ViewHolder(itemView) { companion object { private val logger = Logger("AdViewHolder") fun new(context: Context): AdViewHolder { trace { "newContainerView" } val container = FrameLayout(context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } trace { "newPlaceholderView" } val placeholder = ImageView(context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, context.dp(70f).roundToInt()) scaleType = ImageView.ScaleType.CENTER_CROP setImageDrawable(VectorDrawableCompat.create( resources, R.drawable.pr0mium_ad, null)) setOnClickListener { BrowserHelper.openCustomTab(context, Uri.parse("https://pr0gramm.com/pr0mium")) } } container.addView(placeholder) val adService = context.injector.instance<AdService>() trace { "newAdView()" } val adView = adService.newAdView(context).apply { setAdSize(AdSize(AdSize.FULL_WIDTH, 70)) } container.onAttachedScope { trace { "AdContainer was attached." } delay(Duration.seconds(1)) trace { "Loading ad now." } adService.load(adView, Config.AdType.FEED).collect { state -> [email protected] { "adStateChanged($state)" } if (state == AdService.AdLoadState.SUCCESS && adView.parent == null) { if (adView.parent !== placeholder) { logger.info { "Ad was loaded, showing ad now." } container.removeView(placeholder) container.addView(adView) } } if (state == AdService.AdLoadState.CLOSED || state == AdService.AdLoadState.FAILURE) { if (placeholder.parent !== container) { logger.info { "Ad not loaded: $state" } container.removeView(adView) container.addView(placeholder) } } } } return AdViewHolder(adView, container) } } }
mit
e920f08e028615986dd87e7b178c31de
35.43299
106
0.588568
4.808163
false
false
false
false
FHannes/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/editor/GroovyBreadcrumbsInfoProvider.kt
16
2813
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.editor import com.intellij.lang.Language import com.intellij.psi.ElementDescriptionUtil import com.intellij.psi.PsiElement import com.intellij.refactoring.util.RefactoringDescriptionLocation.WITH_PARENT import com.intellij.xml.breadcrumbs.BreadcrumbsInfoProvider import org.jetbrains.plugins.groovy.GroovyLanguage import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod class GroovyBreadcrumbsInfoProvider : BreadcrumbsInfoProvider() { private companion object { val ourLanguages: Array<Language> = arrayOf(GroovyLanguage) } override fun getLanguages() = ourLanguages override fun acceptElement(e: PsiElement) = when (e) { is GrVariableDeclaration -> e.variables.singleOrNull() is GrField is GrField -> e is GrEnumConstant is GrClosableBlock -> true is GrMember -> e.name != null else -> false } override fun getElementInfo(e: PsiElement) = when (e) { is GrVariableDeclaration -> e.variables.single().name is GrClosableBlock -> (((e.parent as? GrMethodCall)?.invokedExpression as? GrReferenceExpression)?.referenceName ?: "") + "{}" is GrAnonymousClassDefinition -> "new ${e.baseClassReferenceGroovy.referenceName}" is GrMethod -> "${e.name}()" is GrMember -> e.name!! else -> throw RuntimeException() } override fun getElementTooltip(e: PsiElement) = (if (e is GrVariableDeclaration) e.variables.single() else e).let { ElementDescriptionUtil.getElementDescription(it, WITH_PARENT) } }
apache-2.0
b7aec6f0ccc37b45b12b64a38d49ed94
44.370968
130
0.781372
4.28811
false
false
false
false
schaal/ocreader
app/src/main/java/email/schaal/ocreader/api/json/ItemJsonTypeAdapter.kt
1
1975
package email.schaal.ocreader.api.json import com.squareup.moshi.FromJson import com.squareup.moshi.JsonClass import com.squareup.moshi.ToJson import email.schaal.ocreader.database.model.Item import email.schaal.ocreader.util.cleanString import java.util.* class ItemJsonTypeAdapter { @FromJson fun fromJson(jsonItem: JsonItem) : Item { return Item().apply { id = jsonItem.id guid = jsonItem.guid guidHash = jsonItem.guidHash url = jsonItem.url title = jsonItem.title?.cleanString() author = jsonItem.author?.cleanString() pubDate = Date(jsonItem.pubDate * 1000) body = jsonItem.body enclosureLink = jsonItem.enclosureLink feedId = jsonItem.feedId unread = jsonItem.unread starred = jsonItem.starred lastModified = Date(jsonItem.lastModified * 1000) fingerprint = jsonItem.fingerprint contentHash = jsonItem.contentHash } } @ToJson fun toJson(item: Item) : Map<String, Any?> { return mutableMapOf<String, Any?>( "id" to item.id, "contentHash" to item.contentHash ). also { if(item.unreadChanged) it["isUnread"] = item.unread if(item.starredChanged) it["isStarred"] = item.starred } } } @JsonClass(generateAdapter = true) class JsonItem( val id: Long, val guid: String?, val guidHash: String?, val url: String?, val title: String?, val author: String?, val pubDate: Long, val body: String, val enclosureMime: String?, val enclosureLink: String?, val feedId: Long, val unread: Boolean, val starred: Boolean, val lastModified: Long, val fingerprint: String?, val contentHash: String? )
gpl-3.0
a4299b639cea62642f9ba4e65e9f5a72
29.887097
66
0.580253
4.458239
false
false
false
false
didi/DoraemonKit
Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/action/file/RenameFileAction.kt
1
918
package com.didichuxing.doraemonkit.kit.filemanager.action.file import com.didichuxing.doraemonkit.util.FileUtils /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/6/23-15:26 * 描 述: * 修订历史: * ================================================ */ object RenameFileAction { fun renameFileRes(newName: String, filePath: String): MutableMap<String, Any> { val response = mutableMapOf<String, Any>() if (FileUtils.isFileExists(filePath)) { FileUtils.rename(filePath, newName) response["code"] = 200 response["success"] = true response["message"] = "success" } else { response["code"] = 0 response["success"] = false response["message"] = "$filePath is not exists" } return response } }
apache-2.0
d7486682d73ef20e67524bbe91383210
28.1
83
0.517202
4.40404
false
false
false
false