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
DeflatedPickle/Quiver
launcher/src/main/kotlin/com/deflatedpickle/quiver/launcher/window/Window.kt
1
638
/* Copyright (c) 2020 DeflatedPickle under the MIT license */ package com.deflatedpickle.quiver.launcher.window import bibliothek.gui.dock.common.CControl import bibliothek.gui.dock.common.CGrid import com.deflatedpickle.tosuto.ToastWindow import java.awt.BorderLayout import javax.swing.JFrame object Window : JFrame("Quiver") { val control = CControl(this) val grid = CGrid(control) val toastWindow = ToastWindow( parent = this, toastWidth = 160 ) init { this.defaultCloseOperation = EXIT_ON_CLOSE this.add(control.contentArea, BorderLayout.CENTER) this.pack() } }
mit
de27d8082783d33be704594b6b469f8c
22.62963
61
0.708464
3.820359
false
false
false
false
leafclick/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTupleTypeProvider.kt
1
15661
// 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 com.jetbrains.python.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.util.QualifiedName import com.intellij.util.ArrayUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyNamedTupleStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.fromFoothold import com.jetbrains.python.psi.resolve.resolveTopLevelMember import com.jetbrains.python.psi.stubs.PyNamedTupleStub import com.jetbrains.python.psi.types.* import one.util.streamex.StreamEx import java.util.* import java.util.stream.Collectors private typealias NTFields = LinkedHashMap<String, PyNamedTupleType.FieldTypeAndDefaultValue> private typealias ImmutableNTFields = Map<String, PyNamedTupleType.FieldTypeAndDefaultValue> class PyNamedTupleTypeProvider : PyTypeProviderBase() { override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? { return PyTypeUtil.notNullToRef(getNamedTupleTypeForResolvedCallee(referenceTarget, context, anchor)) } override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { val fieldTypeForNamedTuple = getFieldTypeForNamedTupleAsTarget(referenceExpression, context) if (fieldTypeForNamedTuple != null) { return fieldTypeForNamedTuple } val fieldTypeForTypingNTFunctionInheritor = getFieldTypeForTypingNTFunctionInheritor(referenceExpression, context) if (fieldTypeForTypingNTFunctionInheritor != null) { return fieldTypeForTypingNTFunctionInheritor } val namedTupleTypeForCallee = getNamedTupleTypeForCallee(referenceExpression, context) if (namedTupleTypeForCallee != null) { return namedTupleTypeForCallee } val namedTupleReplaceType = getNamedTupleReplaceType(referenceExpression, context) if (namedTupleReplaceType != null) { return namedTupleReplaceType } return null } companion object { fun isNamedTuple(type: PyType?, context: TypeEvalContext): Boolean { if (type is PyNamedTupleType) return true val isNT = { t: PyClassLikeType? -> t is PyNamedTupleType || t != null && PyTypingTypeProvider.NAMEDTUPLE == t.classQName } return type is PyClassLikeType && type.getAncestorTypes(context).any(isNT) } fun isTypingNamedTupleDirectInheritor(cls: PyClass, context: TypeEvalContext): Boolean { val isTypingNT = { type: PyClassLikeType? -> type != null && type !is PyNamedTupleType && PyTypingTypeProvider.NAMEDTUPLE == type.classQName } return cls.getSuperClassTypes(context).any(isTypingNT) } internal fun getNamedTupleTypeForResolvedCallee(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyNamedTupleType? { return when { referenceTarget is PyFunction && anchor is PyCallExpression -> getNamedTupleFunctionType(referenceTarget, context, anchor) referenceTarget is PyTargetExpression -> getNamedTupleTypeForTarget(referenceTarget, context) else -> null } } internal fun getNamedTupleReplaceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyCallableType? { if (referenceTarget is PyFunction && anchor is PyCallExpression && PyTypingTypeProvider.NAMEDTUPLE == referenceTarget.containingClass?.qualifiedName) { val callee = anchor.callee as? PyReferenceExpression ?: return null return getNamedTupleReplaceType(callee, context) } return null } private fun getFieldTypeForNamedTupleAsTarget(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { val qualifierNTType = referenceExpression.qualifier?.let { context.getType(it) } as? PyNamedTupleType ?: return null return qualifierNTType.fields[referenceExpression.name]?.type } private fun getFieldTypeForTypingNTFunctionInheritor(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { val qualifierType = referenceExpression.qualifier?.let { context.getType(it) } as? PyWithAncestors if (qualifierType == null || qualifierType is PyNamedTupleType) return null return PyUnionType.union( qualifierType .getAncestorTypes(context) .filterIsInstance<PyNamedTupleType>() .mapNotNull { it.fields[referenceExpression.name] } .map { it.type } .toList() ) } private fun getNamedTupleTypeForCallee(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyNamedTupleType? { if (PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) == null) return null val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val resolveResults = referenceExpression.getReference(resolveContext).multiResolve(false) for (element in PyUtil.filterTopPriorityResults(resolveResults)) { if (element is PyTargetExpression) { val result = getNamedTupleTypeForTarget(element, context) if (result != null) { return result } } if (element is PyClass) { val result = getNamedTupleTypeForTypingNTInheritorAsCallee(element, context) if (result != null) { return result } } if (element is PyTypedElement) { val type = context.getType(element) if (type is PyClassLikeType) { val superClassTypes = type.getSuperClassTypes(context) val superNTType = superClassTypes.asSequence().filterIsInstance<PyNamedTupleType>().firstOrNull() if (superNTType != null) { return superNTType } } } } return null } private fun getNamedTupleReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null val qualifier = referenceExpression.qualifier if (qualifier != null && "_replace" == referenceExpression.referencedName) { val qualifierType = context.getType(qualifier) as? PyClassLikeType ?: return null val namedTupleType = StreamEx .of<PyType>(qualifierType) .append(qualifierType.getSuperClassTypes(context)) .select(PyNamedTupleType::class.java) .findFirst() .orElse(null) if (namedTupleType != null) { return if (namedTupleType.isTyped) createTypedNamedTupleReplaceType(referenceExpression, namedTupleType.fields, qualifierType) else createUntypedNamedTupleReplaceType(call, namedTupleType.fields, qualifierType, context) } if (qualifierType is PyClassType) { val cls = qualifierType.pyClass if (isTypingNamedTupleDirectInheritor(cls, context)) { return createTypedNamedTupleReplaceType(referenceExpression, collectTypingNTInheritorFields(cls, context), qualifierType) } } } return null } private fun getNamedTupleFunctionType(function: PyFunction, context: TypeEvalContext, call: PyCallExpression): PyNamedTupleType? { if (ArrayUtil.contains(function.qualifiedName, PyNames.COLLECTIONS_NAMEDTUPLE_PY2, PyNames.COLLECTIONS_NAMEDTUPLE_PY3) || PyTypingTypeProvider.NAMEDTUPLE == PyUtil.turnConstructorIntoClass(function)?.qualifiedName) { return getNamedTupleTypeFromAST(call, context, PyNamedTupleType.DefinitionLevel.NT_FUNCTION) } return null } private fun getNamedTupleTypeForTarget(target: PyTargetExpression, context: TypeEvalContext): PyNamedTupleType? { val stub = target.stub return if (stub != null) { getNamedTupleTypeFromStub(target, stub.getCustomStub(PyNamedTupleStub::class.java), context, PyNamedTupleType.DefinitionLevel.NEW_TYPE) } else getNamedTupleTypeFromAST(target, context, PyNamedTupleType.DefinitionLevel.NEW_TYPE) } private fun getNamedTupleTypeForTypingNTInheritorAsCallee(cls: PyClass, context: TypeEvalContext): PyNamedTupleType? { if (isTypingNamedTupleDirectInheritor(cls, context)) { val name = cls.name ?: return null val typingNT = resolveTopLevelMember(QualifiedName.fromDottedString( PyTypingTypeProvider.NAMEDTUPLE), fromFoothold(cls)) val tupleClass = typingNT as? PyClass ?: return null return PyNamedTupleType(tupleClass, name, collectTypingNTInheritorFields(cls, context), PyNamedTupleType.DefinitionLevel.NEW_TYPE, true) } return null } private fun getNamedTupleTypeFromStub(referenceTarget: PsiElement, stub: PyNamedTupleStub?, context: TypeEvalContext, definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? { if (stub == null) return null val typingNT = resolveTopLevelMember(QualifiedName.fromDottedString( PyTypingTypeProvider.NAMEDTUPLE), fromFoothold(referenceTarget)) val tupleClass = typingNT as? PyClass ?: return null val fields = stub.fields return PyNamedTupleType(tupleClass, stub.name, parseNamedTupleFields(referenceTarget, fields, context), definitionLevel, fields.values.any { it.isPresent }, referenceTarget as? PyTargetExpression) } private fun getNamedTupleTypeFromAST(expression: PyTargetExpression, context: TypeEvalContext, definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? { return if (context.maySwitchToAST(expression)) { getNamedTupleTypeFromStub(expression, PyNamedTupleStubImpl.create(expression), context, definitionLevel) } else null } private fun createTypedNamedTupleReplaceType(anchor: PsiElement, fields: ImmutableNTFields, qualifierType: PyClassLikeType): PyCallableType { val parameters = mutableListOf<PyCallableParameter>() val resultType = qualifierType.toInstance() val elementGenerator = PyElementGenerator.getInstance(anchor.project) if (qualifierType.isDefinition) { parameters.add(PyCallableParameterImpl.nonPsi(PyNames.CANONICAL_SELF, resultType)) } parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() for ((name, typeAndValue) in fields) { parameters.add(PyCallableParameterImpl.nonPsi(name, typeAndValue.type, typeAndValue.defaultValue ?: ellipsis)) } return PyCallableTypeImpl(parameters, resultType) } private fun createUntypedNamedTupleReplaceType(call: PyCallExpression, fields: ImmutableNTFields, qualifierType: PyClassLikeType, context: TypeEvalContext): PyCallableType { val parameters = mutableListOf<PyCallableParameter>() val resultType = qualifierType.toInstance() val elementGenerator = PyElementGenerator.getInstance(call.project) if (qualifierType.isDefinition) { parameters.add(PyCallableParameterImpl.nonPsi(PyNames.CANONICAL_SELF, resultType)) } parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() fields.keys.mapTo(parameters) { PyCallableParameterImpl.nonPsi(it, null, ellipsis) } return if (resultType is PyNamedTupleType) { val newFields = mutableMapOf<String?, PyType?>() for (argument in call.arguments) { if (argument is PyKeywordArgument) { val value = argument.valueExpression if (value != null) { newFields[argument.keyword] = context.getType(value) } } } PyCallableTypeImpl(parameters, resultType.clarifyFields(newFields)) } else PyCallableTypeImpl(parameters, resultType) } private fun collectTypingNTInheritorFields(cls: PyClass, context: TypeEvalContext): NTFields { val fields = mutableListOf<PyTargetExpression>() cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression && element.annotationValue != null) { fields.add(element) } true } val ellipsis = PyElementGenerator.getInstance(cls.project).createEllipsis() val toNTFields = Collectors.toMap<PyTargetExpression, String, PyNamedTupleType.FieldTypeAndDefaultValue, NTFields>( { it.name }, { field -> val value = when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } PyNamedTupleType.FieldTypeAndDefaultValue(context.getType(field), value) }, { _, v2 -> v2 }, { NTFields() }) return fields.stream().collect(toNTFields) } private fun getNamedTupleTypeFromAST(expression: PyCallExpression, context: TypeEvalContext, definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? { return if (context.maySwitchToAST(expression)) { getNamedTupleTypeFromStub(expression, PyNamedTupleStubImpl.create(expression), context, definitionLevel) } else null } private fun parseNamedTupleFields(anchor: PsiElement, fields: Map<String, Optional<String>>, context: TypeEvalContext): NTFields { val result = NTFields() for ((name, type) in fields) { result[name] = parseNamedTupleField(anchor, type.orElse(null), context) } return result } private fun parseNamedTupleField(anchor: PsiElement, type: String?, context: TypeEvalContext): PyNamedTupleType.FieldTypeAndDefaultValue { if (type == null) return PyNamedTupleType.FieldTypeAndDefaultValue(null, null) val pyType = Ref.deref(PyTypingTypeProvider.getStringBasedType(type, anchor, context)) return PyNamedTupleType.FieldTypeAndDefaultValue(pyType, null) } } }
apache-2.0
c1290ea7d6e92a6490150b58dabd0622
43.115493
145
0.669242
5.966095
false
false
false
false
leafclick/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/ideaUtils.kt
1
2657
// 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.intellij.build.images.sync import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.serialization.JpsMacroExpander import org.jetbrains.jps.model.serialization.JpsSerializationManager import org.jetbrains.jps.model.serialization.PathMacroUtil import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Paths private val vcsPattern = """(?<=mapping directory=").*(?=" vcs="Git")""".toRegex() private val jme by lazy { JpsMacroExpander(emptyMap()).apply { addFileHierarchyReplacements("MAVEN_REPOSITORY", File(System.getProperty("user.home"), ".m2/repository")) } } /** * @param project idea project root * @return list of VCS roots in [project] */ internal fun vcsRoots(project: File): List<File> { val vcsXml = project.resolve("${PathMacroUtil.DIRECTORY_STORE_NAME}/vcs.xml") return if (vcsXml.exists()) { jme.addFileHierarchyReplacements(PathMacroUtil.PROJECT_DIR_MACRO_NAME, project) vcsPattern.findAll(vcsXml.readText()) .map { expandJpsMacro(it.value) } .map { val file = File(it) if (file.exists()) file else File(project, it) }.filter(File::exists).toList().also { roots -> log("Found ${roots.size} repo roots in $project:") roots.forEach { log(it.absolutePath) } } } else { log("${vcsXml.absolutePath} not found. Using $project") listOf(project) } } internal fun expandJpsMacro(text: String) = jme.substitute(text, SystemInfo.isFileSystemCaseSensitive) internal fun searchTestRoots(project: String) = try { jpsProject(project) .modules.flatMap { it.getSourceRoots(JavaSourceRootType.TEST_SOURCE) + it.getSourceRoots(JavaResourceRootType.TEST_RESOURCE) }.mapTo(mutableSetOf()) { it.file } } catch (e: IOException) { System.err.println(e.message) emptySet<File>() } internal fun jpsProject(path: String): JpsProject { val file = Paths.get(FileUtil.toCanonicalPath(path)) return if (path.endsWith(".ipr") || Files.isDirectory(file.resolve(PathMacroUtil.DIRECTORY_STORE_NAME)) || Files.isDirectory(file) && file.endsWith(PathMacroUtil.DIRECTORY_STORE_NAME)) { JpsSerializationManager.getInstance().loadModel(path, null).project } else { jpsProject(file.parent.toString()) } }
apache-2.0
4e4f5cfcf33b0ffdbe7a1fe9725711d5
35.916667
140
0.72977
3.86754
false
false
false
false
romannurik/muzei
android-client-common/src/main/java/com/google/android/apps/muzei/sync/ArtworkLoadWorker.kt
1
14277
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.sync import android.content.ContentUris import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.BaseColumns import android.util.Log import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.google.android.apps.muzei.api.internal.ProtocolConstants import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_MAX_LOADED_ARTWORK_ID import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_RECENT_ARTWORK_IDS import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_GET_LOAD_INFO import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_MARK_ARTWORK_LOADED import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_REQUEST_LOAD import com.google.android.apps.muzei.api.internal.getRecentIds import com.google.android.apps.muzei.api.provider.MuzeiArtProvider import com.google.android.apps.muzei.api.provider.ProviderContract import com.google.android.apps.muzei.render.isValidImage import com.google.android.apps.muzei.room.Artwork import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.util.ContentProviderClientCompat import com.google.android.apps.muzei.util.getLong import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import net.nurik.roman.muzei.androidclientcommon.BuildConfig import java.io.IOException import java.util.Random import java.util.concurrent.TimeUnit /** * Worker responsible for loading artwork from a [MuzeiArtProvider] and inserting it into * the [MuzeiDatabase]. */ class ArtworkLoadWorker( context: Context, workerParams: WorkerParameters ) : CoroutineWorker(context, workerParams) { companion object { private const val TAG = "ArtworkLoad" private const val PERIODIC_TAG = "ArtworkLoadPeriodic" private const val ARTWORK_LOAD_THROTTLE = 250L // quarter second internal fun enqueueNext(context: Context) { val workManager = WorkManager.getInstance(context) workManager.enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE, OneTimeWorkRequestBuilder<ArtworkLoadWorker>().build()) } internal fun enqueuePeriodic( context: Context, loadFrequencySeconds: Long, loadOnWifi: Boolean ) { val workManager = WorkManager.getInstance(context) workManager.enqueueUniquePeriodicWork(PERIODIC_TAG, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, PeriodicWorkRequestBuilder<ArtworkLoadWorker>( loadFrequencySeconds, TimeUnit.SECONDS, loadFrequencySeconds / 10, TimeUnit.SECONDS) .setConstraints(Constraints.Builder() .setRequiredNetworkType(if (loadOnWifi) { NetworkType.UNMETERED } else { NetworkType.CONNECTED }) .build()) .build()) } fun cancelPeriodic(context: Context) { val workManager = WorkManager.getInstance(context) workManager.cancelUniqueWork(PERIODIC_TAG) } } override suspend fun doWork() = withContext(syncSingleThreadContext) { // Throttle artwork loads delay(ARTWORK_LOAD_THROTTLE) // Now actually load the artwork val database = MuzeiDatabase.getInstance(applicationContext) val (authority) = database.providerDao() .getCurrentProvider() ?: return@withContext Result.failure() if (BuildConfig.DEBUG) { Log.d(TAG, "Artwork Load for $authority") } val contentUri = ProviderContract.getContentUri(authority) try { ContentProviderClientCompat.getClient(applicationContext, contentUri)?.use { client -> val result = client.call(METHOD_GET_LOAD_INFO) ?: return@withContext Result.failure() val maxLoadedArtworkId = result.getLong(KEY_MAX_LOADED_ARTWORK_ID, 0L) val recentArtworkIds = result.getRecentIds(KEY_RECENT_ARTWORK_IDS) client.query( contentUri, selection = "_id > ?", selectionArgs = arrayOf(maxLoadedArtworkId.toString()), sortOrder = ProviderContract.Artwork._ID )?.use { newArtwork -> client.query(contentUri)?.use { allArtwork -> // First prioritize new artwork while (newArtwork.moveToNext()) { val validArtwork = checkForValidArtwork(client, contentUri, newArtwork) if (validArtwork != null) { validArtwork.providerAuthority = authority val artworkId = database.artworkDao().insert(validArtwork) if (BuildConfig.DEBUG) { Log.d(TAG, "Loaded ${validArtwork.imageUri} into id $artworkId") } client.call(METHOD_MARK_ARTWORK_LOADED, validArtwork.imageUri.toString()) // If we just loaded the last new artwork, we should request that they load another // in preparation for the next load if (!newArtwork.moveToNext()) { if (BuildConfig.DEBUG) { Log.d(TAG, "Out of new artwork, requesting load from $authority") } client.call(METHOD_REQUEST_LOAD) } return@withContext Result.success() } } if (BuildConfig.DEBUG) { Log.d(TAG, "Could not find any new artwork, requesting load from $authority") } // No new artwork, request that they load another in preparation for the next load client.call(METHOD_REQUEST_LOAD) // Is there any artwork at all? if (allArtwork.count == 0) { Log.w(TAG, "Unable to find any artwork for $authority") return@withContext Result.failure() } // Okay so there's at least some artwork. // Is it just the one artwork we're already showing? val currentArtwork = database.artworkDao().getCurrentArtwork() if (allArtwork.count == 1 && allArtwork.moveToFirst()) { val artworkId = allArtwork.getLong(BaseColumns._ID) val artworkUri = ContentUris.withAppendedId(contentUri, artworkId) if (artworkUri == currentArtwork?.imageUri) { if (BuildConfig.DEBUG) { Log.i(TAG, "Provider $authority only has one artwork") } return@withContext Result.failure() } } // At this point, we know there must be some artwork that isn't the current // artwork. We want to avoid showing artwork we've recently loaded, so // we'll generate two sequences - the first being made up of // non recent artwork, the second being made up of only recent artwork val random = Random() // Build a lambda that checks whether the given position // represents the current artwork val isCurrentArtwork: (position: Int) -> Boolean = { position -> if (allArtwork.moveToPosition(position)) { val artworkId = allArtwork.getLong(BaseColumns._ID) val artworkUri = ContentUris.withAppendedId(contentUri, artworkId) artworkUri == currentArtwork?.imageUri } else { false } } // Build a lambda that checks whether the given position // represents an artwork in the recentArtworkIds val isRecentArtwork: (position: Int) -> Boolean = { position -> if (allArtwork.moveToPosition(position)) { val artworkId = allArtwork.getLong(BaseColumns._ID) recentArtworkIds.contains(artworkId) } else { false } } // Now generate a random sequence for non recent artwork val nonRecentArtworkSequence = generateSequence { random.nextInt(allArtwork.count) }.distinct().take(allArtwork.count) .filterNot(isCurrentArtwork) .filterNot(isRecentArtwork) // Now generate another sequence for recent artwork val recentArtworkSequence = generateSequence { random.nextInt(allArtwork.count) }.distinct().take(allArtwork.count) .filterNot(isCurrentArtwork) .filter(isRecentArtwork) // And build the final sequence that iterates first through // non recent artwork, then recent artwork val randomSequence = nonRecentArtworkSequence + recentArtworkSequence val iterator = randomSequence.iterator() while (iterator.hasNext()) { val position = iterator.next() if (allArtwork.moveToPosition(position)) { checkForValidArtwork(client, contentUri, allArtwork)?.apply { providerAuthority = authority val artworkId = database.artworkDao().insert(this) if (BuildConfig.DEBUG) { Log.d(TAG, "Loaded $imageUri into id $artworkId") } client.call(METHOD_MARK_ARTWORK_LOADED, imageUri.toString()) return@withContext Result.success() } } } if (BuildConfig.DEBUG) { Log.i(TAG, "Unable to find any other valid artwork for $authority") } } } } } catch (e: Exception) { when (e) { is CancellationException -> throw e else -> Log.i(TAG, "Provider $authority crashed while retrieving artwork: ${e.message}") } } Result.retry() } private suspend fun checkForValidArtwork( client: ContentProviderClientCompat, contentUri: Uri, data: Cursor ): Artwork? { val providerArtwork = com.google.android.apps.muzei.api.provider.Artwork.fromCursor(data) val artworkUri = ContentUris.withAppendedId(contentUri, providerArtwork.id) try { client.openInputStream(artworkUri)?.use { inputStream -> if (inputStream.isValidImage()) { return Artwork(artworkUri).apply { title = providerArtwork.title byline = providerArtwork.byline attribution = providerArtwork.attribution } } else { if (BuildConfig.DEBUG) { Log.w(TAG, "Artwork $artworkUri is not a valid image") } // Tell the client that the artwork is invalid client.call(ProtocolConstants.METHOD_MARK_ARTWORK_INVALID, artworkUri.toString()) } } } catch (e: IOException) { Log.i(TAG, "Unable to preload artwork $artworkUri: ${e.message}") } catch (e: Exception) { when (e) { is CancellationException -> throw e else -> Log.i(TAG, "Provider ${contentUri.authority} crashed preloading artwork " + "$artworkUri: ${e.message}") } } return null } }
apache-2.0
f4bc9c9d67916c5e70a2e0415f8bc050
50.731884
115
0.544302
5.846437
false
false
false
false
HTWDD/HTWDresden
app/src/main/java/de/htwdd/htwdresden/ui/models/Management.kt
1
12389
package de.htwdd.htwdresden.ui.models import android.view.LayoutInflater import android.widget.LinearLayout import androidx.databinding.DataBindingUtil import androidx.databinding.ObservableField import de.htwdd.htwdresden.BR import de.htwdd.htwdresden.R import de.htwdd.htwdresden.databinding.TemplateFreeDayBindableBinding import de.htwdd.htwdresden.databinding.TemplateManagementOffersBindableBinding import de.htwdd.htwdresden.databinding.TemplateManagementTimesBindableBinding import de.htwdd.htwdresden.interfaces.Identifiable import de.htwdd.htwdresden.interfaces.Modelable import de.htwdd.htwdresden.utils.extensions.format import de.htwdd.htwdresden.utils.extensions.toDate import de.htwdd.htwdresden.utils.holders.ContextHolder import de.htwdd.htwdresden.utils.holders.StringHolder import java.util.* import kotlin.collections.ArrayList //-------------------------------------------------------------------------------------------------- Protocols interface Managementable: Identifiable<ManagementableModels> interface ManagementableModels: Modelable //-------------------------------------------------------------------------------------------------- JSON data class JSemesterPlan ( val year: Long, val type: String, val period: JPeriod, val freeDays: List<JFreeDay>, val lecturePeriod: JPeriod, val examsPeriod: JPeriod, val reregistration: JPeriod ) data class JPeriod ( val beginDay: String, val endDay: String ) data class JFreeDay ( val name: String, val beginDay: String, val endDay: String ) data class JManagement ( val type: Int, val room: String, val offeredServices: List<String>, val officeHours: List<JOfficeHour>, val link: String ) data class JOfficeHour ( val day: String, val times: List<JTime> ) data class JTime ( val begin: String, val end: String ) //-------------------------------------------------------------------------------------------------- Concrete Models class SemesterPlan( val year: Long, val type: String, val period: Period, val freeDays: List<FreeDay>, val lecturePeriod: Period, val examsPeriod: Period, val reregistration: Period) { companion object { fun from(json: JSemesterPlan): SemesterPlan { return SemesterPlan( json.year, json.type, Period.from(json.period), json.freeDays.map { FreeDay.from(it) }, Period.from(json.lecturePeriod), Period.from(json.examsPeriod), Period.from(json.reregistration) ) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = year.hashCode() result = 31 * result + type.hashCode() result = 31 * result + period.hashCode() result = 31 * result + freeDays.hashCode() result = 31 * result + lecturePeriod.hashCode() result = 31 * result + examsPeriod.hashCode() result = 31 * result + reregistration.hashCode() return result } } class Period( val beginDay: Date, val endDay: Date) { companion object { fun from(json: JPeriod): Period { return Period( json.beginDay.toDate()!!, json.endDay.toDate()!! ) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = beginDay.hashCode() result = 31 * result + endDay.hashCode() return result } } class FreeDay( val name: String, val beginDay: Date, val endDay: Date) { companion object { fun from(json: JFreeDay): FreeDay { return FreeDay( json.name, json.beginDay.toDate()!!, json.endDay.toDate()!! ) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + beginDay.hashCode() result = 31 * result + endDay.hashCode() return result } } class Management( val type: Int, val room: String, val offeredServices: List<String>, val officeHours: List<OfficeHour>, val link: String ) { companion object { fun from(json: JManagement): Management { return Management( json.type, json.room, json.offeredServices, json.officeHours.map { OfficeHour.from(it) }, json.link ) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = type result = 31 * result + room.hashCode() result = 31 * result + offeredServices.hashCode() result = 31 * result + officeHours.hashCode() result = 31 * result + link.hashCode() return result } } class OfficeHour( val day: String, val times: List<Time> ) { companion object { fun from(json: JOfficeHour): OfficeHour { return OfficeHour( json.day, json.times.map { Time.from(it) } ) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = day.hashCode() result = 31 * result + times.hashCode() return result } } class Time( val begin: String, val end: String ) { companion object { fun from(json: JTime): Time { return Time( json.begin, json.end ) } } override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode(): Int { var result = begin.hashCode() result = 31 * result + end.hashCode() return result } } //-------------------------------------------------------------------------------------------------- Semester Plan Item class SemesterPlanItem(private val item: SemesterPlan): Managementable, Comparable<SemesterPlanItem> { override val viewType: Int get() = R.layout.list_item_management_semester_plan_bindable override val bindings by lazy { ArrayList<Pair<Int, ManagementableModels>>().apply { add(BR.semsterPlanModel to model) } } private val model = SemesterPlanModel() private val sh: StringHolder by lazy { StringHolder.instance } init { model.apply { year.set(item.year.toString()) type.set(when (item.type) { "W" -> sh.getString(R.string.academic_year_winter) else -> sh.getString(R.string.academic_year_summer) }) semesterPeriod.set("${item.period.beginDay.format(sh.getString(R.string.period_date_format))} - ${item.period.endDay.format(sh.getString(R.string.period_date_format))}") examsPeriod.set("${item.examsPeriod.beginDay.format(sh.getString(R.string.period_date_format))} - ${item.examsPeriod.endDay.format(sh.getString(R.string.period_date_format))}") reregistration.set("${item.reregistration.beginDay.format(sh.getString(R.string.period_date_format))} - ${item.reregistration.endDay.format(sh.getString(R.string.period_date_format))}") } } fun addAdditionalInfo(layout: LinearLayout) { layout.removeAllViews() item.freeDays.forEach { freeDay -> val additionalView = LayoutInflater.from(layout.context).inflate(R.layout.template_free_day_bindable, null, false) val binding = DataBindingUtil.bind<TemplateFreeDayBindableBinding>(additionalView)?.apply { freeDayModel = FreeDayModel().apply { name.set(freeDay.name) if (freeDay.beginDay != freeDay.endDay) { time.set("${freeDay.beginDay.format(sh.getString(R.string.period_date_format))} - ${freeDay.endDay.format(sh.getString(R.string.period_date_format))}") } else { time.set(freeDay.beginDay.format(sh.getString(R.string.period_date_format))) } } } layout.addView(binding?.root) } } override fun compareTo(other: SemesterPlanItem) = item.year.compareTo(other.item.year) override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = item.hashCode() } //-------------------------------------------------------------------------------------------------- Management Item class ManagementItem(private val item: Management): Managementable, Comparable<ManagementItem> { override val viewType: Int get() = R.layout.list_item_management_bindable override val bindings by lazy { ArrayList<Pair<Int, ManagementableModels>>().apply { add(BR.managementModel to model) } } private val model = ManagementModel() private val sh: StringHolder by lazy { StringHolder.instance } init { model.apply { name.set(when (item.type) { 1 -> sh.getString(R.string.management_office) 2 -> sh.getString(R.string.management_examination_office) else -> sh.getString(R.string.management_stura) }) link.set(item.link) room.set(item.room) } } fun offers(layout: LinearLayout) { layout.removeAllViews() item.offeredServices.forEach { offerEntry -> val offerView = LayoutInflater.from(layout.context).inflate(R.layout.template_management_offers_bindable, null, false) val binding = DataBindingUtil.bind<TemplateManagementOffersBindableBinding>(offerView)?.apply { offerModel = OfferModel().apply { offer.set(offerEntry) } } layout.addView(binding?.root) } } fun times(layout: LinearLayout) { layout.removeAllViews() item.officeHours.forEach { officeHour -> val officeHourView = LayoutInflater.from(layout.context).inflate(R.layout.template_management_times_bindable, null, false) val binding = DataBindingUtil.bind<TemplateManagementTimesBindableBinding>(officeHourView)?.apply { timeModel = TimeModel().apply { day.set(when (officeHour.day) { "Mo" -> sh.getString(R.string.monday) "Di" -> sh.getString(R.string.tuesday) "Mi" -> sh.getString(R.string.wednesday) "Do" -> sh.getString(R.string.thursday) "Fr" -> sh.getString(R.string.friday) else -> officeHour.day }) time.set(officeHour.times.joinToString("\n") { "${it.begin} - ${it.end}"}) } } layout.addView(binding?.root) } } override fun compareTo(other: ManagementItem) = item.type.compareTo(other.item.type) override fun equals(other: Any?) = hashCode() == other.hashCode() override fun hashCode() = item.hashCode() } //-------------------------------------------------------------------------------------------------- Modelable class SemesterPlanModel: ManagementableModels { val year = ObservableField<String>() val type = ObservableField<String>() val semesterPeriod = ObservableField<String>() val examsPeriod = ObservableField<String>() val reregistration = ObservableField<String>() } class ManagementModel: ManagementableModels { val name = ObservableField<String>() val room = ObservableField<String>() val link = ObservableField<String>() private val ch: ContextHolder by lazy { ContextHolder.instance } fun goToLink() = ch.openUrl(link.get()) } class FreeDayModel: ManagementableModels { val name = ObservableField<String>() val time = ObservableField<String>() } class OfferModel: ManagementableModels { val offer = ObservableField<String>() } class TimeModel: ManagementableModels { val day = ObservableField<String>() val time = ObservableField<String>() }
mit
10a60ee88665c1d543cdc2b61a867cc0
31.952128
197
0.586004
4.421485
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/ClassVtablesBuilder.kt
1
6285
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.descriptors import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.llvm.functionName import org.jetbrains.kotlin.backend.konan.llvm.localHash import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.OverridingUtil import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny internal val FunctionDescriptor.canBeCalledVirtually: Boolean // We check that either method is open, or one of declarations it overrides is open. get() = isOverridable || DescriptorUtils.getAllOverriddenDeclarations(this).any { it.isOverridable } internal class OverriddenFunctionDescriptor(val descriptor: FunctionDescriptor, overriddenDescriptor: FunctionDescriptor) { val overriddenDescriptor = overriddenDescriptor.original val needBridge: Boolean get() = descriptor.target.needBridgeTo(overriddenDescriptor) val bridgeDirections: BridgeDirections get() = descriptor.target.bridgeDirectionsTo(overriddenDescriptor) val canBeCalledVirtually: Boolean get() { if (overriddenDescriptor.isObjCClassMethod()) { return descriptor.canObjCClassMethodBeCalledVirtually(this.overriddenDescriptor) } // We check that either method is open, or one of declarations it overrides is open. return overriddenDescriptor.canBeCalledVirtually } val inheritsBridge: Boolean get() = !descriptor.kind.isReal && OverridingUtil.overrides(descriptor.target, overriddenDescriptor) && descriptor.bridgeDirectionsTo(overriddenDescriptor).allNotNeeded() fun getImplementation(context: Context): FunctionDescriptor { val target = descriptor.target if (!needBridge) return target val bridgeOwner = if (inheritsBridge) { target // Bridge is inherited from superclass. } else { descriptor } return context.specialDeclarationsFactory.getBridgeDescriptor(OverriddenFunctionDescriptor(bridgeOwner, overriddenDescriptor)) } override fun toString(): String { return "(descriptor=$descriptor, overriddenDescriptor=$overriddenDescriptor)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OverriddenFunctionDescriptor) return false if (descriptor != other.descriptor) return false if (overriddenDescriptor != other.overriddenDescriptor) return false return true } override fun hashCode(): Int { var result = descriptor.hashCode() result = 31 * result + overriddenDescriptor.hashCode() return result } } internal class ClassVtablesBuilder(val classDescriptor: ClassDescriptor, val context: Context) { val vtableEntries: List<OverriddenFunctionDescriptor> by lazy { assert(!classDescriptor.isInterface) val superVtableEntries = if (KotlinBuiltIns.isSpecialClassWithNoSupertypes(classDescriptor)) { emptyList() } else { context.getVtableBuilder(classDescriptor.getSuperClassOrAny()).vtableEntries } val methods = classDescriptor.sortedContributedMethods val newVtableSlots = mutableListOf<OverriddenFunctionDescriptor>() val inheritedVtableSlots = superVtableEntries.map { superMethod -> val overridingMethod = methods.singleOrNull { OverridingUtil.overrides(it, superMethod.descriptor) } if (overridingMethod == null) { superMethod } else { newVtableSlots.add(OverriddenFunctionDescriptor(overridingMethod, superMethod.descriptor)) OverriddenFunctionDescriptor(overridingMethod, superMethod.overriddenDescriptor) } } // Add all possible (descriptor, overriddenDescriptor) edges for now, redundant will be removed later. methods.mapTo(newVtableSlots) { OverriddenFunctionDescriptor(it, it) } val inheritedVtableSlotsSet = inheritedVtableSlots.map { it.descriptor to it.bridgeDirections }.toSet() val filteredNewVtableSlots = newVtableSlots .filterNot { inheritedVtableSlotsSet.contains(it.descriptor to it.bridgeDirections) } .distinctBy { it.descriptor to it.bridgeDirections } .filter { it.descriptor.isOverridable } inheritedVtableSlots + filteredNewVtableSlots.sortedBy { it.overriddenDescriptor.functionName.localHash.value } } fun vtableIndex(function: FunctionDescriptor): Int { val bridgeDirections = function.target.bridgeDirectionsTo(function.original) val index = vtableEntries.indexOfFirst { it.descriptor == function.original && it.bridgeDirections == bridgeDirections } if (index < 0) throw Error(function.toString() + " not in vtable of " + classDescriptor.toString()) return index } val methodTableEntries: List<OverriddenFunctionDescriptor> by lazy { classDescriptor.sortedContributedMethods .flatMap { method -> method.allOverriddenDescriptors.map { OverriddenFunctionDescriptor(method, it) } } .filter { it.canBeCalledVirtually } .distinctBy { Triple(it.overriddenDescriptor.functionName, it.descriptor, it.needBridge) } .sortedBy { it.overriddenDescriptor.functionName.localHash.value } // TODO: probably method table should contain all accessible methods to improve binary compatibility } }
apache-2.0
2b5cb1b74f336067a2d1e6ea4d17805d
43.574468
134
0.716468
5.268231
false
false
false
false
redundent/kotlin-xml-builder
kotlin-xml-builder/src/main/kotlin/org/redundent/kotlin/xml/sitemap.kt
1
1174
package org.redundent.kotlin.xml import java.text.SimpleDateFormat import java.util.* const val DEFAULT_URLSET_NAMESPACE = "http://www.sitemaps.org/schemas/sitemap/0.9" class UrlSet internal constructor(): Node("urlset") { init { xmlns = DEFAULT_URLSET_NAMESPACE } fun url( loc: String, lastmod: Date? = null, changefreq: ChangeFreq? = null, priority: Double? = null) { "url" { "loc"(loc) lastmod?.let { "lastmod"(formatDate(it)) } changefreq?.let { "changefreq"(it.name) } priority?.let { "priority"(it.toString()) } } } } class Sitemapindex internal constructor(): Node("sitemapindex") { init { xmlns = DEFAULT_URLSET_NAMESPACE } fun sitemap( loc: String, lastmod: Date? = null) { "sitemap" { "loc"(loc) lastmod?.let { "lastmod"(formatDate(it)) } } } } enum class ChangeFreq { always, hourly, daily, weekly, monthly, yearly, never } private fun formatDate(date: Date): String { return SimpleDateFormat("yyyy-MM-dd").format(date) } fun urlset(init: UrlSet.() -> Unit) = UrlSet().apply(init) fun sitemapindex(init: Sitemapindex.() -> Unit) = Sitemapindex().apply(init)
apache-2.0
e873a50af91a9d457057ea70c3b42fe5
15.785714
82
0.649063
2.856448
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/intrinsics/tostring.kt
4
1767
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS fun box(): String { if (239.toByte().toString() != (239.toByte() as Byte?).toString()) return "byte failed" if (239.toShort().toString() != (239.toShort() as Short?).toString()) return "short failed" if (239.toInt().toString() != (239.toInt() as Int?).toString()) return "int failed" if (239.toFloat().toString() != (239.toFloat() as Float?).toString()) return "float failed" if (239.toLong().toString() != (239.toLong() as Long?).toString()) return "long failed" if (239.toDouble().toString() != (239.toDouble() as Double?).toString()) return "double failed" if (true.toString() != (true as Boolean?).toString()) return "boolean failed" if ('a'.toChar().toString() != ('a'.toChar() as Char?).toString()) return "char failed" if ("${239.toByte()}" != (239.toByte() as Byte?).toString()) return "byte template failed" if ("${239.toShort()}" != (239.toShort() as Short?).toString()) return "short template failed" if ("${239.toInt()}" != (239.toInt() as Int?).toString()) return "int template failed" if ("${239.toFloat()}" != (239.toFloat() as Float?).toString()) return "float template failed" if ("${239.toLong()}" != (239.toLong() as Long?).toString()) return "long template failed" if ("${239.toDouble()}" != (239.toDouble() as Double?).toString()) return "double template failed" if ("${true}" != (true as Boolean?).toString()) return "boolean template failed" if ("${'a'.toChar()}" != ('a'.toChar() as Char?).toString()) return "char template failed" for(b in 0..255) { if("${b.toByte()}" != (b.toByte() as Byte?).toString()) return "byte conversion failed" } return "OK" }
apache-2.0
3de18dad456d37cc2b8d0295ff34e379
62.142857
103
0.618563
3.759574
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/completion/gitmoji/GitmojiMetadata.kt
1
1271
package zielu.gittoolbox.completion.gitmoji import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.constructor.Constructor import zielu.gittoolbox.UtfSeq import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap internal object GitmojiMetadata { private val metadata: Gitmojis by lazy { load() } private val characters: ConcurrentMap<String, List<Char>> = ConcurrentHashMap() private fun load(): Gitmojis { val yaml = Yaml(Constructor(Gitmojis::class.java)) return yaml.load(this::class.java.getResourceAsStream("/zielu/gittoolbox/gitmoji.yaml")) } fun getKeywords(gitmoji: String): List<String> { return metadata.gitmojis[gitmoji]?.keywords ?: listOf() } fun getCharacters(gitmoji: String): List<Char> { return metadata.gitmojis[gitmoji]?.let { found -> characters.computeIfAbsent(gitmoji) { UtfSeq.fromCodepoint(found.codepoint, found.requiresVariation) } } ?: listOf() } fun getUnicode(gitmoji: String): String = String(getCharacters(gitmoji).toCharArray()) } data class Gitmojis( var gitmojis: Map<String, Gitmoji> = mapOf() ) data class Gitmoji( var keywords: List<String> = listOf(), var requiresVariation: Boolean = false, var codepoint: String = "" )
apache-2.0
47b040f7209fdd5b59dd06273e0911a3
28.55814
92
0.734854
3.839879
false
false
false
false
android/compose-samples
Jetchat/app/src/main/java/com/example/compose/jetchat/conversation/ConversationUiState.kt
1
1392
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.compose.jetchat.conversation import androidx.compose.runtime.Immutable import androidx.compose.runtime.toMutableStateList import com.example.compose.jetchat.R class ConversationUiState( val channelName: String, val channelMembers: Int, initialMessages: List<Message> ) { private val _messages: MutableList<Message> = initialMessages.toMutableStateList() val messages: List<Message> = _messages fun addMessage(msg: Message) { _messages.add(0, msg) // Add to the beginning of the list } } @Immutable data class Message( val author: String, val content: String, val timestamp: String, val image: Int? = null, val authorImage: Int = if (author == "me") R.drawable.ali else R.drawable.someone_else )
apache-2.0
b653431079794aa64bf75c935002ba2f
31.372093
90
0.73204
4.058309
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/TypeMap.kt
12
1808
// 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.protocolModelGenerator import java.util.* /** * Keeps track of all referenced types. * A type may be used and resolved (generated or hard-coded). */ internal class TypeMap { private val map = HashMap<Pair<String, String>, TypeData>() var domainGeneratorMap: Map<String, DomainGenerator>? = null private val typesToGenerate = ArrayDeque<StandaloneTypeBinding>() fun resolve(domainName: String, typeName: String, direction: TypeData.Direction): BoxableType? { val domainGenerator = domainGeneratorMap!!.get(domainName) if (domainGenerator == null) { val qName = "$domainName.$typeName" if (qName == "IO.StreamHandle" || qName == "Security.SecurityState" || qName == "Security.CertificateId" || qName == "Emulation.ScreenOrientation" || qName == "Security.MixedContentType" ) { return BoxableType.ANY_STRING // ignore } throw RuntimeException("Failed to find domain generator: $domainName for type $typeName") } return direction.get(getTypeData(domainName, typeName)).resolve(this, domainGenerator) } fun addTypeToGenerate(binding: StandaloneTypeBinding) { typesToGenerate.offer(binding) } fun generateRequestedTypes() { // size may grow during iteration val createdTypes = HashSet<CharSequence>() while (typesToGenerate.isNotEmpty()) { val binding = typesToGenerate.poll() if (createdTypes.add(binding.getJavaType().fullText)) { binding.generate() } } } fun getTypeData(domainName: String, typeName: String) = map.getOrPut(Pair(domainName, typeName)) { TypeData(typeName) } }
apache-2.0
86c81e18cd5d7ac96b89cbb64d0cc719
35.16
140
0.697456
4.52
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/checker/JvmStaticUsagesRuntime.kt
7
1806
// RUNTIME <error descr="[WRONG_ANNOTATION_TARGET] This annotation is not applicable to target 'class'">@JvmStatic</error> class A { <error descr="[WRONG_ANNOTATION_TARGET] This annotation is not applicable to target 'companion object'">@JvmStatic</error> companion object { @JvmStatic fun a1() { } } <error descr="[WRONG_ANNOTATION_TARGET] This annotation is not applicable to target 'object'">@JvmStatic</error> object A { @JvmStatic fun a2() { } } fun test() { val <warning descr="[UNUSED_VARIABLE] Variable 's' is never used">s</warning> = object { <error descr="[JVM_STATIC_NOT_IN_OBJECT_OR_COMPANION] Only members in named objects and companion objects can be annotated with '@JvmStatic'">@JvmStatic fun a3()</error> { } } } <error descr="[JVM_STATIC_NOT_IN_OBJECT_OR_COMPANION] Only members in named objects and companion objects can be annotated with '@JvmStatic'">@JvmStatic fun a4()</error> { } } <error descr="[WRONG_ANNOTATION_TARGET] This annotation is not applicable to target 'interface'">@JvmStatic</error> interface B { companion object { @JvmStatic fun a1() { } } object A { @JvmStatic fun a2() { } } fun test() { val <warning descr="[UNUSED_VARIABLE] Variable 's' is never used">s</warning> = object { <error descr="[JVM_STATIC_NOT_IN_OBJECT_OR_COMPANION] Only members in named objects and companion objects can be annotated with '@JvmStatic'">@JvmStatic fun a3()</error> { } } } <error descr="[JVM_STATIC_NOT_IN_OBJECT_OR_COMPANION] Only members in named objects and companion objects can be annotated with '@JvmStatic'">@JvmStatic fun a4()</error> { } }
apache-2.0
bf97383e83f1e070a82df999d0765a85
31.25
183
0.636766
4.249412
false
false
false
false
fabmax/kool
kool-core/src/jsMain/kotlin/de/fabmax/kool/platform/ImageTextureData.kt
1
507
package de.fabmax.kool.platform import de.fabmax.kool.pipeline.TexFormat import de.fabmax.kool.pipeline.TextureData import org.w3c.dom.HTMLImageElement class ImageTextureData(val image: HTMLImageElement, fmt: TexFormat?) : TextureData() { override val data = image init { if (!image.complete) { throw IllegalStateException("Image must be complete") } width = image.width height = image.height depth = 1 fmt?.let { format = it } } }
apache-2.0
64b23fd92dbe3e6cd4f82ccdc8ab5193
24.4
86
0.658777
4.190083
false
false
false
false
fabmax/kool
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/HttpCache.kt
1
7457
package de.fabmax.kool.platform import de.fabmax.kool.KoolException import de.fabmax.kool.util.logD import de.fabmax.kool.util.logW import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.nio.charset.StandardCharsets import java.util.* import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream import kotlin.concurrent.thread class HttpCache private constructor(private val cacheDir: File) { private val cache = mutableMapOf<File, CacheEntry>() private var cacheSize = 0L init { try { GZIPInputStream(FileInputStream(File(cacheDir, ".cacheIndex.json.gz"))).use { inStream -> val txt = String(inStream.readBytes(), StandardCharsets.UTF_8) val serCache = Json.decodeFromString<SerCache>(txt) serCache.items.forEach { val f = File(it.file) if (f.canRead()) { addCacheEntry(CacheEntry(f, it.size, it.access)) } } } } catch (e: Exception) { logD { "Rebuilding http cache index, $e" } rebuildIndex() } Runtime.getRuntime().addShutdownHook(thread(false) { close() }) } private fun close() { saveIndex() } private fun rebuildIndex() { synchronized(cache) { cache.clear() if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw KoolException("Failed to create cache directory") } } fun File.walk(recv: (File) -> Unit) { listFiles()?.forEach { if (it.isDirectory) { it.walk(recv) } else { recv(it) } } } cacheDir.walk { if (it.name != ".cacheIndex") { addCacheEntry(CacheEntry(it)) } } saveIndex() } private fun addCacheEntry(entry: CacheEntry) { synchronized(cache) { if (entry.file.canRead()) { cacheSize -= cache[entry.file]?.size ?: 0 cacheSize += entry.size cache[entry.file] = entry } else { logW { "Cache entry not readable: ${entry.file}" } } } checkCacheSize() } private fun saveIndex() { val entries = synchronized(cache) { val items = mutableListOf<SerCacheItem>() cache.values.forEach { items += SerCacheItem(it.file.path, it.size, it.lastAccess) } SerCache(items) } try { GZIPOutputStream(FileOutputStream(File(cacheDir, ".cacheIndex.json.gz"))).use { it.write(Json.encodeToString(entries).toByteArray(StandardCharsets.UTF_8)) } } catch (e: Exception) { e.printStackTrace() } } private fun checkCacheSize() { if (cacheSize > MAX_CACHE_SIZE) { val removeQueue = PriorityQueue<CacheEntry>() synchronized(cache) { removeQueue.addAll(cache.values) } var rmCnt = 0 while (!removeQueue.isEmpty() && cacheSize > MAX_CACHE_SIZE * 0.8) { val rmEntry = removeQueue.poll() rmEntry.file.delete() logD { "Deleted from cache: ${rmEntry.file}" } synchronized(cache) { cache.remove(rmEntry.file) cacheSize -= rmEntry.size } rmCnt++ } } } fun loadHttpResource(url: String): File? { val req = URL(url) // use host-name as cache directory name, sub-domain components are dropped // e.g. a.tile.openstreetmap.org and b.tile.openstreetmap.org should share the same cache dir var host = req.host while (host.count { it == '.' } > 1) { host = host.substring(host.indexOf('.') + 1) } val file = if (req.query != null) { File(cacheDir, "/$host/${req.path}_${req.query}") } else { File(cacheDir, "/$host/${req.path}") } if (!file.canRead()) { // download file and add to cache try { val con = req.openConnection() as HttpURLConnection if (req.host in credentialsMap.keys) { con.addRequestProperty("Authorization", credentialsMap[req.host]!!.encoded) } if (con.responseCode == 200) { con.inputStream.copyTo(file) addCacheEntry(CacheEntry(file)) return file } else { logW { "Unexpected response on downloading $url: ${con.responseCode} - ${con.responseMessage}" } } } catch (e: Exception) { logW { "Exception during download of $url: $e" } } } return if (file.canRead()) { synchronized(cache) { cache[file]?.lastAccess = System.currentTimeMillis() } file } else { logW { "Failed downloading $url" } null } } private fun InputStream.copyTo(file: File): Long { file.parentFile.mkdirs() return use { inStream -> FileOutputStream(file).use { outStream -> inStream.copyTo(outStream, 4096) } } } companion object { private const val MAX_CACHE_SIZE = 1024L * 1024L * 1024L private var instance: HttpCache? = null private val credentialsMap = mutableMapOf<String, BasicAuthCredentials>() fun addCredentials(credentials: BasicAuthCredentials) { credentialsMap[credentials.forHost] = credentials } fun initCache(cacheDir: File) { if (instance == null) { instance = HttpCache(cacheDir) } } fun loadHttpResource(url: String): File? { val inst = instance ?: throw KoolException("Default cache used before initCache() was called") return inst.loadHttpResource(url) } } class BasicAuthCredentials(val forHost: String, user: String, password: String) { val encoded = "Basic " + Base64.getEncoder().encodeToString("$user:$password".toByteArray()) } private class CacheEntry(val file: File, var size: Long, lastAccess: Long) : Comparable<CacheEntry> { var lastAccess = lastAccess set(value) { field = value file.setLastModified(value) } constructor(file: File) : this(file, file.length(), file.lastModified()) override fun compareTo(other: CacheEntry): Int { return when { lastAccess < other.lastAccess -> -1 lastAccess > other.lastAccess -> 1 else -> 0 } } } } @Serializable data class SerCache(val items: List<SerCacheItem>) @Serializable data class SerCacheItem(val file: String, val size: Long, val access: Long)
apache-2.0
261a3320ee326377fb97b31142ff60b0
31.563319
116
0.545394
4.704732
false
false
false
false
fabmax/kool
kool-demo/src/jsMain/kotlin/WebGpuTest.kt
1
8807
import de.fabmax.kool.platform.webgpu.* import kotlinx.browser.document import kotlinx.browser.window import kotlinx.coroutines.await import org.khronos.webgl.Float32Array import org.khronos.webgl.Uint32Array import org.w3c.dom.HTMLCanvasElement import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.startCoroutine import kotlin.math.roundToInt val vertexCode = """ struct VSOut { @builtin(position) Position: vec4<f32>, @location(0) color: vec3<f32> }; struct UBO { modelViewProj: mat4x4<f32>, primaryColor: vec4<f32>, accentColor: vec4<f32> }; @group(0) @binding(0) var<uniform> uniforms: UBO; @stage(vertex) fn main(@location(0) inPos: vec3<f32>, @location(1) inColor: vec3<f32>) -> VSOut { var vsOut: VSOut; vsOut.Position = vec4<f32>(inPos, 1.0); vsOut.color = inColor * uniforms.accentColor.rgb + uniforms.primaryColor.rgb; return vsOut; } """.trimIndent() val fragmentCode = """ @stage(fragment) fn main(@location(0) inColor: vec3<f32>) -> @location(0) vec4<f32> { return vec4<f32>(inColor, 1.0); } """.trimIndent() val vertexData = arrayOf(1f, -1f, 0f, -1f, -1f, 0f, 0f, 1f, 0f) val colorData = arrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) val indexData = arrayOf(0, 1, 2) val uniformData = arrayOf( 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0.9f, 0.1f, 0.3f, 1f, 0.8f, 0.2f, 0.8f, 1f ) lateinit var canvas: HTMLCanvasElement lateinit var device: GPUDevice lateinit var context: GPUCanvasContext lateinit var pipeline: GPURenderPipeline lateinit var view: GPUTextureView lateinit var vertexBuffer: GPUBuffer lateinit var colorBuffer: GPUBuffer lateinit var indexBuffer: GPUBuffer lateinit var uniformBuffer: GPUBuffer lateinit var uniformBindGroup: GPUBindGroup /** * WebGPU hello world test / demo, for now this is not integrated into kool at all... * * Only works on Chrome Canary with --enable-unsafe-webgpu */ fun webGpuTest() { launch { canvas = document.getElementById("glCanvas") as HTMLCanvasElement val adapter = navigator.gpu.requestAdapter().await() device = adapter.requestDevice().await() val ctx = canvas.getContext("webgpu") as? GPUCanvasContext if (ctx == null) { js("alert(\"Unable to initialize WebGL2 context. Your browser may not support it.\")") throw RuntimeException("Unable to obtain WebGPU context from canvas") } context = ctx val screenScale = window.devicePixelRatio val presentationSize = intArrayOf((canvas.clientWidth * screenScale).roundToInt(), (canvas.clientHeight * screenScale).roundToInt()) val presentationFormat = navigator.gpu.getPreferredCanvasFormat() val sampleCount = 4 canvas.width = presentationSize[0] canvas.height = presentationSize[1] context.configure( GPUCanvasConfiguration( device = device, format = presentationFormat ) ) println("WebGPU context configured!") vertexBuffer = createF32Buffer(vertexData, GPUBufferUsage.VERTEX) colorBuffer = createF32Buffer(colorData, GPUBufferUsage.VERTEX) indexBuffer = createU32Buffer(indexData, GPUBufferUsage.INDEX) uniformBuffer = createF32Buffer(uniformData, GPUBufferUsage.UNIFORM or GPUBufferUsage.COPY_DST) val positionBufferDesc = GPUVertexBufferLayout( attributes = arrayOf( GPUVertexAttribute( shaderLocation = 0, offset = 0, format = GPUVertexFormat.float32x3 ) ), arrayStride = 4 * 3 ) val colorBufferDesc = GPUVertexBufferLayout( attributes = arrayOf( GPUVertexAttribute( shaderLocation = 1, offset = 0, format = GPUVertexFormat.float32x3 ) ), arrayStride = 4 * 3 ) val uniformBindGroupLayout = device.createBindGroupLayout( GPUBindGroupLayoutDescriptor( entries = arrayOf( GPUBindGroupLayoutEntry( binding = 0, visibility = GPUShaderStage.VERTEX, buffer = GPUBufferBindingLayout(GPUBufferBindingType.uniform) ) ) ) ) uniformBindGroup = device.createBindGroup( GPUBindGroupDescriptor( layout = uniformBindGroupLayout, entries = arrayOf( GPUBindGroupEntry( binding = 0, resource = GPUBufferBinding(uniformBuffer) ) ) ) ) val layout = device.createPipelineLayout( GPUPipelineLayoutDescriptor( bindGroupLayouts = arrayOf(uniformBindGroupLayout) ) ) pipeline = device.createRenderPipeline( GPURenderPipelineDescriptor( layout = layout, vertex = GPUVertexState( module = device.createShaderModule(GPUShaderModuleDescriptor(vertexCode)), entryPoint = "main", buffers = arrayOf(positionBufferDesc, colorBufferDesc) ), fragment = GPUFragmentState( module = device.createShaderModule(GPUShaderModuleDescriptor(fragmentCode)), entryPoint = "main", targets = arrayOf(GPUColorTargetState(presentationFormat)) ), primitive = GPUPrimitiveState( topology = GPUPrimitiveTopology.triangleList ), multisample = GPUMultisampleState( count = sampleCount ) ) ) println("created pipeline!") val texture = device.createTexture( GPUTextureDescriptor( size = presentationSize, sampleCount = sampleCount, format = presentationFormat, usage = GPUTextureUsage.RENDER_ATTACHMENT ) ) view = texture.createView() println("created view!") window.requestAnimationFrame { frame() } println("started animation loop") } } fun frame() { val commandEncoder = device.createCommandEncoder() val passEncoder = commandEncoder.beginRenderPass( GPURenderPassDescriptor(arrayOf( GPURenderPassColorAttachment( view = view, resolveTarget = context.getCurrentTexture().createView(), clearValue = GPUColorDict(0.0, 0.0, 0.0, 1.0), loadOp = GPULoadOp.clear, storeOp = GPUStoreOp.store ) )) ) passEncoder.setPipeline(pipeline) passEncoder.setViewport(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), 0f, 1f) passEncoder.setVertexBuffer(0, vertexBuffer) passEncoder.setVertexBuffer(1, colorBuffer) passEncoder.setIndexBuffer(indexBuffer, GPUIndexFormat.uint32) passEncoder.setBindGroup(0, uniformBindGroup) passEncoder.drawIndexed(3) //passEncoder.draw(3, 1, 0, 0) passEncoder.end() device.queue.submit(arrayOf(commandEncoder.finish())) window.requestAnimationFrame { frame() } } fun createF32Buffer(data: Array<Float>, usage: Int): GPUBuffer { val buffer = device.createBuffer( GPUBufferDescriptor( size = data.size * 4L, usage = usage, mappedAtCreation = true ) ) val array = Float32Array(buffer.getMappedRange()) array.set(data) buffer.unmap() return buffer } fun createU32Buffer(data: Array<Int>, usage: Int): GPUBuffer { val buffer = device.createBuffer( GPUBufferDescriptor( size = data.size * 4L, usage = usage, mappedAtCreation = true ) ) val array = Uint32Array(buffer.getMappedRange()) array.set(data) buffer.unmap() return buffer } fun launch(block: suspend () -> Unit) { block.startCoroutine(object : Continuation<Unit> { override val context: CoroutineContext get() = EmptyCoroutineContext override fun resumeWith(result: Result<Unit>) { if (result.isFailure) { println("resume with failure") result.exceptionOrNull()?.printStackTrace() } } }) }
apache-2.0
bd4425c330d86d40c6be9312b4351aaf
31.743494
140
0.599977
4.441251
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/customization/AvatarCustomizationFragment.kt
1
7637
package com.habitrpg.android.habitica.ui.fragments.inventory.customization import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.GridLayoutManager import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.CustomizationRepository import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.inventory.Customization import com.habitrpg.android.habitica.models.responses.UnlockResponse import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.adapter.CustomizationRecyclerViewAdapter import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.helpers.MarginDecoration import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator import io.reactivex.Flowable import io.reactivex.functions.Consumer import io.realm.RealmResults import kotlinx.android.synthetic.main.fragment_recyclerview.* import javax.inject.Inject class AvatarCustomizationFragment : BaseMainFragment() { @Inject lateinit var customizationRepository: CustomizationRepository @Inject lateinit var inventoryRepository: InventoryRepository var type: String? = null var category: String? = null private var activeCustomization: String? = null internal var adapter: CustomizationRecyclerViewAdapter = CustomizationRecyclerViewAdapter() internal var layoutManager: GridLayoutManager = GridLayoutManager(activity, 2) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_recyclerview, container, false) compositeSubscription.add(adapter.getSelectCustomizationEvents() .flatMap { customization -> userRepository.useCustomization(user, customization.type ?: "", customization.category, customization.identifier ?: "") } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(adapter.getUnlockCustomizationEvents() .flatMap<UnlockResponse> { customization -> val user = this.user if (user != null) { userRepository.unlockPath(user, customization) } else { Flowable.empty() } } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) compositeSubscription.add(adapter.getUnlockSetEvents() .flatMap<UnlockResponse> { set -> val user = this.user if (user != null) { userRepository.unlockPath(user, set) } else { Flowable.empty() } } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val args = AvatarCustomizationFragmentArgs.fromBundle(it) type = args.type if (args.category.isNotEmpty()) { category = args.category } } val layoutManager = GridLayoutManager(activity, 4) layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (adapter.getItemViewType(position) == 0) { layoutManager.spanCount } else { 1 } } } setGridSpanCount(view.width) recyclerView.layoutManager = layoutManager recyclerView.addItemDecoration(MarginDecoration(context)) recyclerView.adapter = adapter recyclerView.itemAnimator = SafeDefaultItemAnimator() this.loadCustomizations() compositeSubscription.add(userRepository.getUser().subscribeWithErrorHandler(Consumer { updateUser(it) })) } override fun onDestroy() { customizationRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun loadCustomizations() { val type = this.type ?: return compositeSubscription.add(customizationRepository.getCustomizations(type, category, false).subscribe(Consumer<RealmResults<Customization>> { adapter.setCustomizations(it) }, RxErrorHandler.handleEmptyError())) if (type == "hair" && (category == "beard" || category == "mustache")) { val otherCategory = if (category == "mustache") "beard" else "mustache" compositeSubscription.add(customizationRepository.getCustomizations(type, otherCategory, true).subscribe(Consumer<RealmResults<Customization>> { adapter.additionalSetItems = it }, RxErrorHandler.handleEmptyError())) } } private fun setGridSpanCount(width: Int) { val itemWidth = context?.resources?.getDimension(R.dimen.customization_width) ?: 0F var spanCount = (width / itemWidth).toInt() if (spanCount == 0) { spanCount = 1 } layoutManager.spanCount = spanCount } fun updateUser(user: User) { this.updateActiveCustomization(user) if (adapter.customizationList.size != 0) { val ownedCustomizations = ArrayList<String>() user.purchased?.customizations?.filter { it.type == this.type && it.purchased }?.mapTo(ownedCustomizations) { it.key ?: "" } adapter.updateOwnership(ownedCustomizations) } else { this.loadCustomizations() } this.adapter.userSize = this.user?.preferences?.size this.adapter.hairColor = this.user?.preferences?.hair?.color this.adapter.gemBalance = user.gemCount adapter.notifyDataSetChanged() } private fun updateActiveCustomization(user: User) { if (this.type == null || user.preferences == null) { return } val prefs = this.user?.preferences val activeCustomization = when (this.type) { "skin" -> prefs?.skin "shirt" -> prefs?.shirt "background" -> prefs?.background "hair" -> when (this.category) { "bangs" -> prefs?.hair?.bangs.toString() "base" -> prefs?.hair?.base.toString() "color" -> prefs?.hair?.color "flower" -> prefs?.hair?.flower.toString() "beard" -> prefs?.hair?.beard.toString() "mustache" -> prefs?.hair?.mustache.toString() else -> "" } else -> "" } if (activeCustomization != null) { this.activeCustomization = activeCustomization this.adapter.activeCustomization = activeCustomization } } }
gpl-3.0
618143101d822b187dba8b2113a9dd1a
40.904494
227
0.631531
5.348039
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/StatefulPresentation.kt
1
3883
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints.presentation import com.intellij.codeInsight.hints.dimension import com.intellij.codeInsight.hints.fireUpdateEvent import com.intellij.openapi.editor.markup.TextAttributes import java.awt.Dimension import java.awt.Graphics2D import java.awt.Point import java.awt.Rectangle import java.awt.event.MouseEvent /** * Partially reimplementation of [DynamicDelegatePresentation], but with state * @param S state, immutable object, requires to implement meaningful equals */ abstract class StatefulPresentation<S: Any?>( state: S, val stateMark: StateMark<S> ) : BasePresentation() { private var _state = state open var state: S get() = _state set(value) { if (value != _state) { val previous = dimension() updateStateAndPresentation(value) fireUpdateEvent(previous) } } private fun updateStateAndPresentation(value: S) { val previous = dimension() _state = value val presentation = getPresentation() updatePresentation(presentation) fireUpdateEvent(previous) } private var _currentPresentation: InlayPresentation? = null val currentPresentation: InlayPresentation get() = when (val current = _currentPresentation) { null -> { val presentation = getPresentation() updatePresentation(presentation) presentation } else -> current } private fun updatePresentation(presentation: InlayPresentation) { _currentPresentation?.removeListener(listener) listener = DelegateListener() presentation.addListener(listener) _currentPresentation = presentation } private var listener = DelegateListener() override val width: Int get() = currentPresentation.width override val height: Int get() = currentPresentation.height override fun updateState(previousPresentation: InlayPresentation): Boolean { if (previousPresentation !is StatefulPresentation<*>) return true val previousState = previousPresentation._state var changed = false if (previousState != _state) { val previousMark = previousPresentation.stateMark if (stateMark == previousMark) { val castedPrevious = stateMark.cast(previousState, previousMark) if (castedPrevious != null) { updateStateAndPresentation(castedPrevious) changed = true } } } currentPresentation.updateState(previousPresentation.currentPresentation) return changed } /** * Method returns actual presentation, depending on state only. * Called once state is changed, presentation cached. * If you want to get actual presentation, use [currentPresentation] */ abstract fun getPresentation() : InlayPresentation override fun paint(g: Graphics2D, attributes: TextAttributes) { currentPresentation.paint(g, attributes) } override fun mouseClicked(event: MouseEvent, translated: Point) { currentPresentation.mouseClicked(event, translated) } override fun mouseMoved(event: MouseEvent, translated: Point) { currentPresentation.mouseMoved(event, translated) } override fun mouseExited() { currentPresentation.mouseExited() } private inner class DelegateListener : PresentationListener { override fun contentChanged(area: Rectangle) = fireContentChanged(area) override fun sizeChanged(previous: Dimension, current: Dimension) = fireSizeChanged(previous, current) } /** * Used to provide type safe access to data * @param id must be different for any different types */ data class StateMark<T: Any?>(val id: String) { @Suppress("UNCHECKED_CAST") fun cast(value: Any?, otherMark: StateMark<*>): T? { if (this != otherMark) return null return value as T? } } }
apache-2.0
6478795f98a2c5c18fe646fa3db1bace
30.322581
140
0.726758
4.695284
false
false
false
false
980f/droid
android/src/main/kotlin/pers/hal42/util/StoredProperties.kt
1
1265
package pers.hal42.util import kotlin.reflect.KClass /** * Created by andyh on 12/9/16. * stores objects in properties files as marked by Storable annoation */ class StoredProperties { fun store(thing: Any) { // for(val prop in thing.class) {println("p" $prop")} // val claz= thing::class // for(val annotation in claz.mem) { // if (note.annotationType() == Storable::class.java) { // var key = (note as Storable).key() // if (key.length == 0) { // key = field.getName() // } // //todo: switch on type recursing fields // val claz = field.getDeclaringClass() // if (claz == Number::class.java) { // try { // val value = field.getDouble(thing) // super.setProperty(key, java.lang.Double.toString(value)) // } catch (e: IllegalAccessException) { // e.printStackTrace() // //if we don't set property then it might have a stale value!! // } // // } else if (claz == Array::class.java) { // //todo: iterate over array with array index as additional key // } // break//only support a single instance of our annotation. // } // } // } } }
mit
61a3212fb1904c2ca7821230bf4cce7a
28.418605
77
0.543874
3.666667
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2k/fromClassToInterface.kt
4
638
// WITH_RUNTIME interface T abstract class <caret>B: T { companion object { // INFO: {"checked": "true"} val _x = 1 // INFO: {"checked": "true"} fun foo(n: Int): Boolean = n > 0 } // INFO: {"checked": "true"} val x = 1 // INFO: {"checked": "true"} val y: Int get() = 2 // INFO: {"checked": "true"} val z: Int by lazy { 3 } // INFO: {"checked": "true"} abstract val t: Int // INFO: {"checked": "true"} fun foo(n: Int): Boolean = n > 0 // INFO: {"checked": "true"} abstract fun bar(s: String) // INFO: {"checked": "true"} class Y { } }
apache-2.0
f0b350d6e14fd81c211a711c0d06a711
20.3
40
0.479624
3.305699
false
false
false
false
OpenConference/DroidconBerlin2017
businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/backend/data2018/SpeakerItem.kt
1
841
package de.droidcon.berlin2018.schedule.backend.data2018 import com.tickaroo.tikxml.annotation.Element import com.tickaroo.tikxml.annotation.Path import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml @Xml(name = "item") data class SpeakerItem( @PropertyElement(name = "uid") val id: String, @PropertyElement(name = "gn") val firstname: String, @PropertyElement(name = "sn") val lastname: String, @PropertyElement(name = "org") val company: String?, @PropertyElement(name = "org_uri") val companyUrl: String?, @PropertyElement(name = "position") val position: String?, @PropertyElement(name = "image") val imageUrl: String, @PropertyElement(name = "description_short") val description: String, @Path("links") @Element(name = "item") val links: List<LinkItem>? )
apache-2.0
2ed3182ca4aac6f8c809b6345a6c9b0d
43.263158
73
0.734839
3.875576
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleManagerComponentBridge.kt
2
17725
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.legacyBridge.module import com.intellij.ProjectTopics import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.AutomaticModuleUnloader import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleEx import com.intellij.openapi.module.impl.NonPersistentModuleStore import com.intellij.openapi.module.impl.UnloadedModulesListStorage import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCloseListener import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.startup.InitProjectActivity import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.workspaceModel.ide.* import com.intellij.workspaceModel.ide.impl.jps.serialization.ErrorReporter import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectEntitiesLoader import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetEntityChangeListener import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleLibraryTableBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootsChangeListener import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.VirtualFileUrlWatcher import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.VersionedEntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.IOException import java.nio.file.Path class ModuleManagerComponentBridge(private val project: Project) : ModuleManagerBridgeImpl(project) { private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) internal class ModuleManagerInitProjectActivity : InitProjectActivity { override suspend fun run(project: Project) { val moduleManager = ModuleManager.getInstance(project) as ModuleManagerComponentBridge var activity = StartUpMeasurer.startActivity("firing modules_added event", ActivityCategory.DEFAULT) val modules = moduleManager.modules().toList() moduleManager.fireModulesAdded(modules) activity = activity.endAndStart("deprecated module component moduleAdded calling") @Suppress("removal", "DEPRECATION") val deprecatedComponents = mutableListOf<com.intellij.openapi.module.ModuleComponent>() for (module in modules) { if (!module.isLoaded) { module.moduleAdded(deprecatedComponents) } } if (!deprecatedComponents.isEmpty()) { withContext(Dispatchers.EDT) { ApplicationManager.getApplication().runWriteAction { for (deprecatedComponent in deprecatedComponents) { @Suppress("DEPRECATION", "removal") deprecatedComponent.moduleAdded() } } } } activity.end() } } init { // default project doesn't have modules if (!project.isDefault) { val busConnection = project.messageBus.connect(this) busConnection.subscribe(ProjectCloseListener.TOPIC, object : ProjectCloseListener { override fun projectClosed(eventProject: Project) { if (project == eventProject) { for (module in modules()) { module.projectClosed() } } } }) val rootsChangeListener = ProjectRootsChangeListener(project) busConnection.subscribe(WorkspaceModelTopics.CHANGED, object : WorkspaceModelChangeListener { override fun beforeChanged(event: VersionedStorageChange) { if (!VirtualFileUrlWatcher.getInstance(project).isInsideFilePointersUpdate) { //the old implementation doesn't fire rootsChanged event when roots are moved or renamed, let's keep this behavior for now rootsChangeListener.beforeChanged(event) } val moduleMap = event.storageBefore.moduleMap for (change in event.getChanges(ModuleEntity::class.java)) { if (change is EntityChange.Removed) { val module = moduleMap.getDataByEntity(change.entity) LOG.debug { "Fire 'beforeModuleRemoved' event for module ${change.entity.name}, module = $module" } if (module != null) { fireBeforeModuleRemoved(module) } } } } override fun changed(event: VersionedStorageChange) { val moduleLibraryChanges = event.getChanges(LibraryEntity::class.java).filterModuleLibraryChanges() val changes = event.getChanges(ModuleEntity::class.java) if (changes.isNotEmpty() || moduleLibraryChanges.isNotEmpty()) { LOG.debug("Process changed modules and facets") incModificationCount() for (change in moduleLibraryChanges) { when (change) { is EntityChange.Removed -> processModuleLibraryChange(change, event) is EntityChange.Replaced -> processModuleLibraryChange(change, event) is EntityChange.Added -> Unit } } val oldModuleNames = mutableMapOf<Module, String>() val unloadedModulesSet = UnloadedModulesListStorage.getInstance(project).unloadedModuleNames for (change in changes) { processModuleChange(change, unloadedModulesSet, oldModuleNames, event) } for (change in moduleLibraryChanges) { if (change is EntityChange.Added) processModuleLibraryChange(change, event) } // After every change processed postProcessModules(oldModuleNames) incModificationCount() } // Roots changed should be sent after syncing with legacy bridge if (!VirtualFileUrlWatcher.getInstance(project).isInsideFilePointersUpdate) { //the old implementation doesn't fire rootsChanged event when roots are moved or renamed, let's keep this behavior for now rootsChangeListener.changed(event) } } }) // Instantiate facet change listener as early as possible project.service<FacetEntityChangeListener>() } } @Suppress("UNCHECKED_CAST") override fun initializeBridges(event: Map<Class<*>, List<EntityChange<*>>>, builder: MutableEntityStorage) { // Initialize modules val moduleChanges = (event[ModuleEntity::class.java] as? List<EntityChange<ModuleEntity>>) ?: emptyList() for (moduleChange in moduleChanges) { initializeModuleBridge(moduleChange, builder) } // Initialize facets FacetEntityChangeListener.getInstance(project).initializeFacetBridge(event, builder) // Initialize module libraries val moduleLibraryChanges = ((event[LibraryEntity::class.java] as? List<EntityChange<LibraryEntity>>) ?: emptyList()) .filterModuleLibraryChanges() for (change in moduleLibraryChanges) { initializeModuleLibraryBridge(change, builder) } } private fun initializeModuleBridge(change: EntityChange<ModuleEntity>, builder: MutableEntityStorage) { val unloadedModuleNames = UnloadedModulesListStorage.getInstance(project).unloadedModuleNames if (change is EntityChange.Added) { val alreadyCreatedModule = change.entity.findModule(builder) if (alreadyCreatedModule == null) { if (change.entity.name in unloadedModuleNames) { return } // Create module bridge val plugins = PluginManagerCore.getPluginSet().getEnabledModules() val module = createModuleInstance(moduleEntity = change.entity, versionedStorage = entityStore, diff = builder, isNew = true, precomputedExtensionModel = null, plugins = plugins, corePlugin = plugins.firstOrNull { it.pluginId == PluginManagerCore.CORE_ID }) builder.mutableModuleMap.addMapping(change.entity, module) } } } private fun initializeModuleLibraryBridge(change: EntityChange<LibraryEntity>, builder: MutableEntityStorage) { if (change is EntityChange.Added) { val tableId = change.entity.tableId as LibraryTableId.ModuleLibraryTableId val moduleEntity = builder.resolve(tableId.moduleId) ?: error("Could not find module for module library: ${change.entity.symbolicId}") if (moduleEntity.name !in unloadedModules) { val library = builder.libraryMap.getDataByEntity(change.entity) if (library == null) { val module = moduleEntity.findModule(builder) ?: error("Could not find module bridge for module entity $moduleEntity") val moduleRootComponent = ModuleRootComponentBridge.getInstance(module) (moduleRootComponent.getModuleLibraryTable() as ModuleLibraryTableBridgeImpl).addLibrary(change.entity, builder) } } } } private fun postProcessModules(oldModuleNames: MutableMap<Module, String>) { if (oldModuleNames.isNotEmpty()) { project.messageBus .syncPublisher(ProjectTopics.MODULES) .modulesRenamed(project, oldModuleNames.keys.toList()) { module -> oldModuleNames[module] } } if (unloadedModules.isNotEmpty()) { AutomaticModuleUnloader.getInstance(project).setLoadedModules(modules.map { it.name }) } } private fun processModuleChange(change: EntityChange<ModuleEntity>, unloadedModuleNames: Set<String>, oldModuleNames: MutableMap<Module, String>, event: VersionedStorageChange) { when (change) { is EntityChange.Removed -> { // It's possible case then idToModule doesn't contain element e.g. if unloaded module was removed val module = change.entity.findModule(event.storageBefore) if (module != null) { fireEventAndDisposeModule(module) } } is EntityChange.Added -> { val alreadyCreatedModule = change.entity.findModule(event.storageAfter) val module = if (alreadyCreatedModule != null) { unloadedModules.remove(change.entity.name) alreadyCreatedModule.entityStorage = entityStore alreadyCreatedModule.diff = null alreadyCreatedModule } else { if (change.entity.name in unloadedModuleNames) { unloadedModules[change.entity.name] = UnloadedModuleDescriptionBridge.createDescription(change.entity) return } error("Module bridge should already be created") } if (project.isOpen) { fireModuleAddedInWriteAction(module) } } is EntityChange.Replaced -> { val oldId = change.oldEntity.symbolicId val newId = change.newEntity.symbolicId if (oldId != newId) { unloadedModules.remove(change.newEntity.name) val module = change.oldEntity.findModule(event.storageBefore) if (module != null) { module.rename(newId.name, getModuleVirtualFileUrl(change.newEntity), true) oldModuleNames[module] = oldId.name } } else if (getImlFileDirectory(change.oldEntity) != getImlFileDirectory(change.newEntity)) { val module = change.newEntity.findModule(event.storageBefore) val imlFilePath = getModuleVirtualFileUrl(change.newEntity) if (module != null && imlFilePath != null) { module.onImlFileMoved(imlFilePath) } } } } } private fun processModuleLibraryChange(change: EntityChange<LibraryEntity>, event: VersionedStorageChange) { when (change) { is EntityChange.Removed -> { val library = event.storageBefore.libraryMap.getDataByEntity(change.entity) if (library != null) { Disposer.dispose(library) } } is EntityChange.Replaced -> { val idBefore = change.oldEntity.symbolicId val idAfter = change.newEntity.symbolicId val newLibrary = event.storageAfter.libraryMap.getDataByEntity(change.newEntity) as LibraryBridgeImpl? if (newLibrary != null) { newLibrary.clearTargetBuilder() if (idBefore != idAfter) { newLibrary.entityId = idAfter } } } is EntityChange.Added -> { val tableId = change.entity.tableId as LibraryTableId.ModuleLibraryTableId val moduleEntity = entityStore.current.resolve(tableId.moduleId) ?: error("Could not find module for module library: ${change.entity.symbolicId}") if (moduleEntity.name !in unloadedModules) { val library = event.storageAfter.libraryMap.getDataByEntity(change.entity) if (library != null) { (library as LibraryBridgeImpl).entityStorage = entityStore library.clearTargetBuilder() } } } } } private fun List<EntityChange<LibraryEntity>>.filterModuleLibraryChanges() = filter { it.isModuleLibrary() } private fun fireModuleAddedInWriteAction(module: ModuleEx) { ApplicationManager.getApplication().runWriteAction { if (!module.isLoaded) { @Suppress("removal", "DEPRECATION") val oldComponents = mutableListOf<com.intellij.openapi.module.ModuleComponent>() module.moduleAdded(oldComponents) for (oldComponent in oldComponents) { @Suppress("DEPRECATION", "removal") oldComponent.moduleAdded() } fireModulesAdded(listOf(module)) } } } private fun fireModulesAdded(modules: List<Module>) { project.messageBus.syncPublisher(ProjectTopics.MODULES).modulesAdded(project, modules) } override fun registerNonPersistentModuleStore(module: ModuleBridge) { (module as ModuleBridgeImpl).registerService(serviceInterface = IComponentStore::class.java, implementation = NonPersistentModuleStore::class.java, pluginDescriptor = ComponentManagerImpl.fakeCorePluginDescriptor, override = true) } override fun loadModuleToBuilder(moduleName: String, filePath: String, diff: MutableEntityStorage): ModuleEntity { val builder = MutableEntityStorage.create() var errorMessage: String? = null JpsProjectEntitiesLoader.loadModule(Path.of(filePath), getJpsProjectConfigLocation(project)!!, builder, object : ErrorReporter { override fun reportError(message: String, file: VirtualFileUrl) { errorMessage = message } }, virtualFileManager) if (errorMessage != null) { throw IOException("Failed to load module from $filePath: $errorMessage") } diff.addDiff(builder) val moduleEntity = diff.entities(ModuleEntity::class.java).firstOrNull { it.name == moduleName } if (moduleEntity == null) { throw IOException("Failed to load module from $filePath") } val moduleFileUrl = getModuleVirtualFileUrl(moduleEntity)!! LocalFileSystem.getInstance().refreshAndFindFileByNioFile(moduleFileUrl.toPath()) return moduleEntity } override fun createModule(symbolicId: ModuleId, name: String, virtualFileUrl: VirtualFileUrl?, entityStorage: VersionedEntityStorage, diff: MutableEntityStorage?): ModuleBridge { return ModuleBridgeImpl(symbolicId, name, project, virtualFileUrl, entityStorage, diff) } companion object { private val LOG = logger<ModuleManagerComponentBridge>() private fun EntityChange<LibraryEntity>.isModuleLibrary(): Boolean { return when (this) { is EntityChange.Added -> entity.tableId is LibraryTableId.ModuleLibraryTableId is EntityChange.Removed -> entity.tableId is LibraryTableId.ModuleLibraryTableId is EntityChange.Replaced -> oldEntity.tableId is LibraryTableId.ModuleLibraryTableId } } } }
apache-2.0
3085c1f9afa79051d8e72e2f3e4f6bf2
44.68299
135
0.69952
5.342074
false
false
false
false
lice-lang/lice-repl
src/main/kotlin/org/lice/tools/Main.kt
2
1155
package org.lice.tools import org.apache.commons.cli.* import org.lice.core.SymbolList import org.lice.repl.Main.interpret import org.lice.tools.repl.GRepl import java.io.File /** * Created by glavo on 17-3-26. * * @author Glavo * @author ice1000 * @version 1.0.1 */ object Main { @Suppress("MemberVisibilityCanPrivate") @JvmStatic fun main(args: Array<String>) { if (args.isEmpty()) { GRepl(SymbolList(true)).runRepl() return@main } val opts = Options() opts.addOption("?", "help", false, "Print this usage message") val help = "lice [-options] [file]" val formatter = HelpFormatter() val parser = DefaultParser() try { val cl = DefaultParser().parse(opts, args) if (cl.hasOption("?")) { formatter.printHelp(help, opts) return@main } val arg = cl.args when { arg.isEmpty() -> GRepl(SymbolList(true)).runRepl() args.size > 1 -> throw Exception() else -> interpret(File(arg[0]).apply { if (!exists()) { System.err.println("file not found: ${arg[0]}") return@main } }) } } catch (t: Throwable) { formatter.printHelp(help, "", opts, "") } } }
gpl-3.0
ff5bbd613a1bbdc36ea7e944eceeb60c
17.95082
64
0.62684
3.047493
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/filter/JvmDebuggerAddFilterStartupActivity.kt
3
1832
// 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.filter import com.intellij.debugger.settings.DebuggerSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.ui.classFilter.ClassFilter private const val KOTLIN_STDLIB_FILTER = "kotlin.*" private const val COMPOSE_RUNTIME_FILTER = "androidx.compose.runtime.*" class JvmDebuggerAddFilterStartupActivity : StartupActivity.DumbAware { override fun runActivity(project: Project) { val settings = DebuggerSettings.getInstance() ?: return settings.addSteppingFilterIfNeeded(KOTLIN_STDLIB_FILTER) settings.addSteppingFilterIfNeeded(COMPOSE_RUNTIME_FILTER) } } private fun DebuggerSettings.addSteppingFilterIfNeeded(pattern: String) { val steppingFilters = this.steppingFilters when (val occurrencesNum = steppingFilters.count { it.pattern == pattern }) { 0 -> setSteppingFilters(steppingFilters + ClassFilter(pattern)) 1 -> return else -> leaveOnlyFirstOccurenceOfSteppingFilter(pattern, occurrencesNum) } } private fun DebuggerSettings.leaveOnlyFirstOccurenceOfSteppingFilter(pattern: String, occurrencesNum: Int) { val steppingFilters = this.steppingFilters val newFilters = ArrayList<ClassFilter>(steppingFilters.size - occurrencesNum + 1) var firstOccurrenceFound = false for (filter in steppingFilters) { if (filter.pattern == pattern) { if (!firstOccurrenceFound) { newFilters.add(filter) firstOccurrenceFound = true } } else { newFilters.add(filter) } } setSteppingFilters(newFilters.toTypedArray()) }
apache-2.0
0e53ee01579024dd30358e1d9369ff4e
37.978723
120
0.732533
4.490196
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonScanningStatistics.kt
1
1434
// 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.util.indexing.diagnostic.dto import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePath @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class JsonScanningStatistics( val providerName: String = "", val numberOfScannedFiles: Int = 0, val numberOfSkippedFiles: Int = 0, val numberOfFilesForIndexing: Int = 0, val numberOfFilesFullyIndexedByInfrastructureExtensions: Int = 0, val scanningTime: JsonDuration = JsonDuration(0), val timeProcessingUpToDateFiles: JsonDuration = JsonDuration(0), val timeUpdatingContentLessIndexes: JsonDuration = JsonDuration(0), val timeIndexingWithoutContent: JsonDuration = JsonDuration(0), // Available only if [com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles] is enabled. val scannedFiles: List<JsonScannedFile>? = null ) { @JsonIgnoreProperties(ignoreUnknown = true) data class JsonScannedFile( val path: PortableFilePath, val isUpToDate: Boolean, @JsonProperty("wfibe") val wasFullyIndexedByInfrastructureExtension: Boolean ) }
apache-2.0
7f6356098404e9bc17b058179dbc705c
43.84375
140
0.804742
4.58147
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/safeCall/changeThisSafeCallWithValue2Runtime.kt
4
303
// "Replace with 's.filter { it != c }'" "true" // WITH_RUNTIME class X { @Deprecated("", ReplaceWith("s.filter { it != c }")) fun oldFun(s: String): CharSequence = s.filter { it != c } val c = 'x' } fun foo(x: X?, s: String) { bar(x?.<caret>oldFun(s)) } fun bar(s: CharSequence?){}
apache-2.0
cb6927ebf883107d9e043a890ed7e00a
19.2
62
0.547855
2.858491
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/network/ovs/sw/remove/RemoveOvsSwitchExecutor.kt
2
994
package com.github.kerubistan.kerub.planner.steps.network.ovs.sw.remove import com.github.kerubistan.kerub.data.config.HostConfigurationDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor import com.github.kerubistan.kerub.utils.junix.ovs.Vsctl class RemoveOvsSwitchExecutor( private val hostCommandExecutor: HostCommandExecutor, private val hostConfigurationDao: HostConfigurationDao ) : AbstractStepExecutor<RemoveOvsSwitch, Unit>() { override fun perform(step: RemoveOvsSwitch) = hostCommandExecutor.execute(step.host) { session -> Vsctl.removeBridge(session, bridgeName = step.virtualNetwork.idStr) } override fun update(step: RemoveOvsSwitch, updates: Unit) = hostConfigurationDao.update(step.host.id) { hostConfig -> hostConfig.copy( networkConfiguration = hostConfig.networkConfiguration .filterNot { it.virtualNetworkId == step.virtualNetwork.id } ) } }
apache-2.0
8a67cb0e342dca6a93310c50dd5211c8
40.458333
73
0.796781
4.158996
false
true
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/LookupElementSink.kt
1
4507
// 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.completion import com.intellij.codeInsight.completion.CompletionInitializationContext import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.openapi.editor.Document import com.intellij.psi.util.elementType import org.jetbrains.kotlin.idea.completion.stringTemplates.InsertStringTemplateBracesLookupElementDecorator import org.jetbrains.kotlin.idea.completion.weighers.CompletionContributorGroupWeigher.groupPriority import org.jetbrains.kotlin.idea.core.canDropBraces import org.jetbrains.kotlin.idea.core.dropBraces import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtSimpleNameStringTemplateEntry import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression internal class LookupElementSink( private val resultSet: CompletionResultSet, private val parameters: KotlinFirCompletionParameters, private val groupPriority: Int = 0, ) { fun withPriority(priority: Int): LookupElementSink = LookupElementSink(resultSet, parameters, priority) fun addElement(element: LookupElement) { element.groupPriority = groupPriority resultSet.addElement(applyWrappersToLookupElement(element)) } fun addAllElements(elements: Iterable<LookupElement>) { elements.forEach { it.groupPriority = groupPriority } resultSet.addAllElements(elements.map(::applyWrappersToLookupElement)) } private fun applyWrappersToLookupElement(lookupElement: LookupElement): LookupElement { val wrappers = WrappersProvider.getWrapperForLookupElement(parameters) return wrappers.wrap(lookupElement) } } private object WrappersProvider { fun getWrapperForLookupElement(parameters: KotlinFirCompletionParameters): List<LookupElementWrapper> { return when (parameters.type) { KotlinFirCompletionParameters.CorrectionType.BRACES_FOR_STRING_TEMPLATE -> { listOf(LookupElementWrapper(::InsertStringTemplateBracesLookupElementDecorator)) } else -> listOf(LookupElementWrapper(::WrapSingleStringTemplateEntryWithBraces)) } } } private class WrapSingleStringTemplateEntryWithBraces(lookupElement: LookupElement) : LookupElementDecorator<LookupElement>(lookupElement) { override fun handleInsert(context: InsertionContext) { val document = context.document context.commitDocument() if (needInsertBraces(context)) { insertBraces(context, document) context.commitDocument() super.handleInsert(context) removeUnneededBraces(context) context.commitDocument() } else { super.handleInsert(context) } } private fun insertBraces(context: InsertionContext, document: Document) { val startOffset = context.startOffset document.insertString(context.startOffset, "{") context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, startOffset + 1) val tailOffset = context.tailOffset document.insertString(tailOffset, "}") context.tailOffset = tailOffset } private fun removeUnneededBraces(context: InsertionContext) { val templateEntry = getContainingTemplateEntry(context) as? KtBlockStringTemplateEntry ?: return if (templateEntry.canDropBraces()) { templateEntry.dropBraces() } } private fun needInsertBraces(context: InsertionContext): Boolean = getContainingTemplateEntry(context) is KtSimpleNameStringTemplateEntry private fun getContainingTemplateEntry(context: InsertionContext): KtStringTemplateEntryWithExpression? { val file = context.file val element = file.findElementAt(context.startOffset) ?: return null if (element.elementType != KtTokens.IDENTIFIER) return null val identifier = element.parent as? KtNameReferenceExpression ?: return null return identifier.parent as? KtStringTemplateEntryWithExpression } }
apache-2.0
aa482f122beadb25e70979130bacb486
41.528302
158
0.759041
5.423586
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectModelSynchronizer.kt
1
15443
// 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.workspaceModel.ide.impl.jps.serialization import com.intellij.configurationStore.StoreReloadManager import com.intellij.configurationStore.isFireStorageFileChangedEvent import com.intellij.diagnostic.Activity import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer.startActivity import com.intellij.ide.highlighter.ModuleFileType import com.intellij.ide.highlighter.ProjectFileType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ProjectLoadingErrorsNotifier import com.intellij.openapi.module.impl.ModuleManagerEx import com.intellij.openapi.project.ExternalStorageConfigurationManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.getExternalConfigurationDir import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.project.stateStore import com.intellij.util.PlatformUtils import com.intellij.workspaceModel.ide.* import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.ide.impl.WorkspaceModelInitialTestContent import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.util.JpsPathUtil import java.util.* import java.util.concurrent.atomic.AtomicReference /** * Manages serialization and deserialization from JPS format (*.iml and *.ipr files, .idea directory) for workspace model in IDE. */ class JpsProjectModelSynchronizer(private val project: Project) : Disposable { private val incomingChanges = Collections.synchronizedList(ArrayList<JpsConfigurationFilesChange>()) private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private lateinit var fileContentReader: JpsFileContentReaderWithCache private val serializers = AtomicReference<JpsProjectSerializers?>() private val sourcesToSave = Collections.synchronizedSet(HashSet<EntitySource>()) private var activity: Activity? = null private var childActivity: Activity? = null fun needToReloadProjectEntities(): Boolean { if (StoreReloadManager.getInstance().isReloadBlocked()) return false if (serializers.get() == null) return false synchronized(incomingChanges) { return incomingChanges.isNotEmpty() } } fun reloadProjectEntities() { if (StoreReloadManager.getInstance().isReloadBlocked()) { LOG.debug("Skip reloading because it's blocked") return } val serializers = serializers.get() if (serializers == null) { LOG.debug("Skip reloading because initial loading wasn't performed yet") return } val changes = getAndResetIncomingChanges() if (changes == null) { LOG.debug("Skip reloading because there are no changed files") return } LOG.debug { "Reload entities from changed files:\n$changes" } val (changedSources, builder) = loadAndReportErrors { serializers.reloadFromChangedFiles(changes, fileContentReader, it) } fileContentReader.clearCache() LOG.debugValues("Changed entity sources", changedSources) if (changedSources.isEmpty() && builder.isEmpty()) return ApplicationManager.getApplication().invokeAndWait(Runnable { runWriteAction { WorkspaceModel.getInstance(project).updateProjectModel { updater -> val storage = builder.toStorage() updater.replaceBySource({ it in changedSources || (it is JpsImportedEntitySource && !it.storedExternally && it.internalFile in changedSources) || it is DummyParentEntitySource }, storage) runAutomaticModuleUnloader(updater) } sourcesToSave.removeAll(changedSources) } }) } private fun <T> loadAndReportErrors(action: (ErrorReporter) -> T): T { val reporter = IdeErrorReporter(project) val result = action(reporter) val errors = reporter.errors if (errors.isNotEmpty()) { ProjectLoadingErrorsNotifier.getInstance(project).registerErrors(errors) } return result } private fun registerListener() { fun isParentOfStorageFiles(dir: VirtualFile): Boolean { if (dir.name == Project.DIRECTORY_STORE_FOLDER) return true val grandParent = dir.parent return grandParent != null && grandParent.name == Project.DIRECTORY_STORE_FOLDER } fun isStorageFile(file: VirtualFile): Boolean { val fileName = file.name if ((FileUtilRt.extensionEquals(fileName, ModuleFileType.DEFAULT_EXTENSION) || FileUtilRt.extensionEquals(fileName, ProjectFileType.DEFAULT_EXTENSION)) && !file.isDirectory) return true val parent = file.parent return parent != null && isParentOfStorageFiles(parent) } ApplicationManager.getApplication().messageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { //todo support move/rename //todo optimize: filter events before creating lists val addedUrls = ArrayList<String>() val removedUrls = ArrayList<String>() val changedUrls = ArrayList<String>() //JPS model is loaded from *.iml files, files in .idea directory (modules.xml), files from directories in .idea (libraries) and *.ipr file // so we can ignore all other events to speed up processing for (event in events) { if (isFireStorageFileChangedEvent(event)) { when (event) { is VFileCreateEvent -> { val fileName = event.childName if (FileUtilRt.extensionEquals(fileName, ModuleFileType.DEFAULT_EXTENSION) && !event.isDirectory || isParentOfStorageFiles(event.parent) && !event.isEmptyDirectory) { addedUrls.add(JpsPathUtil.pathToUrl(event.path)) } } is VFileDeleteEvent -> { if (isStorageFile(event.file)) { removedUrls.add(JpsPathUtil.pathToUrl(event.path)) } } is VFileContentChangeEvent -> { if (isStorageFile(event.file)) { changedUrls.add(JpsPathUtil.pathToUrl(event.path)) } } } } } if (addedUrls.isNotEmpty() || removedUrls.isNotEmpty() || changedUrls.isNotEmpty()) { val change = JpsConfigurationFilesChange(addedUrls, removedUrls, changedUrls) incomingChanges.add(change) StoreReloadManager.getInstance().scheduleProcessingChangedFiles() } } }) WorkspaceModelTopics.getInstance(project).subscribeImmediately(project.messageBus.connect(), object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { LOG.debug("Marking changed entities for save") event.getAllChanges().forEach { when (it) { is EntityChange.Added -> sourcesToSave.add(it.entity.entitySource) is EntityChange.Removed -> sourcesToSave.add(it.entity.entitySource) is EntityChange.Replaced -> { sourcesToSave.add(it.oldEntity.entitySource) sourcesToSave.add(it.newEntity.entitySource) } } } } }) } fun loadProjectToEmptyStorage(project: Project): Pair<WorkspaceEntityStorage, List<EntitySource>>? { val configLocation: JpsProjectConfigLocation = getJpsProjectConfigLocation(project)!! LOG.debug { "Initial loading of project located at $configLocation" } activity = startActivity("project files loading", ActivityCategory.DEFAULT) childActivity = activity?.startChild("serializers creation") val serializers = prepareSerializers() registerListener() val builder = WorkspaceEntityStorageBuilder.create() if (!WorkspaceModelInitialTestContent.hasInitialContent) { childActivity = childActivity?.endAndStart("loading entities from files") val sourcesToUpdate = loadAndReportErrors { serializers.loadAll(fileContentReader, builder, it, project) } (WorkspaceModel.getInstance(project) as? WorkspaceModelImpl)?.entityTracer?.printInfoAboutTracedEntity(builder, "JPS files") childActivity = childActivity?.endAndStart("applying loaded changes (in queue)") return builder.toStorage() to sourcesToUpdate } else { childActivity?.end() childActivity = null activity?.end() activity = null return null } } fun applyLoadedStorage(storeToEntitySources: Pair<WorkspaceEntityStorage, List<EntitySource>>?) { if (storeToEntitySources == null) return WriteAction.runAndWait<RuntimeException> { if (project.isDisposed) return@runAndWait childActivity = childActivity?.endAndStart("applying loaded changes") WorkspaceModel.getInstance(project).updateProjectModel { updater -> updater.replaceBySource({ it is JpsFileEntitySource || it is JpsFileDependentEntitySource || it is CustomModuleEntitySource || it is DummyParentEntitySource }, storeToEntitySources.first) childActivity = childActivity?.endAndStart("unloaded modules loading") runAutomaticModuleUnloader(updater) } childActivity?.end() childActivity = null } sourcesToSave.clear() sourcesToSave.addAll(storeToEntitySources.second) fileContentReader.clearCache() activity?.end() activity = null } fun loadProject(project: Project): Unit = applyLoadedStorage(loadProjectToEmptyStorage(project)) private fun runAutomaticModuleUnloader(storage: WorkspaceEntityStorage) { ModuleManagerEx.getInstanceEx(project).unloadNewlyAddedModulesIfPossible(storage) } // FIXME: 21.01.2021 This is a fix for OC-21192 // We do disable delayed loading of JPS model if modules.xml file missing (what happens because of bug if you open a project in 2020.3) fun blockCidrDelayedUpdate(): Boolean { if (!PlatformUtils.isCidr()) return false val currentSerializers = prepareSerializers() as JpsProjectSerializersImpl if (currentSerializers.moduleSerializers.isNotEmpty()) return false return currentSerializers.moduleListSerializersByUrl.keys.all { !JpsPathUtil.urlToFile(it).exists() } } private fun prepareSerializers(): JpsProjectSerializers { val existingSerializers = this.serializers.get() if (existingSerializers != null) return existingSerializers val serializers = createSerializers() this.serializers.set(serializers) return serializers } private fun createSerializers(): JpsProjectSerializers { val configLocation: JpsProjectConfigLocation = getJpsProjectConfigLocation(project)!! fileContentReader = (project.stateStore as ProjectStoreWithJpsContentReader).createContentReader() val externalStoragePath = project.getExternalConfigurationDir() //TODO:: Get rid of dependency on ExternalStorageConfigurationManager in order to use in build process val externalStorageConfigurationManager = ExternalStorageConfigurationManager.getInstance(project) val fileInDirectorySourceNames = FileInDirectorySourceNames.from(WorkspaceModel.getInstance(project).entityStorage.current) return JpsProjectEntitiesLoader.createProjectSerializers(configLocation, fileContentReader, externalStoragePath, WorkspaceModel.enabledForArtifacts, virtualFileManager, externalStorageConfigurationManager, fileInDirectorySourceNames) } fun saveChangedProjectEntities(writer: JpsFileContentWriter) { LOG.debug("Saving project entities") val data = serializers.get() if (data == null) { LOG.debug("Skipping save because initial loading wasn't performed") return } val storage = WorkspaceModel.getInstance(project).entityStorage.current val affectedSources = synchronized(sourcesToSave) { val copy = HashSet(sourcesToSave) sourcesToSave.clear() copy } LOG.debugValues("Saving affected entities", affectedSources) data.saveEntities(storage, affectedSources, writer) } fun convertToDirectoryBasedFormat() { val newSerializers = createSerializers() WorkspaceModel.getInstance(project).updateProjectModel { newSerializers.changeEntitySourcesToDirectoryBasedFormat(it) } val moduleSources = WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java).map { it.entitySource } synchronized(sourcesToSave) { //to trigger save for modules.xml sourcesToSave.addAll(moduleSources) } serializers.set(newSerializers) } @TestOnly fun markAllEntitiesAsDirty() { val allSources = WorkspaceModel.getInstance(project).entityStorage.current.entitiesBySource { true }.keys synchronized(sourcesToSave) { sourcesToSave.addAll(allSources) } } private fun getAndResetIncomingChanges(): JpsConfigurationFilesChange? { synchronized(incomingChanges) { if (incomingChanges.isEmpty()) return null val combinedChanges = combineChanges() incomingChanges.clear() return combinedChanges } } private fun combineChanges(): JpsConfigurationFilesChange { val singleChange = incomingChanges.singleOrNull() if (singleChange != null) { return singleChange } val allAdded = LinkedHashSet<String>() val allRemoved = LinkedHashSet<String>() val allChanged = LinkedHashSet<String>() for (change in incomingChanges) { allChanged.addAll(change.changedFileUrls) for (addedUrl in change.addedFileUrls) { if (allRemoved.remove(addedUrl)) { allChanged.add(addedUrl) } else { allAdded.add(addedUrl) } } for (removedUrl in change.removedFileUrls) { allChanged.remove(removedUrl) if (!allAdded.remove(removedUrl)) { allRemoved.add(removedUrl) } } } return JpsConfigurationFilesChange(allAdded, allRemoved, allChanged) } override fun dispose() { } @TestOnly fun getSerializers(): JpsProjectSerializersImpl = serializers.get() as JpsProjectSerializersImpl companion object { fun getInstance(project: Project): JpsProjectModelSynchronizer? = project.getComponent(JpsProjectModelSynchronizer::class.java) private val LOG = logger<JpsProjectModelSynchronizer>() } }
apache-2.0
66c3cf05b853630b9e9e0d21c26d22e5
42.747875
152
0.725507
5.35286
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/StubBasedPackageMemberDeclarationProvider.kt
1
4757
// 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.stubindex.resolve import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.indexing.FileBasedIndex import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.vfilefinder.KotlinPackageSourcesMemberNamesIndex import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.safeNameForLazyResolve import org.jetbrains.kotlin.resolve.lazy.data.KtClassInfoUtil import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import java.util.* class StubBasedPackageMemberDeclarationProvider( private val fqName: FqName, private val project: Project, private val searchScope: GlobalSearchScope ) : PackageMemberDeclarationProvider { override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List<KtDeclaration> { val fqNameAsString = fqName.asString() val result = ArrayList<KtDeclaration>() fun addFromIndex(index: AbstractStringStubIndexExtension<out KtNamedDeclaration>) { index.processElements(fqNameAsString, project, searchScope) { if (nameFilter(it.nameAsSafeName)) { result.add(it) } true } } if (kindFilter.acceptsKinds(DescriptorKindFilter.CLASSIFIERS_MASK)) { addFromIndex(KotlinTopLevelClassByPackageIndex.getInstance()) addFromIndex(KotlinTopLevelTypeAliasByPackageIndex.getInstance()) } if (kindFilter.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) { addFromIndex(KotlinTopLevelFunctionByPackageIndex.getInstance()) } if (kindFilter.acceptsKinds(DescriptorKindFilter.VARIABLES_MASK)) { addFromIndex(KotlinTopLevelPropertyByPackageIndex.getInstance()) } return result } private val declarationNames_: Set<Name> by lazy(LazyThreadSafetyMode.PUBLICATION) { FileBasedIndex.getInstance() .getValues(KotlinPackageSourcesMemberNamesIndex.KEY, fqName.asString(), searchScope) .flatMapTo(hashSetOf()) { it.map { stringName -> Name.identifier(stringName).safeNameForLazyResolve() } } } override fun getDeclarationNames() = declarationNames_ override fun getClassOrObjectDeclarations(name: Name): Collection<KtClassOrObjectInfo<*>> = runReadAction { KotlinFullClassNameIndex.getInstance().get(childName(name), project, searchScope) .map { KtClassInfoUtil.createClassOrObjectInfo(it) } } override fun getScriptDeclarations(name: Name): Collection<KtScriptInfo> = runReadAction { KotlinScriptFqnIndex.instance.get(childName(name), project, searchScope) .map(::KtScriptInfo) } override fun getFunctionDeclarations(name: Name): Collection<KtNamedFunction> { return runReadAction { KotlinTopLevelFunctionFqnNameIndex.getInstance().get(childName(name), project, searchScope) } } override fun getPropertyDeclarations(name: Name): Collection<KtProperty> { return runReadAction { KotlinTopLevelPropertyFqnNameIndex.getInstance().get(childName(name), project, searchScope) } } override fun getDestructuringDeclarationsEntries(name: Name): Collection<KtDestructuringDeclarationEntry> { return emptyList() } override fun getAllDeclaredSubPackages(nameFilter: (Name) -> Boolean): Collection<FqName> { return PackageIndexUtil.getSubPackageFqNames(fqName, searchScope, project, nameFilter) } override fun getPackageFiles(): Collection<KtFile> { return PackageIndexUtil.findFilesWithExactPackage(fqName, searchScope, project) } override fun containsFile(file: KtFile): Boolean { return searchScope.contains(file.virtualFile ?: return false) } override fun getTypeAliasDeclarations(name: Name): Collection<KtTypeAlias> { return KotlinTopLevelTypeAliasFqNameIndex.getInstance().get(childName(name), project, searchScope) } private fun childName(name: Name): String { return fqName.child(name.safeNameForLazyResolve()).asString() } }
apache-2.0
cdfbeeb9bc161015599ac6ae02b58e8f
41.097345
158
0.734497
5.104077
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/tests/git4idea/log/VcsLogDataExtensions.kt
3
2371
// 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 git4idea.log import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.data.DataPackChangeListener import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.index.VcsLogIndex import com.intellij.vcs.log.impl.FatalErrorHandler import git4idea.repo.GitRepository import junit.framework.TestCase.fail import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit private val LOG = Logger.getInstance("Git.Test.LogData.Extensions") internal fun createLogData(repo: GitRepository, logProvider: GitLogProvider, disposable: Disposable): VcsLogData { return VcsLogData(repo.project, mapOf(repo.root to logProvider), object : FatalErrorHandler { override fun consume(source: Any?, throwable: Throwable) { LOG.error(throwable) } override fun displayFatalErrorMessage(message: String) { LOG.error(message) } }, disposable) } internal fun VcsLogData.refreshAndWait(repo: GitRepository, waitIndexFinishing: Boolean) { val logWaiter = CompletableFuture<VcsLogData>() val dataPackChangeListener = DataPackChangeListener { newDataPack -> if (newDataPack.isFull) { logWaiter.complete(this) } } addDataPackChangeListener(dataPackChangeListener) refresh(listOf(repo.root)) try { logWaiter.get(5, TimeUnit.SECONDS) if (waitIndexFinishing) { waitIndexFinishing(repo) } } catch (e: Exception) { fail(e.message) } finally { removeDataPackChangeListener(dataPackChangeListener) } } private fun VcsLogData.waitIndexFinishing(repo: GitRepository) { val indexWaiter = CompletableFuture<VirtualFile>() val repositoryRoot = repo.root val indexFinishedListener = VcsLogIndex.IndexingFinishedListener { root -> if (repositoryRoot == root) { indexWaiter.complete(root) } } index.addListener(indexFinishedListener) try { if (index.isIndexed(repositoryRoot)) { indexWaiter.complete(repositoryRoot) } indexWaiter.get(5, TimeUnit.SECONDS) } catch (e: Exception) { fail(e.message) } finally { index.removeListener(indexFinishedListener) } }
apache-2.0
8291259659605670ef2b0beefa0ecbe3
31.054054
158
0.757908
4.174296
false
false
false
false
sksamuel/ktest
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/isolation/test/AfterTestExceptionTest.kt
1
4745
package com.sksamuel.kotest.specs.isolation.test import io.kotest.engine.spec.SpecExecutor import io.kotest.engine.listener.TestEngineListener import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.* import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.core.test.TestStatus import io.kotest.matchers.throwable.shouldHaveMessage import io.kotest.matchers.types.shouldBeInstanceOf private class BehaviorSpecWithAfterTestError : BehaviorSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } given("given") { When("when") { then("then") { } } } }) private class FunSpecWithAfterTestError : FunSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } test("fun spec") {} }) private class StringSpecWithAfterTestError : StringSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } "string test"{} }) private class ShouldSpecWithAfterTestError : ShouldSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } should("foo") {} }) private class DescribeSpecWithAfterTestError : DescribeSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } }) private class FeatureSpecWithAfterTestError : FeatureSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } feature("feature") { scenario("scenario") { } } }) private class ExpectSpecWithAfterTestError : ExpectSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } }) private class FreeSpecWithAfterTestError : FreeSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } "test" {} }) private class WordSpecWithAfterTestError : WordSpec({ isolationMode = IsolationMode.InstancePerTest afterTest { error("boom") } "this test" should { "be alive" {} } }) class AfterTestExceptionTest : WordSpec({ var error: Throwable? = null val listener = object : TestEngineListener { override fun testFinished(testCase: TestCase, result: TestResult) { if (result.status == TestStatus.Error) error = result.error } } "an exception in before test" should { "fail the test for behavior spec" { val executor = SpecExecutor(listener) executor.execute(BehaviorSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for feature spec" { val executor = SpecExecutor(listener) executor.execute(FeatureSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for word spec" { val executor = SpecExecutor(listener) executor.execute(WordSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for should spec" { val executor = SpecExecutor(listener) executor.execute(ShouldSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for string spec" { val executor = SpecExecutor(listener) executor.execute(StringSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for describe spec" { val executor = SpecExecutor(listener) executor.execute(DescribeSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for free spec" { val executor = SpecExecutor(listener) executor.execute(FreeSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for fun spec" { val executor = SpecExecutor(listener) executor.execute(FunSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } "fail the test for expect spec" { val executor = SpecExecutor(listener) executor.execute(ExpectSpecWithAfterTestError::class) error.shouldBeInstanceOf<IllegalStateException>() error!!.shouldHaveMessage("boom") } } })
mit
343ae6cb960d9d1c133794f7a464008d
28.842767
73
0.68156
4.968586
false
true
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/ui/helpers/QuranPageAdapter.kt
2
4321
package com.quran.labs.androidquran.ui.helpers import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.quran.data.core.QuranInfo import com.quran.labs.androidquran.data.Constants import com.quran.labs.androidquran.ui.fragment.QuranPageFragment import com.quran.labs.androidquran.ui.fragment.TabletFragment import com.quran.labs.androidquran.ui.fragment.TranslationFragment import com.quran.page.common.data.PageMode import com.quran.page.common.factory.PageViewFactory import timber.log.Timber class QuranPageAdapter( fm: FragmentManager?, private val isDualPages: Boolean, var isShowingTranslation: Boolean, private val quranInfo: QuranInfo, private val isSplitScreen: Boolean, private val pageViewFactory: PageViewFactory? = null ) : FragmentStatePagerAdapter(fm, if (isDualPages) "dualPages" else "singlePage") { private var pageMode: PageMode = makePageMode() private val totalPages: Int = quranInfo.numberOfPages private val totalPagesDual: Int = totalPages / 2 fun setTranslationMode() { if (!isShowingTranslation) { isShowingTranslation = true pageMode = makePageMode() notifyDataSetChanged() } } fun setQuranMode() { if (isShowingTranslation) { isShowingTranslation = false pageMode = makePageMode() notifyDataSetChanged() } } private fun makePageMode(): PageMode { return if (isDualPages) { if (isShowingTranslation && isSplitScreen) { PageMode.DualScreenMode.Mix } else if (isShowingTranslation) { PageMode.DualScreenMode.Translation } else { PageMode.DualScreenMode.Arabic } } else { if (isShowingTranslation) { PageMode.SingleTranslationPage } else { PageMode.SingleArabicPage } } } override fun getItemPosition(currentItem: Any): Int { /** when the ViewPager gets a notifyDataSetChanged (or invalidated), * it goes through its set of saved views and runs this method on * each one to figure out whether or not it should remove the view * or not. the default implementation returns POSITION_UNCHANGED, * which means that "this page is as is." * * as noted in http://stackoverflow.com/questions/7263291 in one * of the answers, if you're just updating your view (changing a * field's value, etc), this is highly inefficient (because you * recreate the view for nothing). * * in our case, however, this is the right thing to do since we * change the fragment completely when we notifyDataSetChanged. */ return POSITION_NONE } override fun getCount(): Int { return if (isDualPagesVisible) { totalPagesDual } else { totalPages } } override fun getItem(position: Int): Fragment { val page = quranInfo.getPageFromPosition(position, isDualPagesVisible) Timber.d("getting page: %d, from position %d", page, position) return pageViewFactory?.providePage(page, pageMode) ?: when { isDualPages -> { TabletFragment.newInstance( page, if (isShowingTranslation) TabletFragment.Mode.TRANSLATION else TabletFragment.Mode.ARABIC, isSplitScreen ) } isShowingTranslation -> { TranslationFragment.newInstance(page) } else -> { QuranPageFragment.newInstance(page) } } } override fun destroyItem(container: ViewGroup, position: Int, currentItem: Any) { val f = currentItem as Fragment Timber.d("destroying item: %d, %s", position, f) cleanupFragment(f) super.destroyItem(container, position, currentItem) } override fun cleanupFragment(f: Fragment) { if (f is QuranPageFragment) { f.cleanup() } else if (f is TabletFragment) { f.cleanup() } } fun getFragmentIfExistsForPage(page: Int): QuranPage? { if (page < Constants.PAGES_FIRST || totalPages < page) { return null } val position = quranInfo.getPositionFromPage(page, isDualPagesVisible) val fragment = getFragmentIfExists(position) return if (fragment is QuranPage && fragment.isAdded) fragment else null } private val isDualPagesVisible: Boolean get() = isDualPages && !(isSplitScreen && isShowingTranslation) }
gpl-3.0
9d1afc3bd1f7a8d3fac69b6c5eaba034
31.488722
100
0.700069
4.364646
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/application/misc/SearchSuggestionsAdapter.kt
2
2869
package nl.rsdt.japp.application.misc import android.content.Context import android.database.AbstractCursor import android.database.Cursor import android.text.TextUtils import androidx.cursoradapter.widget.SimpleCursorAdapter import nl.rsdt.japp.jotial.maps.searching.Searchable import java.util.* /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 25-7-2016 * Description... */ class SearchSuggestionsAdapter(context: Context, private val searchable: Searchable) : SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, null, mVisible, mViewIds, 0) { override fun runQueryOnBackgroundThread(constraint: CharSequence): Cursor { return SuggestionsCursor(constraint, searchable) } class SuggestionsCursor(constraint: CharSequence, searchable: Searchable) : AbstractCursor() { private val entries: MutableList<String> fun getEntries(): List<String> { return entries } init { entries = searchable.provide() if (!TextUtils.isEmpty(constraint)) { val constraintString = constraint.toString().toLowerCase(Locale.ROOT) val iter = entries.iterator() while (iter.hasNext()) { val value = iter.next() if (!value.toLowerCase(Locale.ROOT).startsWith(constraintString)) { iter.remove() } } } } override fun getCount(): Int { return entries.size } override fun getColumnNames(): Array<String> { return mFields } override fun getLong(column: Int): Long { if (column == 0) { return mPos.toLong() } throw UnsupportedOperationException("unimplemented") } override fun getString(column: Int): String { if (column == 1) { return entries[mPos] } throw UnsupportedOperationException("unimplemented") } override fun getShort(column: Int): Short { throw UnsupportedOperationException("unimplemented") } override fun getInt(column: Int): Int { throw UnsupportedOperationException("unimplemented") } override fun getFloat(column: Int): Float { throw UnsupportedOperationException("unimplemented") } override fun getDouble(column: Int): Double { throw UnsupportedOperationException("unimplemented") } override fun isNull(column: Int): Boolean { return false } } companion object { private val mFields = arrayOf("_id", "result") private val mVisible = arrayOf("result") private val mViewIds = intArrayOf(android.R.id.text1) } }
apache-2.0
8f662b6bf868ef78ab1b8ad1afd7a572
28.57732
183
0.604392
5.244973
false
false
false
false
FrontierRobotics/i2c-api
src/main/kotlin/io/frontierrobotics/i2c/I2CDevice.kt
1
621
package io.frontierrobotics.i2c data class I2CDevice(val busAddress: I2CAddress, val internalAddress: I2CAddress? = null) { constructor(busAddress: Int, internalAddress: Int? = null) : this(busAddress.toI2CAddress(), internalAddress?.toI2CAddress()) fun isValid() = busAddress.isValid() && (internalAddress?.isValid() ?: true) override fun toString(): String { if (internalAddress == null) { return "I2CDevice(busAddress=$busAddress)" } else { return "I2CDevice(busAddress=$busAddress, internalAddress=$internalAddress)" } } }
mit
7775d5b25c5d6a1b9589caa123786242
30.1
129
0.648953
3.833333
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/sceVaudio.kt
1
1767
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.hle.* @Suppress("UNUSED_PARAMETER") class sceVaudio(emulator: Emulator) : SceModule(emulator, "sceVaudio", 0x40010011, "vaudio.prx", "sceVaudio_driver") { fun sceVaudioChReserve(cpu: CpuState): Unit = UNIMPLEMENTED(0x03B6807D) fun sceVaudio_27ACC20B(cpu: CpuState): Unit = UNIMPLEMENTED(0x27ACC20B) fun sceVaudio_346FBE94(cpu: CpuState): Unit = UNIMPLEMENTED(0x346FBE94) fun sceVaudio_504E4745(cpu: CpuState): Unit = UNIMPLEMENTED(0x504E4745) fun sceVaudioChRelease(cpu: CpuState): Unit = UNIMPLEMENTED(0x67585DFD) fun sceVaudioOutputBlocking(cpu: CpuState): Unit = UNIMPLEMENTED(0x8986295E) fun sceVaudio_CBD4AC51(cpu: CpuState): Unit = UNIMPLEMENTED(0xCBD4AC51) fun sceVaudio_E8E78DC8(cpu: CpuState): Unit = UNIMPLEMENTED(0xE8E78DC8) override fun registerModule() { registerFunctionRaw("sceVaudioChReserve", 0x03B6807D, since = 150) { sceVaudioChReserve(it) } registerFunctionRaw("sceVaudio_27ACC20B", 0x27ACC20B, since = 150) { sceVaudio_27ACC20B(it) } registerFunctionRaw("sceVaudio_346FBE94", 0x346FBE94, since = 150) { sceVaudio_346FBE94(it) } registerFunctionRaw("sceVaudio_504E4745", 0x504E4745, since = 150) { sceVaudio_504E4745(it) } registerFunctionRaw("sceVaudioChRelease", 0x67585DFD, since = 150) { sceVaudioChRelease(it) } registerFunctionRaw("sceVaudioOutputBlocking", 0x8986295E, since = 150) { sceVaudioOutputBlocking(it) } registerFunctionRaw("sceVaudio_CBD4AC51", 0xCBD4AC51, since = 150) { sceVaudio_CBD4AC51(it) } registerFunctionRaw("sceVaudio_E8E78DC8", 0xE8E78DC8, since = 150) { sceVaudio_E8E78DC8(it) } } }
mit
987abb7c9fd95a811d65f70178e6612d
59.931034
118
0.744199
3.057093
false
false
false
false
dtretyakov/teamcity-rust
plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/cargo/YankArgumentsProvider.kt
1
1961
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust.cargo import jetbrains.buildServer.agent.BuildRunnerContext import jetbrains.buildServer.rust.ArgumentsProvider import jetbrains.buildServer.rust.CargoConstants import java.util.* /** * Provides arguments to cargo yank command. */ class YankArgumentsProvider : ArgumentsProvider { override fun getArguments(runnerContext: BuildRunnerContext): List<String> { val parameters = runnerContext.runnerParameters val arguments = ArrayList<String>() arguments.add(CargoConstants.COMMAND_YANK) val versionValue = parameters[CargoConstants.PARAM_YANK_VERSION] if (!versionValue.isNullOrBlank()) { arguments.add("--vers") arguments.add(versionValue.trim()) } val undoValue = parameters[CargoConstants.PARAM_YANK_UNDO] if ("true".equals(undoValue, ignoreCase = true)) { arguments.add("--undo") } val indexValue = parameters[CargoConstants.PARAM_YANK_INDEX] if (!indexValue.isNullOrBlank()) { arguments.add("--index") arguments.add(indexValue.trim()) } val tokenValue = parameters[CargoConstants.PARAM_YANK_TOKEN_SECURE] ?: parameters[CargoConstants.PARAM_YANK_TOKEN] if (!tokenValue.isNullOrBlank()) { arguments.add("--token") arguments.add(tokenValue.trim()) } val verbosityValue = parameters[CargoConstants.PARAM_VERBOSITY] if (!verbosityValue.isNullOrBlank()) { arguments.add(verbosityValue.trim()) } val crateValue = parameters[CargoConstants.PARAM_YANK_CRATE] if (!crateValue.isNullOrBlank()) { arguments.add(crateValue.trim()) } return arguments } }
apache-2.0
a46cf10cb3cdeca6d875b072a2775e57
31.683333
122
0.663437
4.646919
false
false
false
false
firebase/quickstart-android
internal/lint/src/main/java/com/firebase/lint/InvalidImportDetector.kt
4
2369
package com.firebase.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import org.jetbrains.uast.UImportStatement val ISSUE_INVALID_IMPORT = Issue.create( "SuspiciousImport", "importing files from the `java` package in a kotlin file", "Importing files from the java package is usually not intentional; it sometimes happens when " + "you have classes with the same name in both `java` and `kotlin` package.", Category.CORRECTNESS, 9, Severity.ERROR, Implementation( InvalidImportDetector::class.java, Scope.JAVA_FILE_SCOPE)) class InvalidImportDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UImportStatement::class.java) override fun createUastHandler(context: JavaContext) = InvalidImportHandler(context) class InvalidImportHandler(private val context: JavaContext) : UElementHandler() { override fun visitImportStatement(node: UImportStatement) { var importedPackageName = "" val classPackageName = context.uastFile?.packageName.toString() node.importReference?.let { importedPackageName = it.asSourceString() } val classPackageSubFolders = classPackageName.split(".") val importedPackageSubFolders = importedPackageName.split(".") var i = 0 while (i < classPackageSubFolders.size && i < importedPackageSubFolders.size) { if (classPackageSubFolders[i] == "kotlin" && importedPackageSubFolders[i] == "java") { node.importReference?.let { context.report(ISSUE_INVALID_IMPORT, node, context.getLocation(it), SHORT_MESSAGE) } } i++ } } } companion object { const val SHORT_MESSAGE = "Invalid Import: java package imported from kotlin package." } }
apache-2.0
284eb25c88c9ff8c12caeb5708301829
39.152542
106
0.66737
4.728543
false
false
false
false
Wyvarn/chatbot
app/src/main/kotlin/com/chatbot/ui/main/MainAdapter.kt
1
1244
package com.chatbot.ui.main import android.view.View import com.chatbot.R import com.chatbot.di.qualifier.DatabaseRefQualifier import com.chatbot.ui.ChatMessage import com.chatbot.ui.ChatViewHolder import com.firebase.ui.database.FirebaseRecyclerAdapter import com.google.firebase.database.DatabaseReference import javax.inject.Inject /** * @author lusinabrian on 23/09/17. * @Notes Main mainAdapter to handle the chats */ class MainAdapter @Inject constructor(@DatabaseRefQualifier databaseReference: DatabaseReference) : FirebaseRecyclerAdapter<ChatMessage, ChatViewHolder>(ChatMessage::class.java, R.layout.item_chat, ChatViewHolder::class.java, databaseReference.child("chat")) { override fun populateViewHolder(viewHolder: ChatViewHolder, model: ChatMessage, position: Int) { if (model.msgUser == "user") { viewHolder.rightText.text = model.msgText viewHolder.rightText.visibility = View.VISIBLE viewHolder.leftText.visibility = View.GONE } else { viewHolder.leftText.text = model.msgText viewHolder.rightText.visibility = View.GONE viewHolder.leftText.visibility = View.VISIBLE } } }
mit
d8a8513d508850f1d99b2ec407c98fcb
35.617647
199
0.717846
4.573529
false
false
false
false
VoIPGRID/vialer-android
app/src/main/java/com/voipgrid/vialer/callrecord/CallRecordAdapter.kt
1
1381
package com.voipgrid.vialer.callrecord import android.app.Activity import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import com.voipgrid.vialer.R import com.voipgrid.vialer.callrecord.database.CallRecordEntity class CallRecordAdapter : PagedListAdapter<CallRecordEntity, CallRecordViewHolder>(DIFF_CALLBACK) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CallRecordViewHolder = CallRecordViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item_call_record, parent, false)) var activity: Activity? = null override fun onBindViewHolder(holder: CallRecordViewHolder, position: Int) { getItem(position)?.let { activity?.let { activity -> holder.setActivity(activity) } holder.bindTo(it) } } companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<CallRecordEntity>() { override fun areItemsTheSame(oldConcert: CallRecordEntity, newConcert: CallRecordEntity) = oldConcert.id == newConcert.id override fun areContentsTheSame(oldConcert: CallRecordEntity, newConcert: CallRecordEntity) = oldConcert == newConcert } } }
gpl-3.0
46dfd948b864d2a2c7e274fe49870524
39.647059
124
0.703838
4.778547
false
false
false
false
dmitryustimov/weather-kotlin
app/src/main/java/ru/ustimov/weather/content/impl/local/data/RoomLocation.kt
1
561
package ru.ustimov.weather.content.impl.local.data import android.arch.persistence.room.ColumnInfo import ru.ustimov.weather.content.data.Location internal data class RoomLocation( @ColumnInfo(name = "latitude") private val latitude: Double, @ColumnInfo(name = "longitude") private val longitude: Double ) : Location { constructor(location: Location) : this( latitude = location.latitude(), longitude = location.longitude() ) override fun latitude() = latitude override fun longitude() = longitude }
apache-2.0
91c8f00da936751fba9aef30b6c385b5
27.1
69
0.702317
4.524194
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/services/PushListenerService.kt
1
5314
package org.eurofurence.connavigator.services import androidx.navigation.NavDeepLinkBuilder import androidx.work.WorkManager import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import org.eurofurence.connavigator.BuildConfig import org.eurofurence.connavigator.R import org.eurofurence.connavigator.notifications.EFNotificationChannel import org.eurofurence.connavigator.notifications.NotificationFactory import org.eurofurence.connavigator.preferences.RemotePreferences import org.eurofurence.connavigator.ui.activities.NavActivity import org.eurofurence.connavigator.ui.fragments.HomeFragmentDirections import org.eurofurence.connavigator.workers.DataUpdateWorker import org.eurofurence.connavigator.workers.FetchPrivateMessageWorker import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import org.jetbrains.anko.info import org.jetbrains.anko.warn import org.joda.time.Duration /** * Created by David on 14-4-2016. */ class PushListenerService : FirebaseMessagingService(), AnkoLogger { private val factory by lazy { NotificationFactory(applicationContext) } fun subscribe() { val messaging = FirebaseMessaging.getInstance() val topics = listOf( "${BuildConfig.CONVENTION_IDENTIFIER}", "${BuildConfig.CONVENTION_IDENTIFIER}-android" ) topics.forEach { messaging.subscribeToTopic(it) } info { "Push token: " + FirebaseInstanceId.getInstance().token } } override fun onMessageReceived(message: RemoteMessage) { info { "Received push message" } debug { "Message payload :" + message.data } when (message.data["Event"]) { "Sync" -> syncData() "Notification" -> createNotification(message) "Announcement" -> createAnnouncement(message) else -> warn("Message did not contain a valid event. Abandoning!") } } private fun syncData() { info { "Received request to sync data" } DataUpdateWorker.execute(this) RemotePreferences.update() } private val RemoteMessage.title get() = data["Title"] private val RemoteMessage.text get() = data["Text"] private val RemoteMessage.message get() = data["Message"] private val RemoteMessage.relatedId get() = data["RelatedId"] private val RemoteMessage.fallbackId get() = hashCode().toString() private val basicIntent get() = NavDeepLinkBuilder(this) .setComponentName(NavActivity::class.java) .setGraph(R.navigation.nav_graph) .setDestination(R.id.navHome) .createPendingIntent() private fun createNotification(message: RemoteMessage) { info { "Received request to create generic notification" } // Fetch in background on receiving, also assume that the cache is invalid every time. FetchPrivateMessageWorker.execute(this) val action = HomeFragmentDirections .actionFragmentViewHomeToFragmentViewMessageItem(message.relatedId!!) val intent = NavDeepLinkBuilder(this) .setComponentName(NavActivity::class.java) .setGraph(R.navigation.nav_graph) .setDestination(R.id.navMessageItem) .setArguments(action.arguments) .createPendingIntent() factory.createBasicNotification() .addRegularText(message.title ?: "No title was sent!", message.message ?: "No message was sent!") .setPendingIntent(intent) .setChannel(EFNotificationChannel.PRIVATE_MESSAGE) .broadcast(message.relatedId ?: message.fallbackId) } private fun createAnnouncement(message: RemoteMessage) { info { "Received request to create announcement notification" } syncData() val intent = try { val action = HomeFragmentDirections .actionFragmentViewHomeToFragmentViewAnnouncement(message.relatedId!!) NavDeepLinkBuilder(this) .setComponentName(NavActivity::class.java) .setGraph(R.navigation.nav_graph) .setDestination(R.id.navAnnouncementItem) .setArguments(action.arguments) .createPendingIntent() .apply { info { "Created pending activity" } } } catch (_: Exception) { warn { "Creating basic intent! You failed!!!" } basicIntent } factory.createBasicNotification() .addRegularText(message.title ?: "No title was sent!", message.text ?: "No extra text supplied") .addBigText(message.text ?: "No big text was supplied") .setPendingIntent(intent) .setChannel(EFNotificationChannel.ANNOUNCEMENT) .broadcast(message.relatedId ?: message.fallbackId) } }
mit
d4b6732389af0ab65efbf1948d5d6910
37.377778
94
0.6449
5.214917
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/codegen/backend/ConnectionProviderTypeProvider.kt
1
6213
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.codegen.backend import com.google.android.libraries.pcc.chronicle.codegen.backend.api.FileSpecContentsProvider import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec /** * Generates implementations of a [com.google.android.libraries.pcc.chronicle.api.ReadConnection] * and [com.google.android.libraries.pcc.chronicle.api.WriteConnection] and a corresponding * ConnectionProvider for each given `ReadConnection`, `WriteConnection` and `DataClass`. * * For example: * ``` * class ${ReadConnection}Impl(cache: TypedDataCacheReader<${DataClass}>) : * ${ReadConnection}, DataCacheReader<${DataClass}> by DataCacheReader.createDefault(cache) * * class ${WriteConnection}Impl(cache: TypedDataCacheWriter<${DataClass}>, timeSource: TimeSource) : * ${WriteConnection}, * DataCacheWriter<${DataClass}> by DataCacheWriter.createDefault(cache, timeSource) * * class ${DataClass}ConnectionProvider( * cache: ManagedDataCache<${DataClass}>, * timeSource: TimeSource, * ) : * DefaultManagedDataCacheConnectionProvider<${DataClass}>( * cache, * mapOf( * ${ReadConnection}::class.java to { ${ReadConnection}Impl(cache) }, * ${WriteConnection}::class.java to { ${WriteConnection}Impl(cache, timeSource) }, * ) * ) * * ``` */ class ConnectionProviderTypeProvider( val dataClass: TypeName, val readerConnections: List<TypeName>, val writerConnections: List<TypeName> ) : FileSpecContentsProvider { override fun provideContentsInto(builder: FileSpec.Builder) { val connectionMappings = mutableListOf<CodeBlock>() readerConnections.forEach { val readerImpl = buildReaderConnectionImpl(it) builder.addType(readerImpl) val readerMap = buildReaderMapEntry(it, readerImpl) connectionMappings.add(readerMap) } writerConnections.forEach { val impl = buildWriterConnectionImpl(it) builder.addType(impl) val mapEntry = buildWriterMapEntry(it, impl) connectionMappings.add(mapEntry) } val connectionProvider = buildConnectionProvider(connectionMappings) builder.addType(connectionProvider) } private fun buildReaderConnectionImpl(readerConnection: TypeName) = TypeSpec.classBuilder("${readerConnection.name}Impl") .primaryConstructor( FunSpec.constructorBuilder() .addParameter("cache", TYPED_DATA_CACHE_READER.parameterizedBy(dataClass)) .build() ) .addSuperinterface(readerConnection) .addSuperinterface( DATA_CACHE_READER.parameterizedBy(dataClass), CodeBlock.of("%N.createDefault(cache)", DATA_CACHE_READER.simpleName) ) .build() private fun buildWriterConnectionImpl(writerConnection: TypeName) = TypeSpec.classBuilder("${writerConnection.name}Impl") .primaryConstructor( FunSpec.constructorBuilder() .addParameter("cache", TYPED_DATA_CACHE_WRITER.parameterizedBy(dataClass)) .addParameter("timeSource", TIME_SOURCE) .build() ) .addSuperinterface(writerConnection) .addSuperinterface( DATA_CACHE_WRITER.parameterizedBy(dataClass), CodeBlock.of("%N.createDefault(cache, timeSource)", DATA_CACHE_WRITER.simpleName) ) .build() private fun buildReaderMapEntry(readerConnection: TypeName, readerImpl: TypeSpec) = CodeBlock.of("%N::class.java to { %N(cache) }", readerConnection.name, readerImpl) private fun buildWriterMapEntry(writerConnection: TypeName, writerImpl: TypeSpec) = CodeBlock.of("%N::class.java to { %N(cache, timeSource) }", writerConnection.name, writerImpl) private fun buildConnectionProvider(connectionMappings: List<CodeBlock>) = TypeSpec.classBuilder("${dataClass.name}ConnectionProvider") .primaryConstructor( FunSpec.constructorBuilder() .addParameter("cache", MANAGED_DATA_CACHE.parameterizedBy(dataClass)) .addParameter("timeSource", TIME_SOURCE) .build() ) .superclass(DEFAULT_MANAGED_DATA_CACHE_CONNECTION_PROVIDER.parameterizedBy(dataClass)) .addSuperclassConstructorParameter("cache") .addSuperclassConstructorParameter( "mapOf(%L)", CodeBlock.of("%L, ".repeat(connectionMappings.size), *connectionMappings.toTypedArray()) ) .build() companion object { private const val UTIL_PACKAGE_NAME = "com.google.android.libraries.pcc.chronicle.util" private val TIME_SOURCE = ClassName(UTIL_PACKAGE_NAME, "TimeSource") private const val DATACACHE_PACKAGE_NAME = "com.google.android.libraries.pcc.chronicle.storage.datacache" private val TYPED_DATA_CACHE_READER = ClassName(DATACACHE_PACKAGE_NAME, "TypedDataCacheReader") private val TYPED_DATA_CACHE_WRITER = ClassName(DATACACHE_PACKAGE_NAME, "TypedDataCacheWriter") private val DATA_CACHE_READER = ClassName(DATACACHE_PACKAGE_NAME, "DataCacheReader") private val DATA_CACHE_WRITER = ClassName(DATACACHE_PACKAGE_NAME, "DataCacheWriter") private val MANAGED_DATA_CACHE = ClassName(DATACACHE_PACKAGE_NAME, "ManagedDataCache") private val DEFAULT_MANAGED_DATA_CACHE_CONNECTION_PROVIDER = ClassName(DATACACHE_PACKAGE_NAME, "DefaultManagedDataCacheConnectionProvider") private val TypeName.name: String get() = (this as ClassName).simpleName } }
apache-2.0
116f46a5b6a05d3dc3047070359873e7
40.697987
100
0.734106
4.412642
false
false
false
false
willowtreeapps/assertk
assertk/src/commonMain/kotlin/assertk/assertions/any.kt
1
8243
package assertk.assertions import assertk.Assert import assertk.all import assertk.assertions.support.appendName import assertk.assertions.support.expected import assertk.assertions.support.fail import assertk.assertions.support.show import kotlin.reflect.KCallable import kotlin.reflect.KClass import kotlin.reflect.KProperty1 /** * Returns an assert on the kotlin class of the value. */ fun Assert<Any>.kClass() = prop("class") { it::class } /** * Returns an assert on the toString method of the value. */ fun Assert<Any?>.toStringFun() = prop("toString", Any?::toString) /** * Returns an assert on the hasCode method of the value. */ fun Assert<Any>.hashCodeFun() = prop("hashCode", Any::hashCode) /** * Asserts the value is equal to the expected one, using `==`. * @see [isNotEqualTo] * @see [isSameAs] */ fun <T> Assert<T>.isEqualTo(expected: T) = given { actual -> if (actual == expected) return fail(expected, actual) } /** * Asserts the value is not equal to the expected one, using `!=`. * @see [isEqualTo] * @see [isNotSameAs] */ fun Assert<Any?>.isNotEqualTo(expected: Any?) = given { actual -> if (actual != expected) return val showExpected = show(expected) val showActual = show(actual) // if they display the same, only show one. if (showExpected == showActual) { expected("to not be equal to:$showActual") } else { expected(":$showExpected not to be equal to:$showActual") } } /** * Asserts the value is the same as the expected one, using `===`. * @see [isNotSameAs] * @see [isEqualTo] */ fun <T> Assert<T>.isSameAs(expected: T) = given { actual -> if (actual === expected) return expected(":${show(expected)} and:${show(actual)} to refer to the same object") } /** * Asserts the value is not the same as the expected one, using `!==`. * @see [isSameAs] * @see [isNotEqualTo] */ fun Assert<Any?>.isNotSameAs(expected: Any?) = given { actual -> if (actual !== expected) return expected(":${show(expected)} to not refer to the same object") } /** * Asserts the value is in the expected values, using `in`. * @see [isNotIn] */ fun <T> Assert<T>.isIn(vararg values: T) = given { actual -> if (actual in values) return expected(":${show(values)} to contain:${show(actual)}") } /** * Asserts the value is not in the expected values, using `!in`. * @see [isIn] */ fun <T> Assert<T>.isNotIn(vararg values: T) = given { actual -> if (actual !in values) return expected(":${show(values)} to not contain:${show(actual)}") } /** * Asserts the value has the expected string from it's [toString]. */ fun Assert<Any?>.hasToString(string: String) { toStringFun().isEqualTo(string) } /** * Asserts the value has the expected hash code from it's [hashCode]. */ fun Assert<Any>.hasHashCode(hashCode: Int) { hashCodeFun().isEqualTo(hashCode) } /** * Asserts the value is null. */ fun Assert<Any?>.isNull() = given { actual -> if (actual == null) return expected("to be null but was:${show(actual)}") } /** * Asserts the value is not null. You can pass in an optional lambda to run additional assertions on the non-null value. * * ``` * val name: String? = ... * assertThat(name).isNotNull().hasLength(4) * ``` */ fun <T : Any> Assert<T?>.isNotNull(): Assert<T> = transform { actual -> actual ?: expected("to not be null") } /** * Returns an assert that asserts on the given property of the value. * @param name The name of the property to show in failure messages. * @param extract The function to extract the property value out of the value of the current assert. * * ``` * assertThat(person).prop("name", { it.name }).isEqualTo("Sue") * ``` */ fun <T, P> Assert<T>.prop(name: String, extract: (T) -> P): Assert<P> = transform(appendName(name, separator = "."), extract) /** * Returns an assert that asserts on the given property. * * Example: * ``` * assertThat(person).prop(Person::name).isEqualTo("Sue") * ``` * * @param property Property on which to assert. The name of this * property will be shown in failure messages. */ fun <T, P> Assert<T>.prop(property: KProperty1<T, P>): Assert<P> = prop(property.name) { property.get(it) } /** * Returns an assert that asserts on the result of calling the given function. * * Example: * ``` * assertThat(person).prop(Person::nameAsLowerCase).isEqualTo("sue") * ``` * * @param callable Callable on which to assert. The name of this * callable will be shown in the failure messages. */ fun <T, R, F> Assert<T>.prop(callable: F): Assert<R> where F : (T) -> R, F : KCallable<R> = prop(callable.name, callable) /** * Asserts the value has the expected kotlin class. This is an exact match, so `assertThat("test").hasClass(String::class)` * is successful but `assertThat("test").hasClass(Any::class)` fails. * @see [doesNotHaveClass] * @see [isInstanceOf] */ fun <T : Any> Assert<T>.hasClass(kclass: KClass<out T>) = given { actual -> if (kclass == actual::class) return expected("to have class:${show(kclass)} but was:${show(actual::class)}") } /** * Asserts the value does not have the expected kotlin class. This is an exact match, so * `assertThat("test").doesNotHaveClass(String::class)` is fails but `assertThat("test").doesNotHaveClass(Any::class)` is * successful. * @see [hasClass] * @see [isNotInstanceOf] */ fun <T : Any> Assert<T>.doesNotHaveClass(kclass: KClass<out T>) = given { actual -> if (kclass != actual::class) return expected("to not have class:${show(kclass)}") } /** * Asserts the value is not an instance of the expected kotlin class. Both * `assertThat("test").isNotInstanceOf(String::class)` and `assertThat("test").isNotInstanceOf(Any::class)` fails. * @see [isInstanceOf] * @see [doesNotHaveClass] */ fun <T : Any> Assert<T>.isNotInstanceOf(kclass: KClass<out T>) = given { actual -> if (!kclass.isInstance(actual)) return expected("to not be instance of:${show(kclass)}") } /** * Asserts the value is an instance of the expected kotlin class. Both `assertThat("test").isInstanceOf(String::class)` and * `assertThat("test").isInstanceOf(Any::class)` is successful. * @see [isNotInstanceOf] * @see [hasClass] */ fun <T : Any, S : T> Assert<T>.isInstanceOf(kclass: KClass<S>): Assert<S> = transform(name) { actual -> if (kclass.isInstance(actual)) { @Suppress("UNCHECKED_CAST") actual as S } else { expected("to be instance of:${show(kclass)} but had class:${show(actual::class)}") } } /** * Asserts the value corresponds to the expected one using the given correspondence function to compare them. This is * useful when the objects don't have an [equals] implementation. * * @see [isEqualTo] * @see [doesNotCorrespond] */ fun <T, E> Assert<T>.corresponds(expected: E, correspondence: (T, E) -> Boolean) = given { actual -> if (correspondence(actual, expected)) return fail(expected, actual) } /** * Asserts the value does not correspond to the expected one using the given correspondence function to compare them. * This is useful when the objects don't have an [equals] implementation. * * @see [corresponds] * @see [isNotEqualTo] */ fun <T, E> Assert<T>.doesNotCorrespond(expected: E, correspondence: (T, E) -> Boolean) = given { actual -> if (!correspondence(actual, expected)) return val showExpected = show(expected) val showActual = show(actual) // if they display the same, only show one. if (showExpected == showActual) { expected("to not be equal to:$showActual") } else { expected(":$showExpected not to be equal to:$showActual") } } /** * Returns an assert that compares only the given properties on the calling class * @param other Other value to compare to * @param properties properties of the type with which to compare * * ``` * assertThat(person).isEqualToWithGivenProperties(other, Person::name, Person::age) * ``` */ fun <T> Assert<T>.isEqualToWithGivenProperties(other: T, vararg properties: KProperty1<T, Any?>) { all { for (prop in properties) { transform(appendName(prop.name, separator = "."), prop::get) .isEqualTo(prop.get(other)) } } }
mit
5721e09c2259dd8c6ab06bb5c862f08a
30.342205
123
0.665898
3.626485
false
false
false
false
pchrysa/Memento-Calendar
android_mobile/src/main/java/com/alexstyl/specialdates/events/namedays/activity/NamedayPresenter.kt
1
2917
package com.alexstyl.specialdates.events.namedays.activity import com.alexstyl.gsc.SoundComparer.Companion.soundTheSame import com.alexstyl.specialdates.contact.Contact import com.alexstyl.specialdates.contact.ContactsProvider import com.alexstyl.specialdates.contact.DisplayName import com.alexstyl.specialdates.contact.Names import com.alexstyl.specialdates.date.Date import com.alexstyl.specialdates.events.namedays.NamedayUserSettings import com.alexstyl.specialdates.events.namedays.calendar.NamedayCalendar import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.disposables.Disposable class NamedayPresenter(private val namedayCalendar: NamedayCalendar, private val namedaysViewModelFactory: NamedaysViewModelFactory, private val contactsProvider: ContactsProvider, private val namedayUserSettings: NamedayUserSettings, private val workScheduler: Scheduler, private val resultScheduler: Scheduler) { private var disposable: Disposable? = null fun startPresenting(into: NamedaysMVPView, forDate: Date) { disposable = Observable.fromCallable { namedayCalendar.getAllNamedaysOn(forDate) } .observeOn(workScheduler) .map { findAndCreateViewModelsOf(it.names) } .observeOn(resultScheduler) .subscribe { namedaysViewModel -> into.displayNamedays(namedaysViewModel) } } fun stopPresenting() = disposable?.dispose() private fun findAndCreateViewModelsOf(celebratingNames: List<String>): List<NamedayScreenViewModel> { val allContacts = contactsProvider.allContacts return celebratingNames.fold(listOf(), { list, celebratingName -> val contactsCelebrating = allContacts.findContactsCalled(celebratingName) list + namedaysViewModelFactory.viewModelsFor(celebratingName) + contactsCelebrating.map { namedaysViewModelFactory.viewModelsFor(it) } }) } private val DisplayName.names: Names get() { return if (namedayUserSettings.shouldLookupAllNames()) { this.firstNames } else { this.firstNames } } private fun List<Contact>.findContactsCalled(celebratingName: String): List<Contact> { val list = ArrayList<Contact>() this.forEach { contact -> contact.displayName.names.forEach { if (it.soundsLike(celebratingName)) { list.add(contact) return@forEach } } } return list } } private fun String.soundsLike(celebratingName: String): Boolean = soundTheSame(this, celebratingName)
mit
76cbf34e05912c4db52a057d4e35eedd
38.418919
105
0.657182
5.037997
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/mlkit/barcode/BarcodeGraphic.kt
1
2660
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.mitations under the License. package com.itachi1706.cheesecakeutilities.mlkit.barcode import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.itachi1706.cheesecakeutilities.mlkit.camera.GraphicOverlay /** * Graphic instance for rendering barcode position, size, and ID within an associated graphic * overlay view. */ class BarcodeGraphic internal constructor(overlay: GraphicOverlay, // EXTRA METHODS val barcode: FirebaseVisionBarcode?) : GraphicOverlay.Graphic(overlay) { private val rectPaint: Paint private val barcodePaint: Paint init { rectPaint = Paint() rectPaint.color = TEXT_COLOR rectPaint.style = Paint.Style.STROKE rectPaint.strokeWidth = STROKE_WIDTH barcodePaint = Paint() barcodePaint.color = TEXT_COLOR barcodePaint.textSize = TEXT_SIZE // Redraw the overlay, as this graphic has been added. postInvalidate() } /** * Draws the barcode block annotations for position, size, and raw value on the supplied canvas. */ override fun draw(canvas: Canvas) { if (barcode == null) { throw IllegalStateException("Attempting to draw a null barcode.") } // Draws the bounding box around the BarcodeBlock. val rect = RectF(barcode.boundingBox) rect.left = translateX(rect.left) rect.top = translateY(rect.top) rect.right = translateX(rect.right) rect.bottom = translateY(rect.bottom) canvas.drawRect(rect, rectPaint) // Renders the barcode at the bottom of the box. @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") canvas.drawText(barcode.rawValue, rect.left, rect.bottom, barcodePaint) } companion object { private val TEXT_COLOR = Color.WHITE private val TEXT_SIZE = 54.0f private val STROKE_WIDTH = 4.0f } }
mit
ffbad7c443596e8063097fcc163fcd20
34.959459
114
0.693609
4.602076
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/AmigosCommand.kt
1
5229
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.LorittaUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.toBufferedImage import net.dv8tion.jda.api.entities.Member import net.perfectdreams.loritta.common.commands.ArgumentType import net.perfectdreams.loritta.common.commands.arguments import net.perfectdreams.loritta.morenitta.utils.ImageFormat import net.perfectdreams.loritta.morenitta.utils.extensions.getEffectiveAvatarUrl import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO class AmigosCommand(loritta: LorittaBot) : AbstractCommand(loritta, "friends", listOf("amigos", "meusamigos", "myfriends"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { companion object { val TEMPLATE by lazy { ImageIO.read(File(Constants.ASSETS_FOLDER, "thx.png")) } } override fun getDescriptionKey() = LocaleKeyData("commands.command.friends.description") override fun getExamplesKey() = LocaleKeyData("commands.command.lava.examples") override fun getUsage() = arguments { repeat(9) { argument(ArgumentType.USER) { optional = true } } } override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { val choosen = mutableListOf<Member>() var contextImage = context.getImageAt(0, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage2 = context.getImageAt(1, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage3 = context.getImageAt(2, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage4 = context.getImageAt(3, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage5 = context.getImageAt(4, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage6 = context.getImageAt(5, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage7 = context.getImageAt(6, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage8 = context.getImageAt(7, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) var contextImage9 = context.getImageAt(8, 0, 128, createTextAsImageIfNotFound = false) ?: getRandomAvatar(context, choosen) contextImage = contextImage.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage2 = contextImage2.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage3 = contextImage3.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage4 = contextImage4.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage5 = contextImage5.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage6 = contextImage6.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage7 = contextImage7.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage8 = contextImage8.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() contextImage9 = contextImage9.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH).toBufferedImage() val finalImage = BufferedImage(384, 384, BufferedImage.TYPE_INT_ARGB) val graphics = finalImage.graphics graphics.drawImage(contextImage, 0, 0, null) graphics.drawImage(contextImage2, 128, 0, null) graphics.drawImage(contextImage3, 256, 0, null) graphics.drawImage(contextImage4, 0, 128, null) graphics.drawImage(contextImage5, 128, 128, null) graphics.drawImage(contextImage6, 256, 128, null) graphics.drawImage(contextImage7, 0, 256, null) graphics.drawImage(contextImage8, 128, 256, null) graphics.drawImage(contextImage9, 256, 256, null) graphics.drawImage(TEMPLATE, 0, 0, null) context.sendFile(finalImage, "thx.png", context.getAsMention(true)) } fun getRandomAvatar(context: CommandContext, choosen: MutableList<Member>): BufferedImage { val list = context.guild.members.toMutableList() list.removeAll(choosen) var userAvatar: String? = null while (userAvatar == null) { if (list.isEmpty()) { // omg, lista vazia! // Vamos pegar um usuário aleatório e vamos cair fora daqui! userAvatar = context.guild.members.random().user.getEffectiveAvatarUrl(ImageFormat.PNG, 128) break } val member = list[LorittaBot.RANDOM.nextInt(list.size)] userAvatar = member.user.avatarUrl if (userAvatar == null) list.remove(member) else choosen.add(member) } return LorittaUtils.downloadImage(loritta, userAvatar!!) ?: Constants.IMAGE_FALLBACK } }
agpl-3.0
64784ca63df1f32f047df7e06149abc2
50.254902
191
0.791276
3.834923
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/entity/Entity3D.kt
1
3172
package xyz.jmullin.drifter.entity import com.badlogic.gdx.graphics.g3d.Environment import com.badlogic.gdx.graphics.g3d.ModelBatch import com.badlogic.gdx.math.Intersector import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.math.Vector3 import com.badlogic.gdx.math.collision.BoundingBox import com.badlogic.gdx.math.collision.Ray import xyz.jmullin.drifter.extensions.V3 /** * 3-dimensional entity, contains scaffolding on top of Entity for tracking 3d position. * An Entity3D can be added/removed from a Layer3D, which will take care of calling update/render periodically. */ @Suppress("UNUSED_PARAMETER") open class Entity3D : EntityContainer3D, Entity() { // Implicits for local context fun self() = this override fun layer() = parent?.layer() override var children = emptyList<Entity3D>() override var mouseLocked: Vector2? = null /** * This entity's parent container, or None if it's not attached. */ var parent: EntityContainer3D? = null /** * World position of the entity. */ var position = V3(0f) /** * Optional bounding box for this entity to determine simple collision. */ var boundingBox: BoundingBox? = null /** * Called to determine if a ray (typically cast from the camera) intersects with this object. * Default implementation checks for intersection with the entity's bounding box, if present. * * @param ray Ray cast to determine the hit point. * @return Some containing the point at which the entity was hit, if there was a collision. * None if there was no collision. */ fun hitPoint(ray: Ray): Vector3? { val intersection = V3(0f, 0f, 0f) return boundingBox?.let { bounds -> if(Intersector.intersectRayBounds(ray, bounds, intersection)) intersection else null } } // 3D oriented mouse events fun touchDown(v: Vector3, button: Int) = true fun touchUp(v: Vector3, button: Int) = false fun touchDragged(v: Vector3) = false fun mouseMoved(v: Vector3) = false /** * Called by the parent container when this entity is added to it. Override to perform some * action after the parent container has been assigned. * * @param container The new parent container. */ open fun create(container: EntityContainer3D) { parent = container } /** * Called by the parent container on each frame to render this entity. * * @param batch Active ModelBatch to use in rendering. * @param environment Environment to render within. */ open fun render(batch: ModelBatch, environment: Environment) { renderChildren(batch, environment) } /** * Called by the parent container at each tick to update this entity. * * @param delta Time in seconds elapsed since the last update tick. */ override fun update(delta: Float) { updateChildren(delta) super.update(delta) } /** * Remove this entity from its parent container, if any. */ fun remove() { layer()?.remove(this) parent = null } }
mit
cb5e043bfda60289c655c056279427ec
30.415842
111
0.667402
4.206897
false
false
false
false
shyiko/ktlint
ktlint-test/src/main/kotlin/com/pinterest/ktlint/test/RuleExtension.kt
1
4527
package com.pinterest.ktlint.test import com.pinterest.ktlint.core.KtLint import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.RuleSet import java.util.ArrayList import org.assertj.core.util.diff.DiffUtils.diff import org.assertj.core.util.diff.DiffUtils.generateUnifiedDiff public fun Rule.lint( text: String, userData: Map<String, String> = emptyMap(), script: Boolean = false ): List<LintError> = lint(null, text, userData, script) public fun Rule.lint( lintedFilePath: String?, text: String, userData: Map<String, String> = emptyMap(), script: Boolean = false ): List<LintError> { val res = ArrayList<LintError>() val debug = debugAST() KtLint.lint( KtLint.Params( fileName = lintedFilePath, text = text, ruleSets = (if (debug) listOf(RuleSet("debug", DumpAST())) else emptyList()) + listOf(RuleSet("standard", this@lint)), userData = userData, script = script, cb = { e, _ -> if (debug) { System.err.println("^^ lint error") } res.add(e) } ) ) return res } public fun Rule.format( text: String, userData: Map<String, String> = emptyMap(), cb: (e: LintError, corrected: Boolean) -> Unit = { _, _ -> }, script: Boolean = false ): String = format(null, text, userData, cb, script) public fun Rule.format( lintedFilePath: String?, text: String, userData: Map<String, String> = emptyMap(), cb: (e: LintError, corrected: Boolean) -> Unit = { _, _ -> }, script: Boolean = false ): String = KtLint.format( KtLint.Params( fileName = lintedFilePath, text = text, ruleSets = (if (debugAST()) listOf(RuleSet("debug", DumpAST())) else emptyList()) + listOf(RuleSet("standard", this@format)), userData = userData, script = script, cb = cb ) ) public fun Rule.diffFileLint( path: String, userData: Map<String, String> = emptyMap() ): String { val resourceText = getResourceAsText(path).replace("\r\n", "\n") val dividerIndex = resourceText.lastIndexOf("\n// expect\n") if (dividerIndex == -1) { throw RuntimeException("$path must contain '// expect' line") } val input = resourceText.substring(0, dividerIndex) val expected = resourceText.substring(dividerIndex + 1).split('\n').mapNotNull { line -> if (line.isBlank() || line == "// expect") { null } else { line.trimMargin("// ").split(':', limit = 3).let { expectation -> if (expectation.size != 3) { throw RuntimeException("$path expectation must be a triple <line>:<column>:<message>") // " (<message> is not allowed to contain \":\")") } val message = expectation[2] val detail = message.removeSuffix(" (cannot be auto-corrected)") LintError(expectation[0].toInt(), expectation[1].toInt(), id, detail, message == detail) } } } val actual = lint(input, userData, script = true) val str = { err: LintError -> val ruleId = if (err.ruleId != id) " (${err.ruleId})" else "" val correctionStatus = if (!err.canBeAutoCorrected) " (cannot be auto-corrected)" else "" "${err.line}:${err.col}:${err.detail}$ruleId$correctionStatus" } val diff = generateUnifiedDiff( "expected", "actual", expected.map(str), diff(expected.map(str), actual.map(str)), expected.size + actual.size ).joinToString("\n") return if (diff.isEmpty()) "" else diff } public fun Rule.diffFileFormat( srcPath: String, expectedPath: String, userData: Map<String, String> = emptyMap() ): String { val actual = format(getResourceAsText(srcPath), userData, script = true).split('\n') val expected = getResourceAsText(expectedPath).split('\n') val diff = generateUnifiedDiff(expectedPath, "output", expected, diff(expected, actual), expected.size + actual.size) .joinToString("\n") return if (diff.isEmpty()) "" else diff } private fun getResourceAsText(path: String) = (ClassLoader.getSystemClassLoader().getResourceAsStream(path) ?: throw RuntimeException("$path not found")) .bufferedReader() .readText()
mit
07b7a8dd2b823ee71293fc6c2d5d2488
34.645669
114
0.595538
4.187789
false
false
false
false
allen-garvey/photog-spark
src/main/kotlin/views/ImageView.kt
1
1579
package views import models.Image import models.Thumbnail import views.BaseView.baseUrl import views.BaseView.uriEncode import java.text.SimpleDateFormat import java.util.* /** * Created by allen on 3/30/17. */ object ImageView{ val mediaBaseUrl: String = BaseView.baseUrl() fun thumbnailAssetBaseUrl(): String{ return "${mediaBaseUrl}media/thumbnails/" } fun imageAssetBaseUrl(): String{ return "${mediaBaseUrl}media/images/" } fun urlForImageFull(image: Image?): String{ if(image != null){ return imageAssetBaseUrl() + uriEncode(image.path) } return "" } fun urlForThumbnailMini(thumbnail: Thumbnail?): String{ if(thumbnail != null){ return thumbnailAssetBaseUrl() + uriEncode(thumbnail.miniThumbnailPath) } return "" } fun urlForThumbnail(thumbnail: Thumbnail?): String{ if(thumbnail != null){ return thumbnailAssetBaseUrl() + uriEncode(thumbnail.thumbnailPath) } return "" } fun urlForImage(image: Image?): String{ if(image != null){ return baseUrl() + "images/" + image.id } return "" } fun creationDate(image: Image): String?{ if(image.creation == null){ return null } val date = Date() date.setTime(image.creation.time) val dateFormatter = SimpleDateFormat("MM/dd/yyyy h:mm a") dateFormatter.timeZone = TimeZone.getTimeZone("UTC") return dateFormatter.format(date) } }
mit
b8942c89b4fea0c20c131a99d2d2ea90
23.292308
83
0.613046
4.386111
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/properties/playstats/factory/GivenVersion21OrLessOfMediaCenter/WhenGettingThePlaystatsUpdater.kt
2
2891
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory.GivenVersion21OrLessOfMediaCenter import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.FakeFilePropertiesContainer import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedFilePropertiesProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.IPlaystatsUpdate import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory.PlaystatsUpdateSelector import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.fileproperties.FilePropertiesPlayStatsUpdater import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.storage.ScopedFilePropertiesStorage import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeScopedRevisionProvider import com.lasthopesoftware.bluewater.client.connection.FakeConnectionProvider import com.lasthopesoftware.bluewater.client.connection.authentication.CheckIfScopedConnectionIsReadOnly import com.lasthopesoftware.bluewater.client.servers.version.IProgramVersionProvider import com.lasthopesoftware.bluewater.client.servers.version.SemanticVersion import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions import org.junit.BeforeClass import org.junit.Test class WhenGettingThePlaystatsUpdater { companion object { private var updater: IPlaystatsUpdate? = null @BeforeClass @JvmStatic fun before() { val fakeConnectionProvider = FakeConnectionProvider() val programVersionProvider = mockk<IProgramVersionProvider>() every { programVersionProvider.promiseServerVersion() } returns Promise(SemanticVersion(21, 0, 0)) val checkConnection = mockk<CheckIfScopedConnectionIsReadOnly>() every { checkConnection.promiseIsReadOnly() } returns false.toPromise() val fakeFilePropertiesContainer = FakeFilePropertiesContainer() val scopedRevisionProvider = FakeScopedRevisionProvider(10) val playstatsUpdateSelector = PlaystatsUpdateSelector( fakeConnectionProvider, ScopedFilePropertiesProvider(fakeConnectionProvider, scopedRevisionProvider, fakeFilePropertiesContainer), ScopedFilePropertiesStorage(fakeConnectionProvider, checkConnection, scopedRevisionProvider, fakeFilePropertiesContainer), programVersionProvider ) updater = playstatsUpdateSelector.promisePlaystatsUpdater().toFuture().get() } } @Test fun thenTheFilePropertiesPlaystatsUpdaterIsGiven() { Assertions.assertThat(updater).isInstanceOf( FilePropertiesPlayStatsUpdater::class.java ) } }
lgpl-3.0
6d37a2eacd75d4c05a04853b5c1de626
51.563636
138
0.857489
4.64791
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/inspectors/deprecated.kt
1
4542
package io.kotest.inspectors @Deprecated("use the extension function version of this", ReplaceWith("array.forAll(fn)")) fun <T> forAll(array: Array<T>, fn: (T) -> Unit) = forAll(array.asList(), fn) @Deprecated("use the extension function version of this", ReplaceWith("col.forAll(fn)")) fun <T> forAll(col: Collection<T>, fn: (T) -> Unit) { val results = runTests(col, fn) val passed = results.filterIsInstance<ElementPass<T>>() if (passed.size < col.size) { val msg = "${passed.size} elements passed but expected ${col.size}" buildAssertionError(msg, results) } } @Deprecated("use the extension function version of this", ReplaceWith("array.forOne(fn)")) fun <T> forOne(array: Array<T>, fn: (T) -> Unit) = forOne(array.asList(), fn) @Deprecated("use the extension function version of this", ReplaceWith("col.forOne(fn)")) fun <T> forOne(col: Collection<T>, f: (T) -> Unit) = forExactly(1, col, f) @Deprecated("use the extension function version of this", ReplaceWith("array.forExactly(fn)")) fun <T> forExactly(k: Int, array: Array<T>, f: (T) -> Unit) = forExactly(k, array.asList(), f) @Deprecated("use the extension function version of this", ReplaceWith("col.forExactly(fn)")) fun <T> forExactly(k: Int, col: Collection<T>, fn: (T) -> Unit) { val results = runTests(col, fn) val passed = results.filterIsInstance<ElementPass<T>>() if (passed.size != k) { val msg = "${passed.size} elements passed but expected $k" buildAssertionError(msg, results) } } @Deprecated("use the extension function version of this", ReplaceWith("array.forSome(fn)")) fun <T> forSome(array: Array<T>, f: (T) -> Unit) = forSome(array.asList(), f) @Deprecated("use the extension function version of this", ReplaceWith("col.forSome(fn)")) fun <T> forSome(col: Collection<T>, fn: (T) -> Unit) { val size = col.size val results = runTests(col, fn) val passed = results.filterIsInstance<ElementPass<T>>() if (passed.isEmpty()) { buildAssertionError("No elements passed but expected at least one", results) } else if (passed.size == size) { buildAssertionError("All elements passed but expected < $size", results) } } @Deprecated("use the extension function version of this", ReplaceWith("array.forAny(fn)")) fun <T> forAny(array: Array<T>, f: (T) -> Unit) = forAny(array.asList(), f) @Deprecated("use the extension function version of this", ReplaceWith("col.forAny(fn)")) fun <T> forAny(col: Collection<T>, f: (T) -> Unit) = forAtLeast(1, col, f) @Deprecated("use the extension function version of this", ReplaceWith("array.forAtLeastOne(fn)")) fun <T> forAtLeastOne(array: Array<T>, f: (T) -> Unit) = forAtLeastOne(array.asList(), f) @Deprecated("use the extension function version of this", ReplaceWith("col.forAtLeastOne(fn)")) fun <T> forAtLeastOne(col: Collection<T>, f: (T) -> Unit) = forAtLeast(1, col, f) @Deprecated("use the extension function version of this", ReplaceWith("array.forAtLeast(fn)")) fun <T> forAtLeast(k: Int, array: Array<T>, f: (T) -> Unit) = forAtLeast(k, array.asList(), f) @Deprecated("use the extension function version of this", ReplaceWith("col.forAtLeast(fn)")) fun <T> forAtLeast(k: Int, col: Collection<T>, f: (T) -> Unit) { val results = runTests(col, f) val passed = results.filterIsInstance<ElementPass<T>>() if (passed.size < k) { val msg = "${passed.size} elements passed but expected at least $k" buildAssertionError(msg, results) } } @Deprecated("use the extension function version of this", ReplaceWith("array.forAtMostOne(fn)")) fun <T> forAtMostOne(array: Array<T>, f: (T) -> Unit) = forAtMost(1, array.asList(), f) @Deprecated("use the extension function version of this", ReplaceWith("col.forAtMostOne(fn)")) fun <T> forAtMostOne(col: Collection<T>, f: (T) -> Unit) = forAtMost(1, col, f) @Deprecated("use the extension function version of this", ReplaceWith("col.forAtMost(fn)")) fun <T> forAtMost(k: Int, col: Collection<T>, f: (T) -> Unit) { val results = runTests(col, f) val passed = results.filterIsInstance<ElementPass<T>>() if (passed.size > k) { val msg = "${passed.size} elements passed but expected at most $k" buildAssertionError(msg, results) } } @Deprecated("use the extension function version of this", ReplaceWith("array.forNone(fn)")) fun <T> forNone(array: Array<T>, testFn: (T) -> Unit) = forNone(array.asList(), testFn) @Deprecated("use the extension function version of this", ReplaceWith("col.forNone(fn)")) fun <T> forNone(col: Collection<T>, testFn: (T) -> Unit) = forExactly(0, col, testFn)
apache-2.0
4876d0b8af4b9b1621bc288413af7a7a
46.810526
97
0.692646
3.392084
false
true
false
false
raniejade/kspec
samples/src/test/kotlin/io/polymorphicpanda/kspec/samples/CalculatorSpec.kt
1
1231
package io.polymorphicpanda.kspec.samples import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import io.polymorphicpanda.kspec.* import io.polymorphicpanda.kspec.junit.JUnitKSpecRunner import org.junit.runner.RunWith /** * @author Ranie Jade Ramiso */ @RunWith(JUnitKSpecRunner::class) class CalculatorSpec: KSpec() { override fun spec() { describe(Calculator::class) { itBehavesLike(calculator()) } } companion object { fun calculator() = sharedExample<Calculator> { describe("add") { it("1 + 1 = 2") { assertThat(subject.add(1, 1), equalTo(2)) } } describe("minus") { it("1 - 1 = 0") { assertThat(subject.minus(1, 1), equalTo(0)) } } describe("multiply") { it("1 * 2 = 2") { assertThat(subject.multiply(1, 2), equalTo(2)) } } describe("divide") { it("10 / 5 = 2") { assertThat(subject.divide(10, 5), equalTo(2)) } } } } }
mit
b45de7073ac70ef89d63bcb9eb1ad2f4
25.191489
66
0.495532
4.444043
false
false
false
false
yongce/DevTools
app/src/main/java/me/ycdev/android/devtools/sampler/AppsSetStat.kt
1
4031
package me.ycdev.android.devtools.sampler import android.app.ActivityManager import android.content.Context import android.os.SystemClock import me.ycdev.android.devtools.sampler.cpu.CpuUtils import me.ycdev.android.devtools.sampler.mem.MemoryUtils import me.ycdev.android.devtools.sampler.traffic.TrafficUtils import java.util.ArrayList import java.util.HashMap import java.util.HashSet import kotlin.collections.set class AppsSetStat private constructor() { var sampleTime: Long = 0 // in System.currentTimeMillis() var clockTime: Long = 0 var targetApps = HashSet<String>() var appsStat = HashMap<String, AppStat>() companion object { fun computeUsage(oldStat: AppsSetStat, newStat: AppsSetStat): AppsSetStat { val usage = AppsSetStat() usage.sampleTime = newStat.sampleTime usage.clockTime = newStat.clockTime - oldStat.clockTime usage.targetApps.addAll(newStat.targetApps) for (newAppStat in newStat.appsStat.values) { val oldAppStat = oldStat.appsStat[newAppStat.pkgName] if (oldAppStat != null) { val appUsage: AppStat? = AppStat.computeUsage(oldAppStat, newAppStat) if (appUsage != null) { usage.appsStat[appUsage.pkgName] = appUsage } } } return usage } fun createSnapshot(cxt: Context, pkgNames: ArrayList<String>?): AppsSetStat { val appsSetStat = AppsSetStat() appsSetStat.sampleTime = System.currentTimeMillis() appsSetStat.clockTime = SystemClock.uptimeMillis() if (pkgNames != null) { appsSetStat.targetApps.addAll(pkgNames) } val am = cxt.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val runningApps = am.runningAppProcesses val allPidsSet = HashSet<Int>() for (procInfo in runningApps) { for (pkgName in procInfo.pkgList) { if (appsSetStat.targetApps.contains(pkgName)) { allPidsSet.add(procInfo.pid) var appStat = appsSetStat.appsStat[pkgName] if (appStat == null) { appStat = AppStat(pkgName, procInfo.uid) appsSetStat.appsStat[pkgName] = appStat } appStat.pidsSet.add(procInfo.pid) } } } val pidsCount = allPidsSet.size val pids = IntArray(pidsCount) run { for ((i, pid) in allPidsSet.withIndex()) { pids[i] = pid } } // cpu stats val pidsCpuStats = CpuUtils.getProcCpuStats(pids) for (i in 0 until pidsCount) { val pid = pids[i] val procCpu = pidsCpuStats[i] ?: continue for (appStat in appsSetStat.appsStat.values) { if (appStat.pidsSet.contains(pid)) { appStat.cpuStat.procSetStats.put(pid, procCpu) break } } } // memory stats val pidsMemStats = MemoryUtils.getProcessMemoryStat(cxt, pids) for (i in 0 until pidsCount) { val pid = pids[i] val procMem = pidsMemStats[i] for (appStat in appsSetStat.appsStat.values) { if (appStat.pidsSet.contains(pid)) { appStat.memStat.procSetStats.put(pid, procMem) break } } } // traffic stats for (appStat in appsSetStat.appsStat.values) { appStat.trafficStat = TrafficUtils.getTrafficStat(appStat.uid) } return appsSetStat } } }
apache-2.0
ab52d7ed0bf49655d11904b2a002ecb9
39.717172
89
0.544034
4.419956
false
false
false
false
FurhatRobotics/example-skills
Dog/src/main/kotlin/furhatos/app/dog/gestures/growls.kt
1
1502
package furhatos.app.dog.gestures import furhatos.app.dog.utils._defineGesture import furhatos.app.dog.utils.getAudioURL import furhatos.gestures.BasicParams val growlPositive2 = _defineGesture("growlPositive2", frameTimes = listOf(0.2), audioURL = getAudioURL("Small_dog_single_growl_non_aggressive_02.wav")) { // This empty frame needs to be here for the audio to not play twice frame(1.0) { } frame(0.5, 1.5) { BasicParams.NECK_ROLL to 10 BasicParams.SMILE_OPEN to 0.8 } reset(2.0) } val growlPositive4 = _defineGesture("growlPositive4", frameTimes = listOf(0.2), audioURL = getAudioURL("Small_dog_single_growl_non_aggressive_04.wav")) { // This empty frame needs to be here for the audio to not play twice frame(1.0) { } frame(0.5, 1.5) { BasicParams.NECK_ROLL to -10 BasicParams.SMILE_OPEN to 0.8 } reset(2.0) } val growl2 = _defineGesture("growl2", frameTimes = listOf(0.2), audioURL = getAudioURL("Medium_dog_growl_vicious_02.wav")) { // This empty frame needs to be here for the audio to not play twice frame(0.2) { } frame(0.5, 1.5) { BasicParams.EXPR_ANGER to 1.0 } reset(2.0) } val growl4 = _defineGesture("growl4", frameTimes = listOf(1.5), audioURL = getAudioURL("Medium_dog_growl_vicious_04.wav")) { // This empty frame needs to be here for the audio to not play twice frame(1.5) { } frame(0.5, 3.0) { BasicParams.EXPR_ANGER to 1.0 } reset(4.0) }
mit
bacd19cf28c3c8ece9ff10f130489902
28.45098
153
0.663116
3.155462
false
false
false
false
jilees/Fuel
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/requests/UploadTaskRequest.kt
1
2888
package com.github.kittinunf.fuel.core.requests import com.github.kittinunf.fuel.core.Request import com.github.kittinunf.fuel.core.Response import com.github.kittinunf.fuel.util.copyTo import com.github.kittinunf.fuel.util.toHexString import java.io.ByteArrayOutputStream import java.io.File import java.io.InputStream import java.io.OutputStream import java.net.URL import java.net.URLConnection import javax.activation.MimetypesFileTypeMap class UploadTaskRequest(request: Request) : TaskRequest(request) { val BUFFER_SIZE = 1024 val CRLF = "\r\n" val boundary = request.httpHeaders["Content-Type"]?.split("=", limit = 2)?.get(1) ?: System.currentTimeMillis().toHexString() var progressCallback: ((Long, Long) -> Unit)? = null lateinit var sourceCallback: (Request, URL) -> Iterable<Pair<InputStream, String>> var dataStream: ByteArrayOutputStream? = null override fun call(): Response { try { dataStream = ByteArrayOutputStream().apply { val files = sourceCallback.invoke(request, request.url) files.forEachIndexed { i, file -> val postFix = if (files.count() == 1) "" else "${i + 1}" val fileName = request.names.getOrElse(i) { request.name + postFix } write("--$boundary") write(CRLF) write("Content-Disposition: form-data; name=\"$fileName\"; filename=\"${file.second}\"") write(CRLF) write("Content-Type: " + request.mediaTypes.getOrElse(i) { guessContentType(file.second) }) write(CRLF) write(CRLF) //input file data file.first.use { it.copyTo(this, BUFFER_SIZE) { writtenBytes -> {} } } write(CRLF) } request.parameters.forEach { write("--$boundary") write(CRLF) write("Content-Disposition: form-data; name=\"${it.first}\"") write(CRLF) write("Content-Type: text/plain") write(CRLF) write(CRLF) write(it.second.toString()) write(CRLF) } write(("--$boundary--")) write(CRLF) flush() } request.body(dataStream!!.toByteArray()) return super.call() } finally { dataStream?.close() } } private fun guessContentType(fileName: String): String { return URLConnection.guessContentTypeFromName(fileName) ?: "multipart/form-data" } } fun OutputStream.write(str: String) = write(str.toByteArray())
mit
0fe2be8218b7a545f894cffd2f0271b5
33.795181
129
0.544321
4.886633
false
false
false
false
wasabeef/recyclerview-animators
animators/src/main/java/jp/wasabeef/recyclerview/animators/ScaleInRightAnimator.kt
1
1873
package jp.wasabeef.recyclerview.animators import android.view.animation.Interpolator import androidx.recyclerview.widget.RecyclerView /** * Copyright (C) 2021 Daichi Furiya / Wasabeef * * 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. */ open class ScaleInRightAnimator : BaseItemAnimator { constructor() constructor(interpolator: Interpolator) { this.interpolator = interpolator } override fun preAnimateRemoveImpl(holder: RecyclerView.ViewHolder) { holder.itemView.pivotX = holder.itemView.width.toFloat() } override fun animateRemoveImpl(holder: RecyclerView.ViewHolder) { holder.itemView.animate().apply { scaleX(0f) scaleY(0f) duration = removeDuration interpolator = interpolator setListener(DefaultRemoveAnimatorListener(holder)) startDelay = getRemoveDelay(holder) }.start() } override fun preAnimateAddImpl(holder: RecyclerView.ViewHolder) { holder.itemView.pivotX = holder.itemView.width.toFloat() holder.itemView.scaleX = 0f holder.itemView.scaleY = 0f } override fun animateAddImpl(holder: RecyclerView.ViewHolder) { holder.itemView.animate().apply { scaleX(1f) scaleY(1f) duration = addDuration interpolator = interpolator setListener(DefaultAddAnimatorListener(holder)) startDelay = getAddDelay(holder) }.start() } }
apache-2.0
63851231294bdd92ac66a17de76ebf88
31.293103
75
0.735718
4.386417
false
false
false
false
CarrotCodes/Warren
src/main/kotlin/chat/willow/warren/handler/rpl/Rpl471Handler.kt
1
1208
package chat.willow.warren.handler.rpl import chat.willow.kale.IMetadataStore import chat.willow.kale.KaleHandler import chat.willow.kale.irc.message.rfc1459.rpl.Rpl471Message import chat.willow.kale.irc.message.rfc1459.rpl.Rpl471MessageType import chat.willow.warren.helper.loggerFor import chat.willow.warren.state.CaseMappingState import chat.willow.warren.state.JoiningChannelLifecycle import chat.willow.warren.state.JoiningChannelsState class Rpl471Handler(val channelsState: JoiningChannelsState, val caseMappingState: CaseMappingState) : KaleHandler<Rpl471MessageType>(Rpl471Message.Parser) { private val LOGGER = loggerFor<Rpl471Handler>() override fun handle(message: Rpl471MessageType, metadata: IMetadataStore) { val channel = channelsState[message.channel] if (channel == null) { LOGGER.warn("got a full channel reply for a channel we don't think we're joining: $message") LOGGER.trace("channels state: $channelsState") return } LOGGER.warn("channel is full, failed to join: $channel") channel.status = JoiningChannelLifecycle.FAILED LOGGER.trace("new channels state: $channelsState") } }
isc
c381af158556ef13647ed9a07667c7dd
35.606061
157
0.752483
4.268551
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/list/ListModel.kt
2
850
package org.wordpress.android.fluxc.model.list import com.yarolegovich.wellsql.core.Identifiable import com.yarolegovich.wellsql.core.annotation.Column import com.yarolegovich.wellsql.core.annotation.PrimaryKey import com.yarolegovich.wellsql.core.annotation.Table const val LIST_STATE_TIMEOUT = 60 * 1000 // 1 minute @Table class ListModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable { @Column var lastModified: String? = null // ISO 8601-formatted date in UTC, e.g. 1955-11-05T14:15:00Z // These fields shouldn't be used directly. @Column var descriptorUniqueIdentifierDbValue: Int? = null @Column var descriptorTypeIdentifierDbValue: Int? = null @Column var stateDbValue: Int = ListState.defaultState.value override fun getId(): Int = id override fun setId(id: Int) { this.id = id } }
gpl-2.0
c64458443abbd60a38f3bf9c445f1d9c
34.416667
105
0.745882
3.863636
false
false
false
false
brunordg/ctanywhere
app/src/main/java/br/com/codeteam/ctanywhere/utils/ScreenUtils.kt
1
2086
package br.com.codeteam.ctanywhere.utils import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.util.DisplayMetrics import android.view.WindowManager import android.widget.TextView import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import br.com.codeteam.ctanywhere.context.ApplicationConstants object ScreenUtils { fun getScreenWidth(context: Context): Int { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager windowManager.let { val dm = DisplayMetrics() it.defaultDisplay.getMetrics(dm) return dm.widthPixels } } fun getScreenHeight(context: Context): Int { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager windowManager.let { val dm = DisplayMetrics() it.defaultDisplay.getMetrics(dm) return dm.heightPixels } } fun getVectorForPreLollipop(resourceId: Int, activity: Context): Drawable? = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { VectorDrawableCompat.create(activity.resources, resourceId, activity.theme) } else { activity.resources.getDrawable(resourceId, activity.theme) } fun setVectorForPreLollipop(textView: TextView, resourceId: Int, activity: Context, position: ApplicationConstants) { val icon = getVectorForPreLollipop(resourceId, activity) when (position) { ApplicationConstants.DRAWABLE_LEFT -> textView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null) ApplicationConstants.DRAWABLE_RIGHT -> textView.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null) ApplicationConstants.DRAWABLE_TOP -> textView.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null) ApplicationConstants.DRAWABLE_BOTTOM -> textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, icon) } } }
mit
e0f58ee32a110f10765a6d8f4ab91782
41.591837
124
0.716203
5.100244
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsExpr.kt
2
4462
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* /** * Extracts [RsLitExpr] raw value */ val RsLitExpr.stringLiteralValue: String? get() = (kind as? RsTextLiteral)?.value enum class UnaryOperator { REF, // `&a` REF_MUT, // `&mut a` DEREF, // `*a` MINUS, // `-a` NOT, // `!a` BOX, // `box a` } val RsUnaryExpr.operatorType: UnaryOperator get() = when { mut != null -> UnaryOperator.REF_MUT and != null -> UnaryOperator.REF mul != null -> UnaryOperator.DEREF minus != null -> UnaryOperator.MINUS excl != null -> UnaryOperator.NOT box != null -> UnaryOperator.BOX else -> error("Unknown unary operator type: `$text`") } sealed class BinaryOperator sealed class ArithmeticOp(val traitName: String, val itemName: String, val sign: String) : BinaryOperator() { object ADD : ArithmeticOp("Add", "add", "+") // `a + b` object SUB : ArithmeticOp("Sub", "sub", "-") // `a - b` object MUL : ArithmeticOp("Mul", "mul", "*") // `a * b` object DIV : ArithmeticOp("Div", "div", "/") // `a / b` object REM : ArithmeticOp("Rem", "rem", "%") // `a % b` object BIT_AND : ArithmeticOp("BitAnd", "bitand", "&") // `a & b` object BIT_OR : ArithmeticOp("BitOr", "bitor", "|") // `a | b` object BIT_XOR : ArithmeticOp("BitXor", "bitxor", "^") // `a ^ b` object SHL : ArithmeticOp("Shl", "shl", "<<") // `a << b` object SHR : ArithmeticOp("Shr", "shr", ">>") // `a >> b operator fun component1(): String = traitName operator fun component2(): String = itemName operator fun component3(): String = sign companion object { fun values(): List<ArithmeticOp> = listOf(ADD, SUB, MUL, DIV, REM, BIT_AND, BIT_OR, BIT_XOR, SHL, SHR) } } sealed class BoolOp : BinaryOperator() sealed class LogicOp : BoolOp() { object AND : LogicOp() // `a && b` object OR : LogicOp() // `a || b` } sealed class ComparisonOp : BoolOp() { object EQ : ComparisonOp() // `a == b` object EXCLEQ : ComparisonOp() // `a != b` object LT : ComparisonOp() // `a < b` object LTEQ : ComparisonOp() // `a <= b` object GT : ComparisonOp() // `a > b` object GTEQ : ComparisonOp() // `a >= b` } sealed class AssignmentOp : BinaryOperator() { object EQ : AssignmentOp() // `a = b` object ANDEQ : AssignmentOp() // `a &= b` object OREQ : AssignmentOp() // `a |= b` object PLUSEQ : AssignmentOp() // `a += b` object MINUSEQ : AssignmentOp() // `a -= b` object MULEQ : AssignmentOp() // `a *= b` object DIVEQ : AssignmentOp() // `a /= b` object REMEQ : AssignmentOp() // `a %= b` object XOREQ : AssignmentOp() // `a ^= b` object GTGTEQ : AssignmentOp() // `a >>= b` object LTLTEQ : AssignmentOp() // `a <<= b` } val RsBinaryExpr.operator: PsiElement get() = requireNotNull(node.findChildByType(BINARY_OPS)) { "guaranteed to be not-null by parser" }.psi val RsBinaryExpr.operatorType: BinaryOperator get() = when (operator.elementType) { PLUS -> ArithmeticOp.ADD MINUS -> ArithmeticOp.SUB MUL -> ArithmeticOp.MUL DIV -> ArithmeticOp.DIV REM -> ArithmeticOp.REM AND -> ArithmeticOp.BIT_AND OR -> ArithmeticOp.BIT_OR XOR -> ArithmeticOp.BIT_XOR LTLT -> ArithmeticOp.SHL GTGT -> ArithmeticOp.SHR ANDAND -> LogicOp.AND OROR -> LogicOp.OR EQEQ -> ComparisonOp.EQ EXCLEQ -> ComparisonOp.EXCLEQ GT -> ComparisonOp.GT LT -> ComparisonOp.LT LTEQ -> ComparisonOp.LTEQ GTEQ -> ComparisonOp.GTEQ EQ -> AssignmentOp.EQ ANDEQ -> AssignmentOp.ANDEQ OREQ -> AssignmentOp.OREQ PLUSEQ -> AssignmentOp.PLUSEQ MINUSEQ -> AssignmentOp.MINUSEQ MULEQ -> AssignmentOp.MULEQ DIVEQ -> AssignmentOp.DIVEQ REMEQ -> AssignmentOp.REMEQ XOREQ -> AssignmentOp.XOREQ GTGTEQ -> AssignmentOp.GTGTEQ LTLTEQ -> AssignmentOp.LTLTEQ else -> error("Unknown binary operator type: `$text`") } private val BINARY_OPS = tokenSetOf( AND, ANDEQ, DIV, DIVEQ, EQ, EQEQ, EXCLEQ, GT, LT, MINUS, MINUSEQ, MUL, MULEQ, OR, OREQ, PLUS, PLUSEQ, REM, REMEQ, XOR, XOREQ, GTGTEQ, GTGT, GTEQ, LTLTEQ, LTLT, LTEQ, OROR, ANDAND )
mit
7fdc6c9affaa9a93bf20e746d91e5194
27.062893
110
0.604886
3.388003
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/models/HeadToHead.kt
1
1330
package com.garpr.android.data.models import android.os.Parcel import android.os.Parcelable import com.garpr.android.extensions.createParcel import com.garpr.android.extensions.requireAbsPlayer import com.garpr.android.extensions.writeAbsPlayer import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class HeadToHead( @Json(name = "opponent") val opponent: AbsPlayer, @Json(name = "player") val player: AbsPlayer, @Json(name = "losses") val losses: Int = 0, @Json(name = "wins") val wins: Int = 0, @Json(name = "matches") val matches: List<TournamentMatch>? = null ) : Parcelable { override fun describeContents(): Int = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeAbsPlayer(opponent, flags) dest.writeAbsPlayer(player, flags) dest.writeInt(losses) dest.writeInt(wins) dest.writeTypedList(matches) } companion object { @JvmField val CREATOR = createParcel { HeadToHead( it.requireAbsPlayer(), it.requireAbsPlayer(), it.readInt(), it.readInt(), it.createTypedArrayList(TournamentMatch.CREATOR) ) } } }
unlicense
152aa83ce6edfb19cd3bb63ec7690f65
29.930233
74
0.630075
4.318182
false
false
false
false
http4k/http4k
http4k-security/oauth/src/main/kotlin/org/http4k/security/OAuthRedirectionFilter.kt
1
2390
package org.http4k.security import org.http4k.core.Filter import org.http4k.core.HttpHandler import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.TEMPORARY_REDIRECT import org.http4k.core.Uri import org.http4k.core.with import org.http4k.lens.Header.LOCATION import org.http4k.security.CrossSiteRequestForgeryToken.Companion.SECURE_CSRF import org.http4k.security.Nonce.Companion.SECURE_NONCE import org.http4k.security.ResponseType.CodeIdToken import org.http4k.security.oauth.server.AuthRequest import org.http4k.security.oauth.server.ClientId class OAuthRedirectionFilter( private val providerConfig: OAuthProviderConfig, private val callbackUri: Uri, private val scopes: List<String>, private val generateCrsf: CsrfGenerator = SECURE_CSRF, private val nonceGenerator: NonceGenerator = SECURE_NONCE, private val modifyState: (Uri) -> Uri, private val oAuthPersistence: OAuthPersistence, private val responseType: ResponseType, private val redirectionBuilder: RedirectionUriBuilder = defaultUriBuilder, private val originalUri: (Request) -> Uri = Request::uri ) : Filter { override fun invoke(next: HttpHandler): HttpHandler = { if (oAuthPersistence.retrieveToken(it) != null) next(it) else { val csrf = generateCrsf(it) val state = State(csrf.value) val nonce = generateNonceIfRequired() val authRequest = AuthRequest( ClientId(providerConfig.credentials.user), scopes, callbackUri, state, responseType, nonce ) val redirect = Response(TEMPORARY_REDIRECT) .with(LOCATION of modifyState(redirectionBuilder(providerConfig.authUri, authRequest, state, nonce))) assignNonceIfRequired( oAuthPersistence.assignOriginalUri( oAuthPersistence.assignCsrf(redirect, csrf), originalUri(it) ), nonce ) } } private fun generateNonceIfRequired() = if (responseType == CodeIdToken) nonceGenerator.invoke() else null private fun assignNonceIfRequired(redirect: Response, nonce: Nonce?): Response = if (nonce != null) oAuthPersistence.assignNonce(redirect, nonce) else redirect }
apache-2.0
e0456520d3e4eb2457fac8a21e61b1c3
38.180328
117
0.691213
4.484053
false
true
false
false
tipsy/javalin
javalin/src/main/java/io/javalin/plugin/metrics/MicrometerPlugin.kt
1
3806
/* * Javalin - https://javalin.io * Copyright 2020 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin.plugin.metrics import io.javalin.Javalin import io.javalin.core.plugin.Plugin import io.javalin.core.util.OptionalDependency import io.javalin.core.util.Util import io.javalin.http.Context import io.javalin.http.ExceptionHandler import io.javalin.http.HandlerType import io.micrometer.core.instrument.MeterRegistry import io.micrometer.core.instrument.Metrics import io.micrometer.core.instrument.Tag import io.micrometer.core.instrument.Tags import io.micrometer.core.instrument.binder.http.DefaultHttpServletRequestTagsProvider import io.micrometer.core.instrument.binder.jetty.JettyConnectionMetrics import io.micrometer.core.instrument.binder.jetty.JettyServerThreadPoolMetrics import io.micrometer.core.instrument.binder.jetty.TimedHandler import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class MicrometerPlugin @JvmOverloads constructor( private val registry: MeterRegistry = Metrics.globalRegistry, private val tags: Iterable<Tag> = Tags.empty(), private val tagExceptionName: Boolean = false, private val tagRedirectPaths: Boolean = false, private val tagNotFoundMappedPaths: Boolean = false ) : Plugin { override fun apply(app: Javalin) { Util.ensureDependencyPresent(OptionalDependency.MICROMETER) app.jettyServer()?.server()?.let { server -> if (tagExceptionName) { app.exception(Exception::class.java, EXCEPTION_HANDLER) } server.insertHandler(TimedHandler(registry, tags, object : DefaultHttpServletRequestTagsProvider() { override fun getTags(request: HttpServletRequest, response: HttpServletResponse): Iterable<Tag> { val exceptionName = if (tagExceptionName) { response.getHeader(EXCEPTION_HEADER) } else { "Unknown" } val pathInfo = request.pathInfo.removePrefix(app._conf.contextPath).prefixIfNot("/") response.setHeader(EXCEPTION_HEADER, null) val handlerType = HandlerType.valueOf(request.method) val uri = app.javalinServlet().matcher.findEntries(handlerType, pathInfo).asSequence() .map { it.path } .map { if (it == "/" || it.isBlank()) "root" else it } .map { if (!tagRedirectPaths && response.status in 300..399) "REDIRECTION" else it } .map { if (!tagNotFoundMappedPaths && response.status == 404) "NOT_FOUND" else it } .firstOrNull() ?: "NOT_FOUND" return Tags.concat( super.getTags(request, response), "uri", uri, "exception", exceptionName ?: "None" ) } })) JettyServerThreadPoolMetrics(server.threadPool, tags).bindTo(registry) app.events { it.serverStarted { JettyConnectionMetrics.addToAllConnectors(server, registry, tags) } } } } companion object { private const val EXCEPTION_HEADER = "__micrometer_exception_name" var EXCEPTION_HANDLER = ExceptionHandler { e: Exception, ctx: Context -> val simpleName = e.javaClass.simpleName ctx.header(EXCEPTION_HEADER, simpleName.ifBlank { e.javaClass.name }) ctx.status(500) } } private fun String.prefixIfNot(prefix: String) = if (this.startsWith(prefix)) this else "$prefix$this" }
apache-2.0
a9636699dcce8995cfd653a11902dbc2
43.764706
113
0.640736
4.762203
false
false
false
false
MusikPolice/funopoly
src/main/kotlin/ca/jonathanfritz/funopoly/game/board/Deck.kt
1
325
package ca.jonathanfritz.funopoly.game.board class Deck<T>( private var cards: List<T>, private var index: Int = 0 ) { fun draw(): T { if (index == cards.size) { index = 0 } if (index == 0) { cards = cards.shuffled() } return cards[index++] } }
gpl-3.0
afc0df2dff7c714739a9eede0d2c7e58
19.375
44
0.492308
3.571429
false
false
false
false
GreaseMonk/android-timetable
timetable/src/main/java/nl/greasemonk/timetable/SpannableBar.kt
1
16113
/* * Copyright (c) 2018 . * This file is released under the Apache-2.0 license and part of the TimeTable repository located at: * https://github.com/greasemonk/android-timetable-core * See the "LICENSE" file at the root of the repository or go to the address below for the full license details. * https://github.com/GreaseMonk/android-timetable-core/blob/develop/LICENSE */ package nl.greasemonk.timetable import android.annotation.TargetApi import android.content.Context import android.graphics.* import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RoundRectShape import android.os.Build import android.util.AttributeSet import android.view.View import android.widget.Toast import androidx.annotation.IntRange /** * Created by Wiebe Geertsma on 10-11-2016. * * @see [SpannableBar on Github](https://github.com/GreaseMonk/SpannableBar) * * @see [Issue tracker](https://github.com/GreaseMonk/SpannableBar/issues) * <br></br><br></br> * SpannableBar is a Grid-style spannable bar, that is useful when you need a way to span a bar over columns. * The view allows you to set the starting column, the span, the number of columns, and more. */ class SpannableBar : View { private var text: String? = null private var start = DEFAULT_START private var span = DEFAULT_SPAN private var columnCount = DEFAULT_COLUMN_COUNT private var textColor = DEFAULT_TEXT_COLOR private var color = DEFAULT_BAR_COLOR private var textSize = DEFAULT_TEXT_SIZE_SP private var scaledDensity: Float = 0.toFloat() private var radius: Float = 0.toFloat() private var textPaint: Paint? = null private var linePaint: Paint? = null private var drawable: ShapeDrawable? = null private var drawCells = false private var renderToSides = true private var columnColors: MutableMap<Int, Paint>? = null private var bounds = Rect() /** * An array of 8 radius values, for the outer roundrect. * The first two floats are for the top-left corner (remaining pairs correspond clockwise). * For no rounded corners on the outer rectangle, pass null. * * @see [RoundRectShape](https://developer.android.com/reference/android/graphics/drawable/shapes/RoundRectShape.html) */ private var radii = floatArrayOf(radius, radius, radius, radius, radius, radius, radius, radius) //region CONSTRUCTORS constructor(context: Context) : super(context) { init(context, null) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context, attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context, attrs) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context, attrs) } //endregion private fun init(context: Context, attrs: AttributeSet?) { if (attrs != null) { val typedArray = context.theme.obtainStyledAttributes( attrs, R.styleable.SpannableBar, 0, 0) try { text = typedArray.getString(R.styleable.SpannableBar_barText) color = typedArray.getColor(R.styleable.SpannableBar_barColor, DEFAULT_BAR_COLOR) textColor = typedArray.getColor(R.styleable.SpannableBar_barTextColor, Color.WHITE) textSize = typedArray.getDimensionPixelSize(R.styleable.SpannableBar_barTextSize, DEFAULT_TEXT_SIZE_SP) start = Math.abs(typedArray.getInteger(R.styleable.SpannableBar_barStart, DEFAULT_START)) span = Math.abs(typedArray.getInteger(R.styleable.SpannableBar_barSpan, DEFAULT_SPAN)) columnCount = Math.abs(typedArray.getInteger(R.styleable.SpannableBar_barColumns, DEFAULT_COLUMN_COUNT)) } finally { typedArray.recycle() } } correctValues() columnColors = HashMap<Int, Paint>() scaledDensity = context.resources.displayMetrics.scaledDensity val typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL) textPaint = Paint() textPaint!!.color = textColor textPaint!!.textSize = scaledDensity * textSize textPaint!!.textAlign = Paint.Align.CENTER textPaint!!.typeface = typeface textPaint!!.isAntiAlias = true linePaint = Paint() linePaint!!.color = Color.GRAY linePaint!!.alpha = 125 setOnClickListener { if (text != null) Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show() } setRadius(DEFAULT_RADIUS) requestLayout() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val colWidth = width / columnCount if (drawCells) { // Draw the grid for this row // Draw a line along the bottom border // canvas.drawLine(0, getHeight()-2, getWidth(), getHeight(), linePaint); // Draw the columns for (i in 0..columnCount) { val x: Float = i * colWidth.toFloat() canvas.drawLine(x, 0f, x, height.toFloat(), linePaint!!) } } // Draw the column background colors if (columnColors != null) { for (key in columnColors!!.keys) { // Get coordinates without padding val left: Float = key * colWidth.toFloat() val top: Float = 0f val right: Float = left + colWidth val bottom: Float = height.toFloat() canvas.drawRect(left, top, right, bottom, columnColors!![key]!!) } } if (span > 0) { val fromStart = start == 0 val toEnd = start + span == columnCount val coordLeft = (if (renderToSides && fromStart) 0 else paddingLeft) + start * colWidth val coordTop = paddingTop var coordRight = coordLeft + span * colWidth if (renderToSides) { if (!fromStart) coordRight -= paddingLeft if (!toEnd) coordRight -= paddingRight //(renderToSides ? (fromStart ? 0 : getPaddingLeft()) - (toEnd ? 0 : getPaddingRight()) : 0); } val coordBottom = height - paddingBottom // Remove the corner radii if the bar spans to the sides if (renderToSides) { val removeLeftRadii = start == 0 val removeRightRadii = start + span == columnCount radii[0] = if (removeLeftRadii) 0f else radius // Top left radii[1] = if (removeLeftRadii) 0f else radius radii[2] = if (removeRightRadii) 0f else radius // Top right radii[3] = if (removeRightRadii) 0f else radius radii[4] = if (removeRightRadii) 0f else radius // Bottom right radii[5] = if (removeRightRadii) 0f else radius radii[6] = if (removeLeftRadii) 0f else radius // Bottom left radii[7] = if (removeLeftRadii) 0f else radius } drawable!!.paint.color = color drawable!!.setBounds(coordLeft, coordTop, coordRight, coordBottom) drawable!!.draw(canvas) // Only make a drawcall if there is actually something to draw. if (text != null && !text!!.isEmpty()) { var textCoordX: Float = (paddingLeft + coordLeft).toFloat() val textBaselineToCenter: Float = Math.abs(Math.round((textPaint!!.descent() + textPaint!!.ascent()) / 2)).toFloat() val textBaselineCoordY: Float = height / 2 + textBaselineToCenter var characters = text!!.length textPaint!!.getTextBounds(text, 0, characters, bounds) while (bounds.right > coordRight - coordLeft) { textPaint!!.getTextBounds(text, 0, characters, bounds) characters-- } var displayedText: String = text ?: "" if (characters != text!!.length && characters > 3) { displayedText = text!!.substring(0, characters - 3) + "..." } textCoordX += bounds.width() / 2 if (characters == text!!.length && coordRight > 0) // prevent division by zero { textCoordX -= bounds.width() / 2 textCoordX += (coordRight - coordLeft) / 2 } canvas.drawText(displayedText, 0, displayedText.length, textCoordX, textBaselineCoordY, textPaint!!) } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val desiredWidth = 100 val desiredHeight = 100 val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val width: Int val height: Int // Measure width if (widthMode == MeasureSpec.EXACTLY) width = widthSize else if (widthMode == MeasureSpec.AT_MOST) width = Math.min(desiredWidth, widthSize) else width = desiredWidth // Measure height if (heightMode == MeasureSpec.EXACTLY) height = heightSize else if (heightMode == MeasureSpec.AT_MOST) height = Math.min(desiredHeight, heightSize) else height = desiredHeight setMeasuredDimension(width, height) } /** * Correct the start, span, and column count where needed. */ private fun correctValues() { // Make sure to set values to zero if it was set below that. start = Math.max(0, start) span = Math.max(0, span) columnCount = Math.max(0, columnCount) if (columnColors != null) { val iterator = columnColors!!.keys.iterator() while (iterator.hasNext()) { val key = iterator.next() if (key > columnCount) columnColors!!.remove(key) } } // Make sure the span vale is correct. if (start + span > columnCount) { if (start <= columnCount) span = columnCount - start if (start >= columnCount) start = columnCount - 1 } } //region GETTERS & SETTERS /** * Set a column's cell background color. * * @param row the row to apply the color to * @param color the color to apply */ fun setColumnColor(row: Int, color: Int) { val paint = Paint() paint.color = color columnColors!![row] = paint } /** * Removes all coloring that was previously applied to any column. */ fun removeColumnColors() { columnColors!!.clear() } /** * Removes the column color of a specific row. * * @param row the row to remove the column color of. */ fun removeColumnColor(row: Int) { if (columnColors == null) return if (columnColors!!.containsKey(row)) columnColors!!.remove(row) } /** * Sets all the required properties of the bar in one go. * Any values will be corrected for you, for example: * start = 3, span = 7, columnCount = 7, will have it's span corrected to 4. * Any values below zero will be automatically corrected to zero. * * @param start the start column of the bar (0 to columnCount) * @param span the span of the bar * @param columnCount the amount of columns to set */ fun setProperties(@IntRange(from = 1) start: Int, @IntRange(from = 0) span: Int, @IntRange(from = 1) columnCount: Int) { this.start = start this.span = span this.columnCount = columnCount correctValues() invalidate() } /** * Set the amount of columnCount * * @param numColumns the amount of columnCount to set */ fun setColumnCount(@IntRange(from = 0) numColumns: Int) { columnCount = numColumns correctValues() invalidate() } /** * Set the displayed text. The view will automatically be invalidated. * * @param text the text to be displayed */ fun setText(text: String?) { this.text = text ?: "" invalidate() } /** * Set the desired starting column of the bar. Any amount that is higher than the span * will automatically limit itself to the value of columnCount. * If you have set the amount of columns to 7, use 0-6. * * @param start the start column of the bar (0 to columnCount) */ fun setStart(@IntRange(from = 0) start: Int) { this.start = start correctValues() invalidate() } /** * Set the bar's span. This is the actual span, * so a value of 1 will show a bar with one column filled. * * @param span the span to set the bar to. */ fun setSpan(@IntRange(from = 0) span: Int) { this.span = span correctValues() invalidate() } /** * Set the bar's corner radius * * @param radius the radius to set */ fun setRadius(radius: Float) { this.radius = scaledDensity * radius + 0.5f this.radii = floatArrayOf(radius, radius, radius, radius, radius, radius, radius, radius) drawable = ShapeDrawable(RoundRectShape(radii, null, null)) invalidate() } /** * Set the bar text size. Values that are zero or below will be brought back up to 1. * * @param sp */ fun setTextSize(@IntRange(from = 1) sp: Int) { this.textSize = Math.max(1, sp) textPaint!!.textSize = scaledDensity * this.textSize invalidate() } /** * Set the bar color * * @param color the color to set the bar to, such as Color.WHITE. */ fun setColor(color: Int) { this.color = color invalidate() } /** * Set the text alignment * * @param align the alignment of the text to set. */ fun setTextAlignment(align: Paint.Align) { textPaint!!.textAlign = align invalidate() } /** * Shows additional lines along the outline of each cell. * * @param show set to TRUE to show cell lines */ fun setShowCellLines(show: Boolean) { this.drawCells = show invalidate() } /** * Set the cell lines color * * @param color the color to set the cell lines to. */ fun setCellLineColor(color: Int) { this.linePaint!!.color = color invalidate() } /** * Set the text typeface, to set the desired font. * Default: Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD); * * @param typeface the typeface to assign to the text */ fun setTextTypeface(typeface: Typeface) { textPaint!!.typeface = typeface invalidate() } /** * The bar will automatically draw to the left and right edge of the * view (no rounded corners) if span == columnCount * * @param renderToSides TRUE to enable */ fun setRenderToSides(renderToSides: Boolean) { this.renderToSides = renderToSides } companion object { val DEFAULT_START = 0 val DEFAULT_SPAN = 7 val DEFAULT_COLUMN_COUNT = 7 // week view, 7 days val DEFAULT_RADIUS = 4f val DEFAULT_BAR_COLOR = Color.argb(128, 63, 81, 181) val DEFAULT_TEXT_SIZE_SP = 12 val DEFAULT_TEXT_COLOR = Color.WHITE } //endregion }
apache-2.0
7fb2ea204f079864d496ee756b9e2d65
33.067653
145
0.594675
4.498325
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/orchard_produce/AddOrchardProduceForm.kt
2
5724
package de.westnordost.streetcomplete.quests.orchard_produce import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AImageListQuestAnswerFragment import de.westnordost.streetcomplete.quests.orchard_produce.OrchardProduce.* import de.westnordost.streetcomplete.view.image_select.Item class AddOrchardProduceForm : AImageListQuestAnswerFragment<OrchardProduce, List<OrchardProduce>>() { private val produces = listOf( // ordered alphabetically here for overview. Produces are filtered and sorted by what is // found in the the country metadata Item(SISAL, R.drawable.produce_sisal, R.string.produce_sisal), Item(GRAPE, R.drawable.produce_grape, R.string.produce_grapes), Item(AGAVE, R.drawable.produce_agave, R.string.produce_agaves), Item(ALMOND, R.drawable.produce_almond, R.string.produce_almonds), Item(APPLE, R.drawable.produce_apple, R.string.produce_apples), Item(APRICOT, R.drawable.produce_apricot, R.string.produce_apricots), Item(ARECA_NUT, R.drawable.produce_areca_nut, R.string.produce_areca_nuts), Item(AVOCADO, R.drawable.produce_avocado, R.string.produce_avocados), Item(BANANA, R.drawable.produce_banana, R.string.produce_bananas), Item(SWEET_PEPPER, R.drawable.produce_bell_pepper, R.string.produce_sweet_peppers), Item(BLUEBERRY, R.drawable.produce_blueberry, R.string.produce_blueberries), Item(BRAZIL_NUT, R.drawable.produce_brazil_nut, R.string.produce_brazil_nuts), Item(CACAO, R.drawable.produce_cacao, R.string.produce_cacao), Item(CASHEW, R.drawable.produce_cashew, R.string.produce_cashew_nuts), Item(CHERRY, R.drawable.produce_cherry, R.string.produce_cherries), Item(CHESTNUT, R.drawable.produce_chestnut, R.string.produce_chestnuts), Item(CHILLI_PEPPER, R.drawable.produce_chili, R.string.produce_chili), Item(COCONUT, R.drawable.produce_coconut, R.string.produce_coconuts), Item(COFFEE, R.drawable.produce_coffee, R.string.produce_coffee), Item(CRANBERRY, R.drawable.produce_cranberry, R.string.produce_cranberries), Item(DATE, R.drawable.produce_date, R.string.produce_dates), Item(FIG, R.drawable.produce_fig, R.string.produce_figs), Item(GRAPEFRUIT, R.drawable.produce_grapefruit, R.string.produce_grapefruits), Item(GUAVA, R.drawable.produce_guava, R.string.produce_guavas), Item(HAZELNUT, R.drawable.produce_hazelnut, R.string.produce_hazelnuts), Item(HOP, R.drawable.produce_hop, R.string.produce_hops), Item(JOJOBA, R.drawable.produce_jojoba, R.string.produce_jojoba), Item(KIWI, R.drawable.produce_kiwi, R.string.produce_kiwis), Item(KOLA_NUT, R.drawable.produce_kola_nut, R.string.produce_kola_nuts), Item(LEMON, R.drawable.produce_lemon, R.string.produce_lemons), Item(LIME, R.drawable.produce_lime, R.string.produce_limes), Item(MANGO, R.drawable.produce_mango, R.string.produce_mangos), Item(MANGOSTEEN, R.drawable.produce_mangosteen, R.string.produce_mangosteen), Item(MATE, R.drawable.produce_mate, R.string.produce_mate), Item(NUTMEG, R.drawable.produce_nutmeg, R.string.produce_nutmeg), Item(OLIVE, R.drawable.produce_olive, R.string.produce_olives), Item(ORANGE, R.drawable.produce_orange, R.string.produce_oranges), Item(PALM_OIL, R.drawable.produce_palm_oil, R.string.produce_oil_palms), Item(PAPAYA, R.drawable.produce_papaya, R.string.produce_papayas), Item(PEACH, R.drawable.produce_peach, R.string.produce_peaches), Item(PEAR, R.drawable.produce_pear, R.string.produce_pears), Item(PEPPER, R.drawable.produce_pepper, R.string.produce_pepper), Item(PERSIMMON, R.drawable.produce_persimmon, R.string.produce_persimmons), Item(PINEAPPLE, R.drawable.produce_pineapple, R.string.produce_pineapples), Item(PISTACHIO, R.drawable.produce_pistachio, R.string.produce_pistachios), Item(PLUM, R.drawable.produce_plum, R.string.produce_plums), Item(RASPBERRY, R.drawable.produce_raspberry, R.string.produce_raspberries), Item(RUBBER, R.drawable.produce_rubber, R.string.produce_rubber), Item(STRAWBERRY, R.drawable.produce_strawberry, R.string.produce_strawberries), Item(TEA, R.drawable.produce_tea, R.string.produce_tea), Item(TOMATO, R.drawable.produce_tomato, R.string.produce_tomatoes), Item(TUNG_NUT, R.drawable.produce_tung_nut, R.string.produce_tung_nuts), Item(VANILLA, R.drawable.produce_vanilla, R.string.produce_vanilla), Item(WALNUT, R.drawable.produce_walnut, R.string.produce_walnuts) ) private val producesMap = produces.associateBy { it.value!!.osmValue } // only include what is given for that country override val items get() = countryInfo.orchardProduces.mapNotNull { producesMap[it] } override val itemsPerRow = 3 override val maxSelectableItems = -1 override fun onClickOk(selectedItems: List<OrchardProduce>) { applyAnswer(selectedItems) } }
gpl-3.0
ee6aa29fbead5b16f7c5c6372d49367a
69.666667
101
0.645702
3.333722
false
false
false
false
songzhw/Hello-kotlin
Advanced_hm/src/main/kotlin/ca/six/kjdemo/proxy/kt/DelegateDemo.kt
1
896
package ca.six.kjdemo.proxy.kt interface IWorkJob { fun work() fun despcription() } class FetchDataWorkJob : IWorkJob { override fun work() { println("http working...") } override fun despcription() { println("I'm fetch") } } class LogWrapper(val bizJob: IWorkJob) : IWorkJob by bizJob { override fun work() { println("=== before log === (${System.currentTimeMillis()})") bizJob.work() println("=== after log === (${System.currentTimeMillis()})") } } fun main() { val fetcher = FetchDataWorkJob() val worker = LogWrapper(fetcher) worker.work() worker.despcription() } /* === before log === (1585841097667) http working... === after log === (1585841097667) I'm fetch === before log === (1585842176441) http working... === after log === (1585842176441) TimeWrapper : consume time = 0ms I'm fetch */
apache-2.0
572b57dc1ab909fec88b46737c7e8e1a
17.6875
69
0.610491
3.541502
false
false
false
false
hubme/WorkHelperApp
javalib/src/main/java/com/example/concurrent/blockingqueue/delayqueue/DelayQueueSample.kt
1
1766
package com.example.concurrent.blockingqueue.delayqueue import java.util.concurrent.DelayQueue import java.util.concurrent.Delayed import java.util.concurrent.TimeUnit /** * @author VanceKing * @since 2019/10/17. */ fun main() { test1() } fun test1() { val queue = DelayQueue<Message>() queue.offer(Message("id-1", "msg_1", 6)) queue.offer(Message("id-2", "msg_2", 2)) queue.offer(Message("id-3", "msg_3", 5)) queue.offer(Message("id-4", "msg_4", 1)) Thread(Consumer(queue)).start() } private class Message(private val id: String, private val message: String, private val delayDuration: Long) : Delayed { val time: Long = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(delayDuration) override fun getDelay(unit: TimeUnit): Long { return unit.convert(this.time - System.currentTimeMillis(), TimeUnit.MILLISECONDS) } override fun compareTo(other: Delayed): Int { return (this.time - (other as Message).time).toInt() } override fun toString(): String { return "Message{" + "id=" + id + ", message='" + message + '\''.toString() + ", time=" + time + '}'.toString() + System.currentTimeMillis() } } private class Consumer(private val queue: DelayQueue<Message>) : Runnable { override fun run() { println("开始获取消息: " + System.currentTimeMillis()) while (true) { try { val message = queue.take() println("消费消息: $message") if (queue.isEmpty()) { break } } catch (e: InterruptedException) { e.printStackTrace() } } } }
apache-2.0
d4189c452a33339b8c39fffece398225
25.861538
119
0.576174
4.013793
false
false
false
false
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Model/ModelLaser.kt
1
2013
package antimattermod.core.Model import net.minecraft.client.model.ModelBase import net.minecraft.client.model.ModelRenderer import net.minecraft.entity.Entity /** * @author kojin15. */ class ModelLaser : ModelBase() { internal var xLine: ModelRenderer? = null internal var yLine: ModelRenderer? = null internal var zLine: ModelRenderer? = null init { textureWidth = 64 textureHeight = 32 xLine = ModelRenderer(this, 0, 0) xLine!!.addBox(-8f, -1f, -1f, 16, 2, 2) xLine!!.setRotationPoint(0f, 16f, 0f) xLine!!.setTextureSize(64, 32) xLine!!.mirror = true setRotation(xLine, 0.0349066f, 0f, 0f) yLine = ModelRenderer(this, 0, 0) yLine!!.addBox(-1f, -8f, -1f, 2, 16, 2) yLine!!.setRotationPoint(0f, 16f, 0f) yLine!!.setTextureSize(64, 32) yLine!!.mirror = true setRotation(yLine, 0f, 0f, 0f) zLine = ModelRenderer(this, 0, 0) zLine!!.addBox(-1f, -1f, -8f, 2, 2, 16) zLine!!.setRotationPoint(0f, 16f, 0f) zLine!!.setTextureSize(64, 32) zLine!!.mirror = true setRotation(zLine, 0f, 0f, 0f) } override fun render(entity: Entity, f: Float, f1: Float, f2: Float, f3: Float, f4: Float, f5: Float) { super.render(entity, f, f1, f2, f3, f4, f5) setRotationAngles(f, f1, f2, f3, f4, f5) xLine!!.render(f5) yLine!!.render(f5) zLine!!.render(f5) } fun renderXLine(f: Float) { xLine!!.render(f) } fun renderYLine(f: Float) { yLine!!.render(f) } fun renderZLine(f: Float) { zLine!!.render(f) } private fun setRotation(model: ModelRenderer?, x: Float, y: Float, z: Float) { model!!.rotateAngleX = x model.rotateAngleY = y model.rotateAngleZ = z } fun setRotationAngles(f: Float, f1: Float, f2: Float, f3: Float, f4: Float, f5: Float) { super.setRotationAngles(f, f1, f2, f3, f4, f5, null) } }
gpl-3.0
088848e9e1b657e8941b311a36e2e593
27.771429
106
0.588177
3.045386
false
false
false
false
hartwigmedical/hmftools
teal/src/main/kotlin/com/hartwig/hmftools/teal/TealConstants.kt
1
1154
package com.hartwig.hmftools.teal import com.hartwig.hmftools.common.utils.sv.ChrBaseRegion import htsjdk.samtools.util.SequenceUtil object TealConstants { const val DEFAULT_PARTITION_SIZE = 10000000 const val DEFAULT_MIN_TELE_SEQ_COUNT = 2 const val POLY_G_THRESHOLD = 0.9 const val CANONICAL_TELOMERE_SEQ = "TTAGGG" // NOTE: cannot use TealUtils.reverseComplementSeq, cause we would run into static initialisation // ordering issue, since TealUtils uses TealConstants val CANONICAL_TELOMERE_SEQ_REV = SequenceUtil.reverseComplement("TTAGGG") val TELOMERE_HEXAMERS: Array<String> = arrayOf( CANONICAL_TELOMERE_SEQ, "TCAGGG", "TTCGGG", "GTAGGG", "TGAGGG", "TTGGGG", "TAAGGG", "ATAGGG", "CTAGGG", "TTTGGG" ) val TELOMERE_HEXAMERS_REV: Array<String> = TELOMERE_HEXAMERS.map({ obj: String -> SequenceUtil.reverseComplement(obj) }).toTypedArray() val CANONICAL_TELOMERE_SEQUENCES = arrayOf( CANONICAL_TELOMERE_SEQ.repeat(DEFAULT_MIN_TELE_SEQ_COUNT), CANONICAL_TELOMERE_SEQ_REV.repeat(DEFAULT_MIN_TELE_SEQ_COUNT)) }
gpl-3.0
90195dad62e949d1ea4b1d040b553ba4
34
139
0.689775
3.250704
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/util/common/AnimationStarter.kt
1
1605
/* Copyright 2013 Dániel Sólyom 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 ds.violin.v1.util.common import android.graphics.drawable.AnimationDrawable import android.os.Handler import android.view.View import android.widget.ImageView object AnimationStarter { fun start(view: ImageView) { val aDrawable = view.drawable as? AnimationDrawable if (aDrawable != null) { // stupid stupid way - but no animation otherwise val handler = Handler() object : Thread() { override fun run() { handler.post { if (view.visibility == View.VISIBLE) { aDrawable.start() } } } }.start() } } fun start(animation: AnimationDrawable) { // stupid stupid way - but no animation otherwise val handler = Handler() object : Thread() { override fun run() { handler.post { animation.start() } } }.start() } }
apache-2.0
719ed7d470e1baa09752068061644ef5
27.625
73
0.604492
4.646377
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/helpers/PlayerBehavior.kt
1
3551
package org.videolan.vlc.gui.helpers import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class PlayerBehavior<V : View> : com.google.android.material.bottomsheet.BottomSheetBehavior<V> { private var lock = false constructor() { isHideable = true } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) fun lock(lock: Boolean) { this.lock = lock } override fun onInterceptTouchEvent(parent: CoordinatorLayout, child: V, event: MotionEvent): Boolean { if (lock) return false try { return super.onInterceptTouchEvent(parent, child, event) } catch (ignored: NullPointerException) { // BottomSheetBehavior receives input events too soon and mNestedScrollingChildRef is not set yet. return false } } override fun onStopNestedScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, type: Int) { if (lock) return try { super.onStopNestedScroll(coordinatorLayout, child, target, type) } catch (ignored: NullPointerException) { } } override fun onStopNestedScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View) { if (lock) return try { super.onStopNestedScroll(coordinatorLayout, child, target) } catch (ignored: NullPointerException) { //Same crash, weakref not already set. } } override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) { if (lock) return try { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) } catch (ignored: NullPointerException) { //Same crash, weakref not already set. } } override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray) { if (lock) return try { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed) } catch (ignored: NullPointerException) { //Same crash, weakref not already set. } } override fun onNestedPreFling(coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float): Boolean { if (lock) return false try { return super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY) } catch (ignored: NullPointerException) { //Same crash, weakref not already set. } return false } override fun onLayoutChild(parent: CoordinatorLayout, child: V, layoutDirection: Int)= try { super.onLayoutChild(parent, child, layoutDirection) } catch (ignored: IndexOutOfBoundsException) { false } override fun onTouchEvent(parent: CoordinatorLayout, child: V, event: MotionEvent): Boolean { if (lock) return false return try { super.onTouchEvent(parent, child, event) } catch (ignored: NullPointerException) { false } } companion object { const val TAG = "VLC/BottomSheetBehavior" } }
gpl-2.0
ba28107bf460e93ede63fbed6d5b313e
32.186916
147
0.665446
4.945682
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpsAuthenticationTaskCallable.kt
1
3373
/* * Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.asynchronous.asynctasks.ftp.auth import com.amaze.filemanager.filesystem.ftp.FTPClientImpl import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTPS_URI_PREFIX import com.amaze.filemanager.utils.X509CertificateUtil import com.amaze.filemanager.utils.X509CertificateUtil.FINGERPRINT import net.schmizz.sshj.userauth.UserAuthException import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPSClient import org.json.JSONObject import javax.net.ssl.HostnameVerifier class FtpsAuthenticationTaskCallable( hostname: String, port: Int, private val certInfo: JSONObject, username: String, password: String ) : FtpAuthenticationTaskCallable(hostname, port, username, password) { override fun call(): FTPClient { val ftpClient = createFTPClient() as FTPSClient ftpClient.connectTimeout = NetCopyClientConnectionPool.CONNECT_TIMEOUT ftpClient.controlEncoding = Charsets.UTF_8.name() ftpClient.connect(hostname, port) val loginSuccess = if (username.isBlank() && password.isBlank()) { ftpClient.login( FTPClientImpl.ANONYMOUS, FTPClientImpl.generateRandomEmailAddressForLogin() ) } else { ftpClient.login(username, password) } return if (loginSuccess) { // RFC 2228 set protection buffer size to 0 ftpClient.execPBSZ(0) // RFC 2228 set data protection level to PRIVATE ftpClient.execPROT("P") ftpClient.enterLocalPassiveMode() ftpClient } else { throw UserAuthException("Login failed") } } @Suppress("LabeledExpression") override fun createFTPClient(): FTPClient { return ( NetCopyClientConnectionPool.ftpClientFactory.create(FTPS_URI_PREFIX) as FTPSClient ).apply { this.hostnameVerifier = HostnameVerifier { _, session -> return@HostnameVerifier if (session.peerCertificateChain.isNotEmpty()) { X509CertificateUtil.parse( session.peerCertificateChain.first() )[FINGERPRINT] == certInfo.get(FINGERPRINT) } else { false } } } } }
gpl-3.0
6cb97c513195a4fe5d2b5d6275d72053
39.154762
107
0.681886
4.626886
false
false
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/brvah/BaseBinderAdapter.kt
1
8895
package com.didichuxing.doraemonkit.widget.brvah import android.annotation.SuppressLint import android.util.SparseArray import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.didichuxing.doraemonkit.widget.brvah.binder.BaseItemBinder import com.didichuxing.doraemonkit.widget.brvah.viewholder.BaseViewHolder /** * 使用 Binder 来实现adapter,既可以实现单布局,也能实现多布局 * 数据实体类也不存继承问题 * * 当有多种条目的时候,避免在convert()中做太多的业务逻辑,把逻辑放在对应的 BaseItemBinder 中。 * 适用于以下情况: * 1、实体类不方便扩展,此Adapter的数据类型可以是任意类型,默认情况下不需要实现 getItemType * 2、item 类型较多,在convert()中管理起来复杂 * * ViewHolder 由 [BaseItemBinder] 实现,并且每个[BaseItemBinder]可以拥有自己类型的ViewHolder类型。 * * 数据类型为Any */ open class BaseBinderAdapter(list: MutableList<Any>? = null) : BaseQuickAdapter<Any, BaseViewHolder>(0, list) { /** * 用于存储每个 Binder 类型对应的 Diff */ private val classDiffMap = HashMap<Class<*>, DiffUtil.ItemCallback<Any>?>() private val mTypeMap = HashMap<Class<*>, Int>() private val mBinderArray = SparseArray<BaseItemBinder<Any, *>>() init { setDiffCallback(ItemCallback()) } /** * 添加 ItemBinder */ @JvmOverloads fun <T : Any> addItemBinder(clazz: Class<out T>, baseItemBinder: BaseItemBinder<T, *>, callback: DiffUtil.ItemCallback<T>? = null): BaseBinderAdapter { val itemType = mTypeMap.size + 1 mTypeMap[clazz] = itemType mBinderArray.append(itemType, baseItemBinder as BaseItemBinder<Any, *>) baseItemBinder._adapter = this callback?.let { classDiffMap[clazz] = it as DiffUtil.ItemCallback<Any> } return this } /** * kotlin 可以使用如下方法添加 ItemBinder,更加简单 */ inline fun <reified T : Any> addItemBinder(baseItemBinder: BaseItemBinder<T, *>, callback: DiffUtil.ItemCallback<T>? = null): BaseBinderAdapter { addItemBinder(T::class.java, baseItemBinder, callback) return this } override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { return getItemBinder(viewType).let { it._context = context it.onCreateViewHolder(parent, viewType) } } override fun convert(holder: BaseViewHolder, item: Any) { getItemBinder(holder.itemViewType).convert(holder, item) } override fun convert(holder: BaseViewHolder, item: Any, payloads: List<Any>) { getItemBinder(holder.itemViewType).convert(holder, item, payloads) } open fun getItemBinder(viewType: Int): BaseItemBinder<Any, BaseViewHolder> { val binder = mBinderArray[viewType] checkNotNull(binder) { "getItemBinder: viewType '$viewType' no such Binder found,please use addItemBinder() first!" } return binder as BaseItemBinder<Any, BaseViewHolder> } open fun getItemBinderOrNull(viewType: Int): BaseItemBinder<Any, BaseViewHolder>? { val binder = mBinderArray[viewType] return binder as? BaseItemBinder<Any, BaseViewHolder> } override fun getDefItemViewType(position: Int): Int { return findViewType(data[position].javaClass) } override fun bindViewClickListener(viewHolder: BaseViewHolder, viewType: Int) { super.bindViewClickListener(viewHolder, viewType) bindClick(viewHolder) bindChildClick(viewHolder, viewType) } override fun onViewAttachedToWindow(holder: BaseViewHolder) { super.onViewAttachedToWindow(holder) getItemBinderOrNull(holder.itemViewType)?.onViewAttachedToWindow(holder) } override fun onViewDetachedFromWindow(holder: BaseViewHolder) { super.onViewDetachedFromWindow(holder) getItemBinderOrNull(holder.itemViewType)?.onViewDetachedFromWindow(holder) } override fun onFailedToRecycleView(holder: BaseViewHolder): Boolean { return getItemBinderOrNull(holder.itemViewType)?.onFailedToRecycleView(holder) ?: false } protected fun findViewType(clazz : Class<*>):Int { val type = mTypeMap[clazz] checkNotNull(type) { "findViewType: ViewType: $clazz Not Find!" } return type } protected open fun bindClick(viewHolder: BaseViewHolder) { if (getOnItemClickListener() == null) { //如果没有设置点击监听,则回调给 itemProvider //Callback to itemProvider if no click listener is set viewHolder.itemView.setOnClickListener { var position = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnClickListener } position -= headerLayoutCount val itemViewType = viewHolder.itemViewType val binder = getItemBinder(itemViewType) binder.onClick(viewHolder, it, data[position], position) } } if (getOnItemLongClickListener() == null) { //如果没有设置长按监听,则回调给itemProvider // If you do not set a long press listener, callback to the itemProvider viewHolder.itemView.setOnLongClickListener { var position = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnLongClickListener false } position -= headerLayoutCount val itemViewType = viewHolder.itemViewType val binder = getItemBinder(itemViewType) binder.onLongClick(viewHolder, it, data[position], position) } } } protected open fun bindChildClick(viewHolder: BaseViewHolder, viewType: Int) { if (getOnItemChildClickListener() == null) { val provider = getItemBinder(viewType) val ids = provider.getChildClickViewIds() ids.forEach { id -> viewHolder.itemView.findViewById<View>(id)?.let { if (!it.isClickable) { it.isClickable = true } it.setOnClickListener { v -> var position: Int = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnClickListener } position -= headerLayoutCount provider.onChildClick(viewHolder, v, data[position], position) } } } } if (getOnItemChildLongClickListener() == null) { val provider = getItemBinder(viewType) val ids = provider.getChildLongClickViewIds() ids.forEach { id -> viewHolder.itemView.findViewById<View>(id)?.let { if (!it.isLongClickable) { it.isLongClickable = true } it.setOnLongClickListener { v -> var position: Int = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnLongClickListener false } position -= headerLayoutCount provider.onChildLongClick(viewHolder, v, data[position], position) } } } } } /** * Diff Callback */ private inner class ItemCallback : DiffUtil.ItemCallback<Any>() { override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean { if (oldItem.javaClass == newItem.javaClass) { classDiffMap[oldItem.javaClass]?.let { return it.areItemsTheSame(oldItem, newItem) } } return oldItem == newItem } @SuppressLint("DiffUtilEquals") override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean { if (oldItem.javaClass == newItem.javaClass) { classDiffMap[oldItem.javaClass]?.let { return it.areContentsTheSame(oldItem, newItem) } } return true } override fun getChangePayload(oldItem: Any, newItem: Any): Any? { if (oldItem.javaClass == newItem.javaClass) { return classDiffMap[oldItem.javaClass]?.getChangePayload(oldItem, newItem) } return null } } }
apache-2.0
e0c6499f404a524313cd51f559c1d5bb
36.201754
155
0.614196
5.00354
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/dependency/Netty.kt
2
1717
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.internal.dependency @Suppress("unused") object Netty { // https://github.com/netty/netty/releases private const val version = "4.1.72.Final" const val common = "io.netty:netty-common:${version}" const val buffer = "io.netty:netty-buffer:${version}" const val transport = "io.netty:netty-transport:${version}" const val handler = "io.netty:netty-handler:${version}" const val codecHttp = "io.netty:netty-codec-http:${version}" }
apache-2.0
4d501ec050a653344c0cd3b34dd5f073
44.184211
73
0.739662
4.147343
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/app/view/components/StatusComponent.kt
1
2747
/* Copyright 2015 Andreas Würl 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.blitzortung.android.app.view.components import android.app.Activity import android.view.View import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import org.blitzortung.android.alert.AlertLabel import org.blitzortung.android.alert.AlertLabelHandler import org.blitzortung.android.alert.event.AlertEvent import org.blitzortung.android.alert.event.AlertResultEvent import org.blitzortung.android.app.R class StatusComponent(activity: Activity) : AlertLabel { private val alertLabelHandler: AlertLabelHandler val alertEventConsumer: (AlertEvent) -> Unit private val status: TextView private val warning: TextView private val progressBar: ProgressBar private val errorIndicator: ImageView init { status = activity.findViewById(R.id.status) as TextView warning = activity.findViewById(R.id.warning) as TextView progressBar = (activity.findViewById(R.id.progress) as ProgressBar).apply { visibility = View.INVISIBLE } errorIndicator = (activity.findViewById(R.id.error_indicator) as ImageView).apply { visibility = View.INVISIBLE } alertLabelHandler = AlertLabelHandler(this, activity.resources) alertEventConsumer = { event -> alertLabelHandler.apply( if (event is AlertResultEvent) event.alertResult else null) } } fun startProgress() { progressBar.visibility = View.VISIBLE progressBar.progress = 0 } fun stopProgress() { progressBar.visibility = View.INVISIBLE progressBar.progress = progressBar.max } fun indicateError(indicateError: Boolean) { errorIndicator.visibility = if (indicateError) View.VISIBLE else View.INVISIBLE } fun setText(statusText: String) { status.text = statusText } override fun setAlarmTextColor(color: Int) { warning.setTextColor(color) } override fun setAlarmText(alarmText: String) { warning.text = alarmText } }
apache-2.0
b7cd12a217b7c9670bcd65f0c6ae76df
27.905263
91
0.695921
4.759099
false
false
false
false
arturbosch/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/RuleSet.kt
1
1309
package io.gitlab.arturbosch.detekt.api import io.gitlab.arturbosch.detekt.api.internal.BaseRule import io.gitlab.arturbosch.detekt.api.internal.PathFilters import io.gitlab.arturbosch.detekt.api.internal.validateIdentifier import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext typealias RuleSetId = String /** * A rule set is a collection of rules and must be defined within a rule set provider implementation. */ class RuleSet(val id: RuleSetId, val rules: List<BaseRule>) { init { validateIdentifier(id) } /** * Is used to determine if a given [KtFile] should be analyzed at all. */ @Deprecated("Exposes detekt-core implementation details.") var pathFilters: PathFilters? = null /** * Visits given file with all rules of this rule set, returning a list * of all code smell findings. */ @Suppress("DEPRECATION") @Deprecated("Exposes detekt-core implementation details.") fun accept(file: KtFile, bindingContext: BindingContext = BindingContext.EMPTY): List<Finding> = if (pathFilters?.isIgnored(file) == true) { emptyList() } else { rules.flatMap { it.visitFile(file, bindingContext) it.findings } } }
apache-2.0
942c2c6375069dd34e12ecdf70efb9bc
30.926829
101
0.679144
4.320132
false
false
false
false
ivw/tinyscript
compiler-core/src/test/kotlin/tinyscript/compiler/core/ClassExpressionSpec.kt
1
1575
package tinyscript.compiler.core import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it object ClassExpressionSpec : Spek({ describe("class expression") { it("can be inherited from") { assertAnalysis(""" Animal = class [ name: String ] Dog = class [ &Animal bark = -> println[m = "woof"] ] myAnimal: Animal = [&Dog, name = "Foo"] """) assertAnalysisFails(""" Animal = class [ name: String ] Dog = class [ &Animal bark = -> println[m = "woof"] ] myDog = [&Dog] """) } it("can be used with an explicit type") { assertAnalysis(""" Animal = class [ name: String ] myObjectWithName: [name: String] = [&Animal, name = "Foo"] """) assertAnalysisFails(""" Animal = class [ name: String ] myAnimal: Animal = [name = "Foo"] """) assertAnalysisFails(""" Animal = class [ name: String ] myAnimal: [&Animal] = [name = "Foo"] """) } it("can have multiple inheritance") { assertAnalysis(""" Scanner = class [ scan: -> ? ] Printer = class [ print: -> ? ] Copier = class [ &Scanner &Printer copy = -> ( scan[] print[] ) ] foo: [&Scanner, &Printer] = [ &Copier scan = -> println[] print = -> println[] ] """) } it("can use forward references until it is used") { assertAnalysis(""" Animal = class [ name: String = defaultAnimalName ] defaultAnimalName = "Foo" myAnimal = [&Animal] """) } } })
mit
19e08017fbc5960acea6f3d23428e859
18.6875
62
0.553016
3.294979
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/jobs/CalendarImportWork.kt
1
2604
/* * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2017 Tobias Kaminsky * Copyright (C) 2017 Nextcloud GmbH. * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.content.ContentResolver import android.content.Context import androidx.work.Worker import androidx.work.WorkerParameters import com.nextcloud.client.logger.Logger import net.fortuna.ical4j.data.CalendarBuilder import third_parties.sufficientlysecure.AndroidCalendar import third_parties.sufficientlysecure.CalendarSource import third_parties.sufficientlysecure.ProcessVEvent import java.io.File class CalendarImportWork( private val appContext: Context, params: WorkerParameters, private val logger: Logger, private val contentResolver: ContentResolver ) : Worker(appContext, params) { companion object { const val TAG = "CalendarImportWork" const val SELECTED_CALENDARS = "selected_contacts_indices" } override fun doWork(): Result { val calendarPaths = inputData.getStringArray(SELECTED_CALENDARS) ?: arrayOf<String>() val calendars = inputData.keyValueMap as Map<String, AndroidCalendar> val calendarBuilder = CalendarBuilder() for ((path, selectedCalendar) in calendars) { logger.d(TAG, "Import calendar from $path") val file = File(path) val calendarSource = CalendarSource( file.toURI().toURL().toString(), null, null, null, appContext ) val calendars = AndroidCalendar.loadAll(contentResolver)[0] ProcessVEvent( appContext, calendarBuilder.build(calendarSource.stream), selectedCalendar, true ).run() } return Result.success() } }
gpl-2.0
67ab82c912756c19b563019bd9b92736
32.818182
93
0.688172
4.641711
false
false
false
false
cashapp/sqldelight
drivers/sqlite-driver/src/main/kotlin/app/cash/sqldelight/driver/jdbc/sqlite/JdbcSqliteDriver.kt
1
3472
package app.cash.sqldelight.driver.jdbc.sqlite import app.cash.sqldelight.Query import app.cash.sqldelight.driver.jdbc.ConnectionManager import app.cash.sqldelight.driver.jdbc.ConnectionManager.Transaction import app.cash.sqldelight.driver.jdbc.JdbcDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver.Companion.IN_MEMORY import java.sql.Connection import java.sql.DriverManager import java.util.Properties import kotlin.concurrent.getOrSet @Suppress("DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE") class JdbcSqliteDriver constructor( /** * Database connection URL in the form of `jdbc:sqlite:path` where `path` is either blank * (creating an in-memory database) or a path to a file. */ url: String, properties: Properties = Properties(), ) : JdbcDriver(), ConnectionManager by connectionManager(url, properties) { private val listeners = linkedMapOf<String, MutableSet<Query.Listener>>() override fun addListener(listener: Query.Listener, queryKeys: Array<String>) { synchronized(listeners) { queryKeys.forEach { listeners.getOrPut(it, { linkedSetOf() }).add(listener) } } } override fun removeListener(listener: Query.Listener, queryKeys: Array<String>) { synchronized(listeners) { queryKeys.forEach { listeners[it]?.remove(listener) } } } override fun notifyListeners(queryKeys: Array<String>) { val listenersToNotify = linkedSetOf<Query.Listener>() synchronized(listeners) { queryKeys.forEach { listeners[it]?.let(listenersToNotify::addAll) } } listenersToNotify.forEach(Query.Listener::queryResultsChanged) } companion object { const val IN_MEMORY = "jdbc:sqlite:" } } private fun connectionManager(url: String, properties: Properties) = when (url) { IN_MEMORY -> InMemoryConnectionManager(properties) else -> ThreadedConnectionManager(url, properties) } private abstract class JdbcSqliteDriverConnectionManager : ConnectionManager { override fun Connection.beginTransaction() { prepareStatement("BEGIN TRANSACTION").execute() } override fun Connection.endTransaction() { prepareStatement("END TRANSACTION").execute() } override fun Connection.rollbackTransaction() { prepareStatement("ROLLBACK TRANSACTION").execute() } } private class InMemoryConnectionManager( properties: Properties, ) : JdbcSqliteDriverConnectionManager() { override var transaction: Transaction? = null private val connection: Connection = DriverManager.getConnection(IN_MEMORY, properties) override fun getConnection() = connection override fun closeConnection(connection: Connection) = Unit override fun close() = connection.close() } private class ThreadedConnectionManager( private val url: String, private val properties: Properties, ) : JdbcSqliteDriverConnectionManager() { private val transactions = ThreadLocal<Transaction>() private val connections = ThreadLocal<Connection>() override var transaction: Transaction? get() = transactions.get() set(value) { transactions.set(value) } override fun getConnection() = connections.getOrSet { DriverManager.getConnection(url, properties) } override fun closeConnection(connection: Connection) { check(connections.get() == connection) { "Connections must be closed on the thread that opened them" } if (transaction == null) { connection.close() connections.remove() } } override fun close() = Unit }
apache-2.0
9429d64e97362ed32655e7d68b5c0fee
31.448598
106
0.746256
4.592593
false
false
false
false
Jasper-Hilven/dynamic-extensions-for-alfresco
annotations-runtime/src/main/kotlin/com/github/dynamicextensionsalfresco/policy/BehaviourProxy.kt
1
4448
package com.github.dynamicextensionsalfresco.policy import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.Proxy import java.util.concurrent.ConcurrentHashMap import com.github.dynamicextensionsalfresco.metrics.Timer import com.github.dynamicextensionsalfresco.metrics.time import org.alfresco.repo.policy.Behaviour import org.alfresco.repo.policy.Policy import org.alfresco.service.cmr.repository.NodeRef import java.lang.reflect.InvocationTargetException /** * Proxy that allows a [Behaviour] to be garbage-collected. * * * This class prevents dangling references to [Behaviour] instances when code is undeployed from an OSGi * container, as the [PolicyComponent] interface offers no means of unregistering [Behaviour]s. Dangling * references to the [BehaviourProxy] itself will continue to exist throughout the lifetime of the Alfresco * process, however. There will be a slight memory leak for every time you redeploy a Dynamic Extension that contains a * Behaviour. (Further revisions of this class may add the ability to reattach a Behaviour once a module gets updated.) * @author Laurens Fridael */ public class BehaviourProxy(private var behaviour: Behaviour, val timer: Timer) : Behaviour by behaviour { private val proxiesByPolicyClass = ConcurrentHashMap<Class<*>, ProxyPolicy>() @Suppress("UNCHECKED_CAST") override fun <T> getInterface(policy: Class<T>?): T { return proxiesByPolicyClass.getOrPut(policy) { if (behaviour is NoOpBehaviour) { val proxyHandler = ProxyPolicyInvocationHandler(null, behaviour, timer) val proxy = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(policy), proxyHandler) ProxyPolicy(proxy, proxyHandler) } else { val originalHandler = behaviour.getInterface<T>(policy) val proxyHandler = ProxyPolicyInvocationHandler(originalHandler, behaviour, timer) val proxy = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(policy), proxyHandler) ProxyPolicy(proxy, proxyHandler) } }.proxy as T } /** * Clears the reference to the original [Behaviour] and clears the target references for the * [ProxyPolicyComponentInvocationHandler]s. */ @Synchronized public fun release() { behaviour = NoOpBehaviour(behaviour.notificationFrequency, behaviour.isEnabled) for (proxyPolicy in proxiesByPolicyClass.values) { proxyPolicy.handler.release() } } private class ProxyPolicyInvocationHandler(private var target: Any?, private var behaviour: Behaviour?, val timer: Timer) : InvocationHandler { override fun invoke(proxy: Any, method: Method, args: Array<Any>?): Any? { if (method.declaringClass.isAssignableFrom(Any::class.java)) { // Direct Object methods to ourselves. if (args != null) { return method.invoke(this, *args) } else { return method.invoke(this) } } else if (Policy::class.java.isAssignableFrom(method.declaringClass)) { /* Policy interface operations always return void. */ if (behaviour != null) { try { timer.time( { behaviour.toString() + " " + args?.filterIsInstance(NodeRef::class.java)?.joinToString(",") } , { if (args != null) { return method.invoke(target, *args) } else { return method.invoke(target) } }) } catch(e: InvocationTargetException) { throw e.targetException } } return null } else { /* We should never get to this point. */ throw AssertionError("Cannot handle methods from " + method.declaringClass) } } fun release() { target = null behaviour = null } } override fun toString(): String { return behaviour.toString() } private class ProxyPolicy(val proxy: Any, val handler: ProxyPolicyInvocationHandler) }
apache-2.0
91c72a9282c254cf352a47f9514b1102
42.184466
147
0.623201
5.184149
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityELMe.kt
1
13336
package com.tamsiree.rxdemo.activity import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.graphics.PointF import android.os.Bundle import android.view.Gravity import android.view.View import android.view.WindowManager import android.view.animation.AccelerateInterpolator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.tamsiree.rxdemo.R import com.tamsiree.rxdemo.adapter.AdapterLeftMenu import com.tamsiree.rxdemo.adapter.AdapterLeftMenu.onItemSelectedListener import com.tamsiree.rxdemo.adapter.AdapterRightDish import com.tamsiree.rxdemo.interfaces.ShopCartInterface import com.tamsiree.rxdemo.model.ModelDish import com.tamsiree.rxdemo.model.ModelDishMenu import com.tamsiree.rxdemo.model.ModelShopCart import com.tamsiree.rxdemo.view.RxDialogShopCart import com.tamsiree.rxdemo.view.RxDialogShopCart.ShopCartDialogImp import com.tamsiree.rxdemo.view.RxFakeAddImageView import com.tamsiree.rxdemo.view.RxPointFTypeEvaluator import com.tamsiree.rxkit.RxDeviceTool.setPortrait import com.tamsiree.rxkit.TLog import com.tamsiree.rxui.activity.ActivityBase import kotlinx.android.synthetic.main.activity_elme.* import kotlinx.android.synthetic.main.right_menu_item.* import java.util.* /** * @author tamsiree */ class ActivityELMe : ActivityBase(), onItemSelectedListener, ShopCartInterface, ShopCartDialogImp { private var headMenu: ModelDishMenu? = null private var leftAdapter: AdapterLeftMenu? = null private lateinit var rightAdapter: AdapterRightDish //数据源 private lateinit var mModelDishMenuList: ArrayList<ModelDishMenu> private var leftClickType = false //左侧菜单点击引发的右侧联动 private lateinit var mModelShopCart: ModelShopCart override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_elme) setPortrait(this) } override fun initView() { rx_title.setLeftFinish(mContext) left_menu.layoutManager = LinearLayoutManager(this) right_menu.layoutManager = LinearLayoutManager(this) right_menu.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (!recyclerView.canScrollVertically(1)) { //无法下滑 showHeadView() return } val underView: View? = if (dy > 0) { right_menu.findChildViewUnder(right_menu_item.x, right_menu_item.measuredHeight + 1.toFloat()) } else { right_menu.findChildViewUnder(right_menu_item.x, 0f) } if (underView != null && underView.contentDescription != null) { val position = underView.contentDescription.toString().toInt() val menu = rightAdapter.getMenuOfMenuByPosition(position) if (leftClickType || menu?.menuName != headMenu!!.menuName) { if (dy > 0 && right_menu_item.translationY <= 1 && right_menu_item.translationY >= -1 * right_menu_item.measuredHeight * 4 / 5 && !leftClickType) { // underView.getTop()>9 val dealtY = underView.top - right_menu_item.measuredHeight right_menu_item.translationY = dealtY.toFloat() // RxLogTool.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+" "+headerLayout.getBottom()+" - "+headerLayout.getMeasuredHeight() ); } else if (dy < 0 && right_menu_item.translationY <= 0 && !leftClickType) { right_menu_tv.text = menu?.menuName val dealtY = underView.bottom - right_menu_item.measuredHeight right_menu_item.translationY = dealtY.toFloat() // RxLogTool.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+" "+headerLayout.getBottom()+" - "+headerLayout.getMeasuredHeight() ); } else { right_menu_item.translationY = 0f headMenu = menu right_menu_tv.text = headMenu!!.menuName for (i in mModelDishMenuList.indices) { if (mModelDishMenuList[i] == headMenu) { leftAdapter!!.selectedNum = i break } } if (leftClickType) { leftClickType = false } TLog.e(TAG, "onScrolled: " + menu?.menuName) } } } } }) shopping_cart_layout.setOnClickListener { view -> showCart(view) } } override fun initData() { mModelShopCart = ModelShopCart() mModelDishMenuList = ArrayList() val dishs1 = ArrayList<ModelDish>() dishs1.add(ModelDish("面包", 1.0, 10)) dishs1.add(ModelDish("蛋挞", 1.0, 10)) dishs1.add(ModelDish("牛奶", 1.0, 10)) dishs1.add(ModelDish("肠粉", 1.0, 10)) dishs1.add(ModelDish("绿茶饼", 1.0, 10)) dishs1.add(ModelDish("花卷", 1.0, 10)) dishs1.add(ModelDish("包子", 1.0, 10)) val breakfast = ModelDishMenu("早点", dishs1) val dishs2 = ArrayList<ModelDish>() dishs2.add(ModelDish("粥", 1.0, 10)) dishs2.add(ModelDish("炒饭", 1.0, 10)) dishs2.add(ModelDish("炒米粉", 1.0, 10)) dishs2.add(ModelDish("炒粿条", 1.0, 10)) dishs2.add(ModelDish("炒牛河", 1.0, 10)) dishs2.add(ModelDish("炒菜", 1.0, 10)) val launch = ModelDishMenu("午餐", dishs2) val dishs3 = ArrayList<ModelDish>() dishs3.add(ModelDish("淋菜", 1.0, 10)) dishs3.add(ModelDish("川菜", 1.0, 10)) dishs3.add(ModelDish("湘菜", 1.0, 10)) dishs3.add(ModelDish("粤菜", 1.0, 10)) dishs3.add(ModelDish("赣菜", 1.0, 10)) dishs3.add(ModelDish("东北菜", 1.0, 10)) val evening = ModelDishMenu("晚餐", dishs3) val dishs4 = ArrayList<ModelDish>() dishs4.add(ModelDish("淋菜", 1.0, 10)) dishs4.add(ModelDish("川菜", 1.0, 10)) dishs4.add(ModelDish("湘菜", 1.0, 10)) dishs4.add(ModelDish("湘菜", 1.0, 10)) dishs4.add(ModelDish("湘菜1", 1.0, 10)) dishs4.add(ModelDish("湘菜2", 1.0, 10)) dishs4.add(ModelDish("湘菜3", 1.0, 10)) dishs4.add(ModelDish("湘菜4", 1.0, 10)) dishs4.add(ModelDish("湘菜5", 1.0, 10)) dishs4.add(ModelDish("湘菜6", 1.0, 10)) dishs4.add(ModelDish("湘菜7", 1.0, 10)) dishs4.add(ModelDish("湘菜8", 1.0, 10)) dishs4.add(ModelDish("粤菜", 1.0, 10)) dishs4.add(ModelDish("赣菜", 1.0, 10)) dishs4.add(ModelDish("东北菜", 1.0, 10)) val menu1 = ModelDishMenu("夜宵", dishs4) mModelDishMenuList.add(breakfast) mModelDishMenuList.add(launch) mModelDishMenuList.add(evening) mModelDishMenuList.add(menu1) initAdapter() } private fun initAdapter() { leftAdapter = AdapterLeftMenu(this, mModelDishMenuList) rightAdapter = AdapterRightDish(this, mModelDishMenuList, mModelShopCart) right_menu.adapter = rightAdapter left_menu.adapter = leftAdapter leftAdapter!!.addItemSelectedListener(this) rightAdapter.shopCartInterface = this initHeadView() } private fun initHeadView() { headMenu = rightAdapter.getMenuOfMenuByPosition(0) right_menu_item.contentDescription = "0" right_menu_tv.text = headMenu?.menuName } override fun onDestroy() { super.onDestroy() leftAdapter!!.removeItemSelectedListener(this) } private fun showHeadView() { right_menu_item.translationY = 0f val underView = right_menu.findChildViewUnder(right_menu_tv.x, 0f) if (underView != null && underView.contentDescription != null) { val position = underView.contentDescription.toString().toInt() val menu = rightAdapter.getMenuOfMenuByPosition(position + 1) headMenu = menu right_menu_tv.text = headMenu!!.menuName for (i in mModelDishMenuList.indices) { if (mModelDishMenuList[i] == headMenu) { leftAdapter!!.selectedNum = i break } } } } override fun onLeftItemSelected(position: Int, menu: ModelDishMenu) { var sum = 0 for (i in 0 until position) { sum += mModelDishMenuList[i].modelDishList!!.size + 1 } val layoutManager = right_menu.layoutManager as LinearLayoutManager? layoutManager!!.scrollToPositionWithOffset(sum, 0) leftClickType = true } @SuppressLint("ObjectAnimatorBinding") override fun add(view: View?, position: Int) { val addLocation = IntArray(2) val cartLocation = IntArray(2) val recycleLocation = IntArray(2) view!!.getLocationInWindow(addLocation) shopping_cart.getLocationInWindow(cartLocation) right_menu.getLocationInWindow(recycleLocation) val startP = PointF() val endP = PointF() val controlP = PointF() startP.x = addLocation[0].toFloat() startP.y = addLocation[1] - recycleLocation[1].toFloat() endP.x = cartLocation[0].toFloat() endP.y = cartLocation[1] - recycleLocation[1].toFloat() controlP.x = endP.x controlP.y = startP.y val rxFakeAddImageView = RxFakeAddImageView(this) main_layout.addView(rxFakeAddImageView) rxFakeAddImageView.setImageResource(R.drawable.ic_add_circle_blue_700_36dp) rxFakeAddImageView.layoutParams.width = resources.getDimensionPixelSize(R.dimen.item_dish_circle_size) rxFakeAddImageView.layoutParams.height = resources.getDimensionPixelSize(R.dimen.item_dish_circle_size) rxFakeAddImageView.visibility = View.VISIBLE val addAnimator = ObjectAnimator.ofObject(rxFakeAddImageView, "mPointF", RxPointFTypeEvaluator(controlP), startP, endP) addAnimator.interpolator = AccelerateInterpolator() addAnimator.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animator: Animator) { rxFakeAddImageView.visibility = View.VISIBLE } override fun onAnimationEnd(animator: Animator) { rxFakeAddImageView.visibility = View.GONE main_layout.removeView(rxFakeAddImageView) } override fun onAnimationCancel(animator: Animator) {} override fun onAnimationRepeat(animator: Animator) {} }) val scaleAnimatorX: ObjectAnimator = ObjectAnimator.ofFloat(shopping_cart, "scaleX", 0.6f, 1.0f) val scaleAnimatorY: ObjectAnimator = ObjectAnimator.ofFloat(shopping_cart, "scaleY", 0.6f, 1.0f) scaleAnimatorX.interpolator = AccelerateInterpolator() scaleAnimatorY.interpolator = AccelerateInterpolator() val animatorSet = AnimatorSet() animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator) animatorSet.duration = 800 animatorSet.start() showTotalPrice() } override fun remove(view: View?, position: Int) { showTotalPrice() } @SuppressLint("SetTextI18n") private fun showTotalPrice() { if (mModelShopCart.shoppingTotalPrice > 0) { shopping_cart_total_tv.visibility = View.VISIBLE shopping_cart_total_tv.text = "¥ " + mModelShopCart.shoppingTotalPrice.toString() shopping_cart_total_num.visibility = View.VISIBLE shopping_cart_total_num.text = mModelShopCart.shoppingAccount.toString() } else { shopping_cart_total_tv.visibility = View.GONE shopping_cart_total_num.visibility = View.GONE } } private fun showCart(view: View) { if (mModelShopCart.shoppingAccount > 0) { val dialog = RxDialogShopCart(this, mModelShopCart, R.style.cartdialog) val window = dialog.window dialog.shopCartDialogImp = this dialog.setCanceledOnTouchOutside(true) dialog.setCancelable(true) dialog.show() val params = window!!.attributes params.width = WindowManager.LayoutParams.MATCH_PARENT params.height = WindowManager.LayoutParams.WRAP_CONTENT params.gravity = Gravity.BOTTOM params.dimAmount = 0.5f window.attributes = params } } override fun dialogDismiss() { showTotalPrice() rightAdapter.notifyDataSetChanged() } }
apache-2.0
5e3fbd6bc20acf580db5e2a721e173a7
43.073826
195
0.621259
3.836693
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/popupwindows/tools/RxPopupViewBackgroundConstructor.kt
1
4289
package com.tamsiree.rxui.view.popupwindows.tools import android.content.Context import android.graphics.PorterDuff import android.graphics.drawable.Drawable import android.os.Build import android.view.View import com.tamsiree.rxui.R import com.tamsiree.rxui.view.popupwindows.tools.RxPopupViewTool.isRtl /** * @author Tamsiree */ internal object RxPopupViewBackgroundConstructor { /** * Select which background will be assign to the tip view */ fun setBackground(tipView: View, rxPopupView: RxPopupView) { // show tool tip without arrow. no need to continue if (rxPopupView.hideArrow()) { setToolTipNoArrowBackground(tipView, rxPopupView.backgroundColor) return } when (rxPopupView.position) { RxPopupView.POSITION_ABOVE -> setToolTipAboveBackground(tipView, rxPopupView) RxPopupView.POSITION_BELOW -> setToolTipBelowBackground(tipView, rxPopupView) RxPopupView.POSITION_LEFT_TO -> setToolTipLeftToBackground(tipView, rxPopupView.backgroundColor) RxPopupView.POSITION_RIGHT_TO -> setToolTipRightToBackground(tipView, rxPopupView.backgroundColor) else -> { } } } private fun setToolTipAboveBackground(tipView: View, rxPopupView: RxPopupView) { when (rxPopupView.align) { RxPopupView.ALIGN_CENTER -> setTipBackground(tipView, R.drawable.tooltip_arrow_down, rxPopupView.backgroundColor) RxPopupView.ALIGN_LEFT -> setTipBackground(tipView, if (!isRtl) R.drawable.tooltip_arrow_down_left else R.drawable.tooltip_arrow_down_right , rxPopupView.backgroundColor) RxPopupView.ALIGN_RIGHT -> setTipBackground(tipView, if (!isRtl) R.drawable.tooltip_arrow_down_right else R.drawable.tooltip_arrow_down_left , rxPopupView.backgroundColor) else -> { } } } private fun setToolTipBelowBackground(tipView: View, rxPopupView: RxPopupView) { when (rxPopupView.align) { RxPopupView.ALIGN_CENTER -> setTipBackground(tipView, R.drawable.tooltip_arrow_up, rxPopupView.backgroundColor) RxPopupView.ALIGN_LEFT -> setTipBackground(tipView, if (!isRtl) R.drawable.tooltip_arrow_up_left else R.drawable.tooltip_arrow_up_right , rxPopupView.backgroundColor) RxPopupView.ALIGN_RIGHT -> setTipBackground(tipView, if (!isRtl) R.drawable.tooltip_arrow_up_right else R.drawable.tooltip_arrow_up_left , rxPopupView.backgroundColor) else -> { } } } private fun setToolTipLeftToBackground(tipView: View, color: Int) { setTipBackground(tipView, if (!isRtl) R.drawable.tooltip_arrow_right else R.drawable.tooltip_arrow_left, color) } private fun setToolTipRightToBackground(tipView: View, color: Int) { setTipBackground(tipView, if (!isRtl) R.drawable.tooltip_arrow_left else R.drawable.tooltip_arrow_right, color) } private fun setToolTipNoArrowBackground(tipView: View, color: Int) { setTipBackground(tipView, R.drawable.tooltip_no_arrow, color) } private fun setTipBackground(tipView: View, drawableRes: Int, color: Int) { val paintedDrawable = getTintedDrawable(tipView.context, drawableRes, color) setViewBackground(tipView, paintedDrawable) } private fun setViewBackground(view: View, drawable: Drawable?) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.background = drawable } else { view.setBackgroundDrawable(drawable) } } private fun getTintedDrawable(context: Context, drawableRes: Int, color: Int): Drawable? { val drawable: Drawable? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { drawable = context.resources.getDrawable(drawableRes, null) drawable?.setTint(color) } else { drawable = context.resources.getDrawable(drawableRes) drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) } return drawable } }
apache-2.0
c534096f8ce2e5268a8d8ad50c8bf1c7
41.058824
125
0.660294
4.233959
false
false
false
false
panpf/sketch
sketch/src/main/java/com/github/panpf/sketch/drawable/internal/ResizeAnimatableDrawable.kt
1
3245
/* * Copyright (C) 2022 panpf <[email protected]> * * 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.panpf.sketch.drawable.internal import android.annotation.SuppressLint import android.graphics.drawable.Drawable import androidx.vectordrawable.graphics.drawable.Animatable2Compat import androidx.vectordrawable.graphics.drawable.Animatable2Compat.AnimationCallback import com.github.panpf.sketch.drawable.SketchAnimatableDrawable import com.github.panpf.sketch.resize.Scale import com.github.panpf.sketch.util.Size import com.github.panpf.sketch.util.asOrThrow import com.github.panpf.sketch.util.requiredMainThread /** * Using [resizeSize] as the intrinsic size of [drawable], [drawable] will be scaled according to the scale of [resizeSize]. * ResizeDrawable is suitable for changing the start and end pictures to the same size when using CrossfadeDrawable to display pictures in transition, so as to avoid the start or end pictures being scaled when the transition animation starts */ open class ResizeAnimatableDrawable( drawable: SketchAnimatableDrawable, resizeSize: Size, resizeScale: Scale ) : ResizeDrawable(drawable, resizeSize, resizeScale), Animatable2Compat { override fun start() { wrappedDrawable.start() } override fun stop() { wrappedDrawable.stop() } override fun isRunning(): Boolean { return wrappedDrawable.isRunning } override fun registerAnimationCallback(callback: AnimationCallback) { requiredMainThread() // Consistent with AnimatedImageDrawable wrappedDrawable.registerAnimationCallback(callback) } override fun unregisterAnimationCallback(callback: AnimationCallback): Boolean { return wrappedDrawable.unregisterAnimationCallback(callback) } override fun clearAnimationCallbacks() { wrappedDrawable.clearAnimationCallbacks() } @SuppressLint("RestrictedApi") override fun getWrappedDrawable(): SketchAnimatableDrawable { return super.getWrappedDrawable().asOrThrow() } @SuppressLint("RestrictedApi") override fun setWrappedDrawable(drawable: Drawable) { super.setWrappedDrawable(drawable as SketchAnimatableDrawable) } @SuppressLint("RestrictedApi") override fun mutate(): ResizeAnimatableDrawable { val mutateDrawable = wrappedDrawable.mutate() return if (mutateDrawable !== wrappedDrawable) { ResizeAnimatableDrawable(mutateDrawable, resizeSize, resizeScale) } else { this } } override fun toString(): String { return "ResizeAnimatableDrawable(wrapped=$wrappedDrawable, resizeSize=$resizeSize, resizeScale=$resizeScale)" } }
apache-2.0
2a99f2866be939b8fd0ba48ccdc3883c
36.744186
241
0.749153
4.916667
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/DiningHall.kt
1
7241
package com.pennapps.labs.pennmobile.classes import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName import org.joda.time.DateTime import org.joda.time.Interval import java.util.* open class DiningHall : Parcelable { var id: Int private set var name: String? private set // Refers to whether the dining hall is residential or retail var isResidential: Boolean private set private var openHours: HashMap<String, Interval> var venue: Venue? = null private set var image: Int private set @SerializedName("tblDayPart") var menus: MutableList<Menu> = ArrayList() constructor(id: Int, name: String?, residential: Boolean, hours: HashMap<String, Interval>, venue: Venue?, image: Int) { this.id = id this.name = name isResidential = residential openHours = hours this.venue = venue this.image = image } protected constructor(`in`: Parcel) { val booleanArray = BooleanArray(1) `in`.readBooleanArray(booleanArray) isResidential = booleanArray[0] openHours = HashMap() menus = ArrayList() // Use application class loader instead of framework class loader because Menu is a custom class `in`.readMap(openHours as Map<*, *>, javaClass.classLoader) (menus as List<*>?)?.let { `in`.readList(it, javaClass.classLoader) } id = `in`.readInt() name = `in`.readString() image = `in`.readInt() } fun sortMeals(menus: MutableList<Menu>) { this.menus = menus val mealOrder = listOf("Breakfast", "Brunch", "Lunch", "Dinner", "Express") val comparator = Comparator { lhs: Menu, rhs: Menu -> mealOrder.indexOf(lhs.name) - mealOrder.indexOf(rhs.name) } this.menus.sortedWith(comparator) } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeBooleanArray(booleanArrayOf(isResidential)) dest.writeMap(openHours as Map<*, *>?) dest.writeList(menus as List<*>?) dest.writeInt(id) dest.writeString(name) dest.writeInt(image) } // Returns list of time intervals sorted by interval starting time private fun orderedHours(): List<Interval?> { val list: List<Interval?> = ArrayList(openHours.values) val comparator = Comparator { x: Interval, y: Interval -> x.start.compareTo(y.start) } return list.sortedWith(comparator) } // Returns list of time intervals sorted by interval starting time, and merges intervals such that none overlap private fun orderedMergedHours(): List<Interval> { val originalList = orderedHours() val mergedList: MutableList<Interval> = ArrayList(originalList.size) var currentInterval: Interval? = null for (i in originalList.indices) { currentInterval = if (currentInterval == null) { originalList[i] } else if (currentInterval.end >= originalList[i]!!.start) { val newEndTime = if (currentInterval.end > originalList[i]!!.end) currentInterval.end else originalList[i]!!.end Interval(currentInterval.start, newEndTime) } else { mergedList.add(currentInterval) null } } if (currentInterval != null) { mergedList.add(currentInterval) } return mergedList } // Takes the ordered time intervals of the dining hall and formats them for displaying to the user // e.g. 8 - 11 | 12 - 3 | 6 - 9 fun openTimes(): String { //val list = if (isResidential) orderedHours() else orderedMergedHours() val list = orderedHours() val builder = StringBuilder() for (i in list.indices) { val openInterval = list[i] if (i != 0) { builder.append(" | ") } if (openInterval != null) { builder.append(getFormattedTime(openInterval.start)) builder.append(" - ") builder.append(getFormattedTime(openInterval.end)) } } return builder.toString() } private fun getFormattedTime(time: DateTime): String { return if (time.toString("mm") == "00") { if (isResidential) { time.toString("h") } else { time.toString("h a") } } else { if (isResidential) { time.toString("h:mm") } else { time.toString("h:mm a") } } } val isOpen: Boolean get() { for (openInterval in openHours.values) { if (openInterval.containsNow()) { return true } } return false } // Returns the name of the meal that the dining hall is currently serving (e.g. Breakfast) fun openMeal(): String? { for ((key, openInterval) in openHours) { if (openInterval.containsNow()) { return key } } return null } /** * Created by Adel on 12/18/14. * Class for a single menu, ie. Lunch, Dinner */ open class Menu protected constructor(`in`: Parcel) : Parcelable { @SerializedName("service") var name: String = `in`.readString() ?: "" @SerializedName("stations") var stations: List<DiningStation> = ArrayList() @SerializedName("venue") var venue: DiningVenue? = null override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(name) } companion object { val CREATOR: Parcelable.Creator<Menu?> = object : Parcelable.Creator<Menu?> { override fun createFromParcel(`in`: Parcel): Menu? { return Menu(`in`) } override fun newArray(size: Int): Array<Menu?> { return arrayOfNulls(size) } } } } class DiningVenue { @SerializedName("venue_id") var venue_id: Int = -1 } /** * Created by Adel on 12/18/14. * Class for a station at a dining hall */ class DiningStation { @SerializedName("name") var name: String = "" @SerializedName("items") var items: List<FoodItem> = ArrayList() } /** * Created by Adel on 12/18/14. * Class for Food items in Dining menus */ class FoodItem { @SerializedName("name") var title: String? = null @SerializedName("description") var description: String? = null } companion object CREATOR : Parcelable.Creator<DiningHall> { override fun createFromParcel(parcel: Parcel): DiningHall { return DiningHall(parcel) } override fun newArray(size: Int): Array<DiningHall?> { return arrayOfNulls(size) } } }
mit
de03387780f78e06e746806d0e77f974
30.215517
128
0.572435
4.525625
false
false
false
false
Devifish/ReadMe
app/src/main/java/cn/devifish/readme/entity/Rank.kt
1
731
package cn.devifish.readme.entity import java.util.* /** * Created by zhang on 2017/7/22. * 书籍榜单 */ data class Rank( var _id: String? = null, var updated: Date? = null, var title: String? = null, var tag: String? = null, var cover: String? = null, var icon: String? = null, var monthRank: String? = null, var totalRank: String? = null, var shortTitle: String? = null, var created: Date? = null, var isSub: Boolean = false, var collapse: Boolean = false, var new: Boolean = false, var gender: String? = null, var priority: Int = 0, var books: List<Book>? = null, var total: Int = 0 )
apache-2.0
e99690791e0f2c4ae89ed39b5441239f
25.814815
39
0.549101
3.615
false
false
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/polling/PollingTestUtils.kt
1
1868
package com.stripe.android.polling import com.stripe.android.PaymentConfiguration import com.stripe.android.core.networking.ApiRequest import com.stripe.android.model.PaymentIntent import com.stripe.android.model.StripeIntent import com.stripe.android.networking.AbsFakeStripeRepository import kotlinx.coroutines.CoroutineDispatcher import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock internal fun exponentialDelayProvider(): () -> Long { var attempt = 1 return { // Add a minor offset so that we run after the delay has finished, // not when it's just about to finish. val offset = if (attempt == 1) 1 else 0 calculateDelay(attempts = attempt++).inWholeMilliseconds + offset } } internal fun createIntentStatusPoller( enqueuedStatuses: List<StripeIntent.Status?>, dispatcher: CoroutineDispatcher, maxAttempts: Int = 10, ): DefaultIntentStatusPoller { return DefaultIntentStatusPoller( stripeRepository = FakeStripeRepository(enqueuedStatuses), paymentConfigProvider = { PaymentConfiguration( publishableKey = "key", stripeAccountId = "account_id", ) }, config = IntentStatusPoller.Config( clientSecret = "secret", maxAttempts = maxAttempts, ), dispatcher = dispatcher, ) } private class FakeStripeRepository( enqueuedStatuses: List<StripeIntent.Status?> ) : AbsFakeStripeRepository() { private val queue = enqueuedStatuses.toMutableList() override suspend fun retrievePaymentIntent( clientSecret: String, options: ApiRequest.Options, expandFields: List<String> ): PaymentIntent { val intentStatus = queue.removeFirst() return mock { on { status } doReturn intentStatus } } }
mit
5c1d180e8877170676701079e3ba10b0
30.661017
74
0.686296
4.941799
false
true
false
false
AndroidX/androidx
compose/ui/ui-text/src/desktopMain/kotlin/androidx/compose/ui/text/intl/DesktopPlatformLocale.desktop.kt
3
1391
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.intl import java.util.Locale internal class DesktopLocale(val locale: Locale) : PlatformLocale { override val language: String get() = locale.language override val script: String get() = locale.script override val region: String get() = locale.country override fun toLanguageTag(): String = locale.toLanguageTag() } internal actual fun createPlatformLocaleDelegate() = object : PlatformLocaleDelegate { override val current: List<PlatformLocale> get() = listOf(DesktopLocale(Locale.getDefault())) override fun parseLanguageTag(languageTag: String): PlatformLocale = DesktopLocale( Locale.forLanguageTag( languageTag ) ) }
apache-2.0
9c353051b9cb026762e9ebe55fe3ccf2
30.613636
86
0.704529
4.560656
false
false
false
false
AndroidX/androidx
camera/integration-tests/viewfindertestapp/src/main/java/androidx/camera/integration/viewfinder/OrientationLiveData.kt
3
3534
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 androidx.camera.integration.viewfinder import android.content.Context import android.hardware.camera2.CameraCharacteristics import android.view.OrientationEventListener import android.view.Surface import androidx.lifecycle.LiveData /** * Calculates closest 90-degree orientation to compensate for the device * rotation relative to sensor orientation, i.e., allows user to see camera * frames with the expected orientation. */ class OrientationLiveData( context: Context, characteristics: CameraCharacteristics ) : LiveData<Int>() { private val listener = object : OrientationEventListener(context.applicationContext) { override fun onOrientationChanged(orientation: Int) { val rotation = when { orientation <= 45 -> Surface.ROTATION_0 orientation <= 135 -> Surface.ROTATION_90 orientation <= 225 -> Surface.ROTATION_180 orientation <= 315 -> Surface.ROTATION_270 else -> Surface.ROTATION_0 } val relative = computeRelativeRotation(characteristics, rotation) if (relative != value) postValue(relative) } } override fun onActive() { super.onActive() listener.enable() } override fun onInactive() { super.onInactive() listener.disable() } companion object { /** * Computes rotation required to transform from the camera sensor orientation to the * device's current orientation in degrees. * * @param characteristics the [CameraCharacteristics] to query for the sensor orientation. * @param surfaceRotation the current device orientation as a Surface constant * @return the relative rotation from the camera sensor to the current device orientation. */ @JvmStatic private fun computeRelativeRotation( characteristics: CameraCharacteristics, surfaceRotation: Int ): Int { val sensorOrientationDegrees = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!! val deviceOrientationDegrees = when (surfaceRotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> 0 } // Reverse device orientation for front-facing cameras val sign = if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) 1 else -1 // Calculate desired JPEG orientation relative to camera orientation to make // the image upright relative to the device orientation return (sensorOrientationDegrees - (deviceOrientationDegrees * sign) + 360) % 360 } } }
apache-2.0
95ffb5b9020e6fa57a30b2f681820147
36.595745
98
0.659027
5.346445
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/RsImplIndexAndTypeAliasCache.kt
2
3861
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.containers.ContainerUtil import org.rust.lang.core.psi.RustStructureChangeListener import org.rust.lang.core.psi.rustPsiManager import org.rust.lang.core.resolve.indexes.RsImplIndex import org.rust.lang.core.resolve.indexes.RsTypeAliasIndex import org.rust.lang.core.types.TyFingerprint import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicReference @Service class RsImplIndexAndTypeAliasCache(private val project: Project) : Disposable { // strong key -> soft value maps private val _implIndexCache: AtomicReference<ConcurrentMap<TyFingerprint, List<RsCachedImplItem>>?> = AtomicReference(null) private val _typeAliasIndexCache: AtomicReference<ConcurrentMap<TyFingerprint, List<RsCachedTypeAlias>>?> = AtomicReference(null) private val implIndexCache: ConcurrentMap<TyFingerprint, List<RsCachedImplItem>> get() = _implIndexCache.getOrCreateMap() private val typeAliasIndexCache: ConcurrentMap<TyFingerprint, List<RsCachedTypeAlias>> get() = _typeAliasIndexCache.getOrCreateMap() /** * This map is actually used is a [Set] (the value is always [placeholder]). * The only purpose of this set is holding links to [PsiFile]s, so retain them in memory. * Without this set [PsiFile]s are retained only by [java.lang.ref.WeakReference], hence they are * quickly collected by GC and then further index lookups work slower. * * Note: keys in this map are referenced via [java.lang.ref.SoftReference], so they're also * can be collected by GC, hence there isn't a memory leak */ private val usedPsiFiles: ConcurrentMap<PsiFile, Any> = ContainerUtil.createConcurrentSoftMap() private val placeholder = Any() init { val rustPsiManager = project.rustPsiManager val connection = project.messageBus.connect(this) rustPsiManager.subscribeRustStructureChange(connection, object : RustStructureChangeListener { override fun rustStructureChanged(file: PsiFile?, changedElement: PsiElement?) { _implIndexCache.getAndSet(null) _typeAliasIndexCache.getAndSet(null) } }) } fun findPotentialImpls(tyf: TyFingerprint): List<RsCachedImplItem> { return implIndexCache.getOrPut(tyf) { RsImplIndex.findPotentialImpls(project, tyf).filter { retainPsi(it.impl.containingFile) it.isValid } } } fun findPotentialAliases(tyf: TyFingerprint): List<RsCachedTypeAlias> { return typeAliasIndexCache.getOrPut(tyf) { RsTypeAliasIndex.findPotentialAliases(project, tyf).filter { retainPsi(it.alias.containingFile) it.isFreeAndValid } } } private fun retainPsi(containingFile: PsiFile) { usedPsiFiles[containingFile] = placeholder } override fun dispose() {} companion object { fun getInstance(project: Project): RsImplIndexAndTypeAliasCache = project.service() @JvmStatic private fun <T : Any> AtomicReference<ConcurrentMap<TyFingerprint, T>?>.getOrCreateMap(): ConcurrentMap<TyFingerprint, T> { while (true) { get()?.let { return it } val map = ContainerUtil.createConcurrentSoftValueMap<TyFingerprint, T>() if (compareAndSet(null, map)) return map } } } }
mit
32989aefde9d2830b9c3d6c55df43042
39.642105
133
0.703445
4.53169
false
false
false
false
rwinch/spring-security
config/src/test/kotlin/org/springframework/security/config/web/server/ServerCsrfDslTests.kt
1
10126
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.security.config.web.server import io.mockk.every import io.mockk.mockkObject import io.mockk.verify import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler import org.springframework.security.web.server.csrf.CsrfToken import org.springframework.security.web.server.csrf.DefaultCsrfToken import org.springframework.security.web.server.csrf.ServerCsrfTokenRepository import org.springframework.security.web.server.csrf.WebSessionServerCsrfTokenRepository import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.reactive.config.EnableWebFlux import org.springframework.web.reactive.function.BodyInserters.fromMultipartData import reactor.core.publisher.Mono /** * Tests for [ServerCsrfDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class ServerCsrfDslTests { @JvmField val spring = SpringTestContext(this) private val token: CsrfToken = DefaultCsrfToken("csrf", "CSRF", "a") private lateinit var client: WebTestClient @Autowired fun setup(context: ApplicationContext) { this.client = WebTestClient .bindToApplicationContext(context) .configureClient() .build() } @Test fun `post when CSRF protection enabled then requires CSRF token`() { this.spring.register(CsrfConfig::class.java).autowire() this.client.post() .uri("/") .exchange() .expectStatus().isForbidden } @EnableWebFluxSecurity @EnableWebFlux open class CsrfConfig { @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { } } } } @Test fun `post when CSRF protection disabled then CSRF token is not required`() { this.spring.register(CsrfDisabledConfig::class.java).autowire() this.client.post() .uri("/") .exchange() .expectStatus().isOk } @EnableWebFluxSecurity @EnableWebFlux open class CsrfDisabledConfig { @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { disable() } } } @RestController internal class TestController { @PostMapping("/") fun home() { } } } @Test fun `post when request matches CSRF matcher then CSRF token required`() { this.spring.register(CsrfMatcherConfig::class.java).autowire() this.client.post() .uri("/csrf") .exchange() .expectStatus().isForbidden } @Test fun `post when request does not match CSRF matcher then CSRF token is not required`() { this.spring.register(CsrfMatcherConfig::class.java).autowire() this.client.post() .uri("/") .exchange() .expectStatus().isOk } @EnableWebFluxSecurity @EnableWebFlux open class CsrfMatcherConfig { @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { requireCsrfProtectionMatcher = PathPatternParserServerWebExchangeMatcher("/csrf") } } } @RestController internal class TestController { @PostMapping("/") fun home() { } @PostMapping("/csrf") fun csrf() { } } } @Test fun `csrf when custom access denied handler then handler used`() { this.spring.register(CustomAccessDeniedHandlerConfig::class.java).autowire() mockkObject(CustomAccessDeniedHandlerConfig.ACCESS_DENIED_HANDLER) this.client.post() .uri("/") .exchange() verify(exactly = 1) { CustomAccessDeniedHandlerConfig.ACCESS_DENIED_HANDLER.handle(any(), any()) } } @EnableWebFluxSecurity @EnableWebFlux open class CustomAccessDeniedHandlerConfig { companion object { val ACCESS_DENIED_HANDLER: ServerAccessDeniedHandler = HttpStatusServerAccessDeniedHandler(HttpStatus.FORBIDDEN) } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { accessDeniedHandler = ACCESS_DENIED_HANDLER } } } } @Test fun `csrf when custom token repository then repository used`() { this.spring.register(CustomCsrfTokenRepositoryConfig::class.java).autowire() mockkObject(CustomCsrfTokenRepositoryConfig.TOKEN_REPOSITORY) every { CustomCsrfTokenRepositoryConfig.TOKEN_REPOSITORY.loadToken(any()) } returns Mono.just(this.token) this.client.post() .uri("/") .exchange() verify(exactly = 1) { CustomCsrfTokenRepositoryConfig.TOKEN_REPOSITORY.loadToken(any()) } } @EnableWebFluxSecurity @EnableWebFlux open class CustomCsrfTokenRepositoryConfig { companion object { val TOKEN_REPOSITORY: ServerCsrfTokenRepository = WebSessionServerCsrfTokenRepository() } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { csrfTokenRepository = TOKEN_REPOSITORY } } } } @Test fun `csrf when multipart form data and not enabled then denied`() { this.spring.register(MultipartFormDataNotEnabledConfig::class.java).autowire() mockkObject(MultipartFormDataNotEnabledConfig.TOKEN_REPOSITORY) every { MultipartFormDataNotEnabledConfig.TOKEN_REPOSITORY.loadToken(any()) } returns Mono.just(this.token) every { MultipartFormDataNotEnabledConfig.TOKEN_REPOSITORY.generateToken(any()) } returns Mono.just(this.token) this.client.post() .uri("/") .contentType(MediaType.MULTIPART_FORM_DATA) .body(fromMultipartData(this.token.parameterName, this.token.token)) .exchange() .expectStatus().isForbidden } @EnableWebFluxSecurity @EnableWebFlux open class MultipartFormDataNotEnabledConfig { companion object { val TOKEN_REPOSITORY: ServerCsrfTokenRepository = WebSessionServerCsrfTokenRepository() } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { csrfTokenRepository = TOKEN_REPOSITORY } } } } @Test fun `csrf when multipart form data and enabled then granted`() { this.spring.register(MultipartFormDataEnabledConfig::class.java).autowire() mockkObject(MultipartFormDataEnabledConfig.TOKEN_REPOSITORY) every { MultipartFormDataEnabledConfig.TOKEN_REPOSITORY.loadToken(any()) } returns Mono.just(this.token) every { MultipartFormDataEnabledConfig.TOKEN_REPOSITORY.generateToken(any()) } returns Mono.just(this.token) this.client.post() .uri("/") .contentType(MediaType.MULTIPART_FORM_DATA) .body(fromMultipartData(this.token.parameterName, this.token.token)) .exchange() .expectStatus().isOk } @EnableWebFluxSecurity @EnableWebFlux open class MultipartFormDataEnabledConfig { companion object { val TOKEN_REPOSITORY: ServerCsrfTokenRepository = WebSessionServerCsrfTokenRepository() } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { csrf { csrfTokenRepository = TOKEN_REPOSITORY tokenFromMultipartDataEnabled = true } } } @RestController internal class TestController { @PostMapping("/") fun home() { } } } }
apache-2.0
24036969a8ad9a103b2f2d0dc7043c1d
32.309211
124
0.645862
5.329474
false
true
false
false
androidx/androidx
benchmark/benchmark-darwin-gradle-plugin/src/main/kotlin/androidx/benchmark/darwin/gradle/DarwinBenchmarkResultsTask.kt
3
2827
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark.darwin.gradle import androidx.benchmark.darwin.gradle.skia.Metrics import androidx.benchmark.darwin.gradle.xcode.GsonHelpers import androidx.benchmark.darwin.gradle.xcode.XcResultParser import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import javax.inject.Inject import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.process.ExecOperations @CacheableTask abstract class DarwinBenchmarkResultsTask @Inject constructor( private val execOperations: ExecOperations ) : DefaultTask() { @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) abstract val xcResultPath: DirectoryProperty @get:OutputFile abstract val outputFile: RegularFileProperty @get:OutputFile @get:Optional abstract val distFile: RegularFileProperty @TaskAction fun benchmarkResults() { val xcResultFile = xcResultPath.get().asFile val parser = XcResultParser(xcResultFile) { args -> val output = ByteArrayOutputStream() execOperations.exec { spec -> spec.commandLine = args spec.standardOutput = output } output.use { val input = ByteArrayInputStream(output.toByteArray()) input.use { input.reader().readText() } } } val (record, summaries) = parser.parseResults() val metrics = Metrics.buildMetrics(record, summaries) val output = GsonHelpers.gsonBuilder() .setPrettyPrinting() .create() .toJson(metrics) outputFile.get().asFile.writeText(output) // Add output to the DIST_DIR when specified if (distFile.isPresent) { distFile.get().asFile.writeText(output) } } }
apache-2.0
18eee8d45270f42993c78e8351e1522b
33.47561
75
0.705695
4.611746
false
false
false
false
androidx/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/SuspendingGesturesDemo.kt
3
18101
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos import android.graphics.Matrix import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.requiredWidth import androidx.compose.integration.demos.common.ComposableDemo import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.PointerType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import kotlin.math.atan2 import kotlin.math.roundToInt import kotlin.math.sqrt import kotlin.random.Random val CoroutineGestureDemos = listOf( ComposableDemo("Tap/Double-Tap/Long Press") { CoroutineTapDemo() }, ComposableDemo("Drag Horizontal and Vertical") { TouchSlopDragGestures() }, ComposableDemo("Drag with orientation locking") { OrientationLockDragGestures() }, ComposableDemo("Drag 2D") { Drag2DGestures() }, ComposableDemo("Rotation/Pan/Zoom") { MultitouchGestureDetector() }, ComposableDemo("Rotation/Pan/Zoom with Lock") { MultitouchLockGestureDetector() }, ComposableDemo("Pointer type input") { PointerTypeInput() }, ) fun hueToColor(hue: Float): Color { val huePrime = hue / 60 val hueRange = huePrime.toInt() val hueRemainder = huePrime - hueRange return when (hueRange) { 0 -> Color(1f, hueRemainder, 0f) 1 -> Color(1f - hueRemainder, 1f, 0f) 2 -> Color(0f, 1f, hueRemainder) 3 -> Color(0f, 1f - hueRemainder, 1f) 4 -> Color(hueRemainder, 0f, 1f) else -> Color(1f, 0f, 1f - hueRemainder) } } fun randomHue() = Random.nextFloat() * 360 fun anotherRandomHue(hue: Float): Float { val newHue: Float = Random.nextFloat() * 260f // we don't want the hue to be close, so we ensure that it isn't with 50 of the current hue return if (newHue > hue - 50f) { newHue + 100f } else { newHue } } /** * Gesture detector for tap, double-tap, and long-press. */ @Composable fun CoroutineTapDemo() { var tapHue by remember { mutableStateOf(randomHue()) } var longPressHue by remember { mutableStateOf(randomHue()) } var doubleTapHue by remember { mutableStateOf(randomHue()) } var pressHue by remember { mutableStateOf(randomHue()) } var releaseHue by remember { mutableStateOf(randomHue()) } var cancelHue by remember { mutableStateOf(randomHue()) } Column { Text("The boxes change color when you tap the white box.") Spacer(Modifier.requiredSize(5.dp)) Box( Modifier .fillMaxWidth() .height(50.dp) .pointerInput(Unit) { detectTapGestures( onTap = { tapHue = anotherRandomHue(tapHue) }, onDoubleTap = { doubleTapHue = anotherRandomHue(doubleTapHue) }, onLongPress = { longPressHue = anotherRandomHue(longPressHue) }, onPress = { pressHue = anotherRandomHue(pressHue) if (tryAwaitRelease()) { releaseHue = anotherRandomHue(releaseHue) } else { cancelHue = anotherRandomHue(cancelHue) } } ) } .background(Color.White) .border(BorderStroke(2.dp, Color.Black)) ) { Text("Tap, double-tap, or long-press", Modifier.align(Alignment.Center)) } Spacer(Modifier.requiredSize(5.dp)) Row { Box( Modifier .size(50.dp) .background(hueToColor(tapHue)) .border(BorderStroke(2.dp, Color.Black)) ) Text("Changes color on tap", Modifier.align(Alignment.CenterVertically)) } Spacer(Modifier.requiredSize(5.dp)) Row { Box( Modifier .size(50.dp) .clipToBounds() .background(hueToColor(doubleTapHue)) .border(BorderStroke(2.dp, Color.Black)) ) Text("Changes color on double-tap", Modifier.align(Alignment.CenterVertically)) } Spacer(Modifier.requiredSize(5.dp)) Row { Box( Modifier .size(50.dp) .clipToBounds() .background(hueToColor(longPressHue)) .border(BorderStroke(2.dp, Color.Black)) ) Text("Changes color on long press", Modifier.align(Alignment.CenterVertically)) } Spacer(Modifier.requiredSize(5.dp)) Row { Box( Modifier .size(50.dp) .clipToBounds() .background(hueToColor(pressHue)) .border(BorderStroke(2.dp, Color.Black)) ) Text("Changes color on press", Modifier.align(Alignment.CenterVertically)) } Spacer(Modifier.requiredSize(5.dp)) Row { Box( Modifier .size(50.dp) .clipToBounds() .background(hueToColor(releaseHue)) .border(BorderStroke(2.dp, Color.Black)) ) Text("Changes color on release", Modifier.align(Alignment.CenterVertically)) } Spacer(Modifier.requiredSize(5.dp)) Row { Box( Modifier .size(50.dp) .clipToBounds() .background(hueToColor(cancelHue)) .border(BorderStroke(2.dp, Color.Black)) ) Text("Changes color on cancel", Modifier.align(Alignment.CenterVertically)) } } } @Composable fun TouchSlopDragGestures() { Column { var width by remember { mutableStateOf(0f) } Box( Modifier.fillMaxWidth() .background(Color.Cyan) .onSizeChanged { width = it.width.toFloat() } ) { var offset by remember { mutableStateOf(0.dp) } Box( Modifier.offset(offset, 0.dp) .requiredSize(50.dp) .background(Color.Blue) .pointerInput(Unit) { detectHorizontalDragGestures { _, dragDistance -> val offsetPx = offset.toPx() val newOffset = (offsetPx + dragDistance).coerceIn(0f, width - 50.dp.toPx()) val consumed = newOffset - offsetPx if (consumed != 0f) { offset = newOffset.toDp() } } } ) Text("Drag blue box within here", Modifier.align(Alignment.Center)) } Box(Modifier.weight(1f)) { var height by remember { mutableStateOf(0f) } Box( Modifier.fillMaxHeight() .background(Color.Yellow) .onSizeChanged { height = it.height.toFloat() } ) { var offset by remember { mutableStateOf(0.dp) } Box( Modifier.offset(0.dp, offset) .requiredSize(50.dp) .background(Color.Red) .pointerInput(Unit) { detectVerticalDragGestures { _, dragDistance -> val offsetPx = offset.toPx() val newOffset = (offsetPx + dragDistance) .coerceIn(0f, height - 50.dp.toPx()) val consumed = newOffset - offsetPx if (consumed != 0f) { offset = newOffset.toDp() } } } ) } Box( Modifier.requiredHeight(50.dp) .fillMaxWidth() .align(Alignment.TopStart) .graphicsLayer( rotationZ = 90f, transformOrigin = TransformOrigin(0f, 1f) ) ) { Text( "Drag red box within here", Modifier.align(Alignment.Center) ) } } } } @Composable fun OrientationLockDragGestures() { var size by remember { mutableStateOf(IntSize.Zero) } var offsetX by remember { mutableStateOf(0.dp) } var offsetY by remember { mutableStateOf(0.dp) } Box( Modifier.onSizeChanged { size = it }.pointerInput(Unit) { detectVerticalDragGestures { _, dragAmount -> offsetY = (offsetY.toPx() + dragAmount) .coerceIn(0f, size.height.toFloat() - 50.dp.toPx()).toDp() } } ) { Box( Modifier.offset(offsetX, 0.dp) .background(Color.Blue.copy(alpha = 0.5f)) .requiredWidth(50.dp) .fillMaxHeight() .pointerInput(Unit) { detectHorizontalDragGestures { _, dragAmount -> offsetX = (offsetX.toPx() + dragAmount) .coerceIn(0f, size.width.toFloat() - 50.dp.toPx()).toDp() } } ) Box( Modifier.offset(0.dp, offsetY) .background(Color.Red.copy(alpha = 0.5f)) .requiredHeight(50.dp) .fillMaxWidth() ) Text( "Drag the columns around. They should lock to vertical or horizontal.", Modifier.align(Alignment.Center) ) } } @Composable fun Drag2DGestures() { var size by remember { mutableStateOf(IntSize.Zero) } val offsetX = remember { mutableStateOf(0f) } val offsetY = remember { mutableStateOf(0f) } Box( Modifier.onSizeChanged { size = it }.fillMaxSize() ) { Box( Modifier.offset { IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt()) } .background(Color.Blue) .requiredSize(50.dp) .pointerInput(Unit) { detectDragGestures { _, dragAmount -> offsetX.value = (offsetX.value + dragAmount.x) .coerceIn(0f, size.width.toFloat() - 50.dp.toPx()) offsetY.value = (offsetY.value + dragAmount.y) .coerceIn(0f, size.height.toFloat() - 50.dp.toPx()) } } ) Text("Drag the box around", Modifier.align(Alignment.Center)) } } @Composable fun MultitouchArea( text: String, gestureDetector: suspend PointerInputScope.( (centroid: Offset, pan: Offset, zoom: Float, angle: Float) -> Unit, ) -> Unit ) { val matrix by remember { mutableStateOf(Matrix()) } var angle by remember { mutableStateOf(0f) } var zoom by remember { mutableStateOf(1f) } var offsetX by remember { mutableStateOf(0f) } var offsetY by remember { mutableStateOf(0f) } Box( Modifier.fillMaxSize().pointerInput(Unit) { gestureDetector { centroid, pan, gestureZoom, gestureAngle -> val anchorX = centroid.x - size.width / 2f val anchorY = centroid.y - size.height / 2f matrix.postRotate(gestureAngle, anchorX, anchorY) matrix.postScale(gestureZoom, gestureZoom, anchorX, anchorY) matrix.postTranslate(pan.x, pan.y) val v = FloatArray(9) matrix.getValues(v) offsetX = v[Matrix.MTRANS_X] offsetY = v[Matrix.MTRANS_Y] val scaleX = v[Matrix.MSCALE_X] val skewY = v[Matrix.MSKEW_Y] zoom = sqrt(scaleX * scaleX + skewY * skewY) angle = atan2(v[Matrix.MSKEW_X], v[Matrix.MSCALE_X]) * (-180 / Math.PI.toFloat()) } } ) { Box( Modifier.offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) } .graphicsLayer( scaleX = zoom, scaleY = zoom, rotationZ = angle ).drawBehind { val approximateRectangleSize = 10.dp.toPx() val numRectanglesHorizontal = (size.width / approximateRectangleSize).roundToInt() val numRectanglesVertical = (size.height / approximateRectangleSize).roundToInt() val rectangleWidth = size.width / numRectanglesHorizontal val rectangleHeight = size.height / numRectanglesVertical var hue = 0f val rectangleSize = Size(rectangleWidth, rectangleHeight) for (x in 0 until numRectanglesHorizontal) { for (y in 0 until numRectanglesVertical) { hue += 30 if (hue >= 360f) { hue = 0f } val color = hueToColor(hue) val topLeft = Offset( x = x * size.width / numRectanglesHorizontal, y = y * size.height / numRectanglesVertical ) drawRect(color = color, topLeft = topLeft, size = rectangleSize) } } } .fillMaxSize() ) Text(text) } } /** * This is a multi-touch gesture detector, including pan, zoom, and rotation. * The user can pan, zoom, and rotate once touch slop has been reached. */ @Composable fun MultitouchGestureDetector() { MultitouchArea( "Zoom, Pan, and Rotate" ) { detectTransformGestures( panZoomLock = false, onGesture = it ) } } /** * This is a multi-touch gesture detector, including pan, zoom, and rotation. * It is common to want to lean toward zoom over rotation, so this gesture detector will * lock into zoom if the first unless the rotation passes touch slop first. */ @Composable fun MultitouchLockGestureDetector() { MultitouchArea( "Zoom, Pan, and Rotate Locking to Zoom" ) { detectTransformGestures( panZoomLock = true, onGesture = it ) } } @Composable fun PointerTypeInput() { var pointerType by remember { mutableStateOf<PointerType?>(null) } Box( Modifier.pointerInput(Unit) { awaitEachGesture { val pointer = awaitPointerEvent().changes.first() pointerType = pointer.type do { val event = awaitPointerEvent() } while (event.changes.first().pressed) pointerType = null } } ) { Text("Touch or click the area to see what type of input it is.") Text("PointerType: ${pointerType ?: ""}", Modifier.align(Alignment.BottomStart)) } }
apache-2.0
0530d0605970428bb35219ef48e95504
36.947589
97
0.557262
4.880291
false
false
false
false
ftoresan/kotlin-tv
src/main/kotlin/com/github/ftoresan/domain/Person.kt
1
351
package com.github.ftoresan.domain import java.time.LocalDate import javax.persistence.* /** * Created by Fabricio Toresan on 28/05/16. */ @Entity @Table(name = "person") class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) var id : Long = 0 var name : String = "" var birthDate : LocalDate = LocalDate.now() }
mit
711c6a801b7b56de65de4dc20a57c951
16.6
51
0.675214
3.545455
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/SleepStageRecord.kt
3
3787
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.IntDef import androidx.annotation.RestrictTo import androidx.health.connect.client.records.metadata.Metadata import java.time.Instant import java.time.ZoneOffset /** * Captures the sleep stage the user entered during a sleep session. * * @see SleepSessionRecord */ public class SleepStageRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** Type of sleep stage. Required field. */ @property:StageTypes public val stage: Int, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SleepStageRecord) return false if (stage != other.stage) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false return true } override fun hashCode(): Int { var result = 0 result = 31 * result + stage.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } companion object { const val STAGE_TYPE_UNKNOWN = 0 const val STAGE_TYPE_AWAKE = 1 const val STAGE_TYPE_SLEEPING = 2 const val STAGE_TYPE_OUT_OF_BED = 3 const val STAGE_TYPE_LIGHT = 4 const val STAGE_TYPE_DEEP = 5 const val STAGE_TYPE_REM = 6 @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val STAGE_TYPE_STRING_TO_INT_MAP: Map<String, Int> = mapOf( "awake" to STAGE_TYPE_AWAKE, "sleeping" to STAGE_TYPE_SLEEPING, "out_of_bed" to STAGE_TYPE_OUT_OF_BED, "light" to STAGE_TYPE_LIGHT, "deep" to STAGE_TYPE_DEEP, "rem" to STAGE_TYPE_REM, "unknown" to STAGE_TYPE_UNKNOWN ) @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val STAGE_TYPE_INT_TO_STRING_MAP = STAGE_TYPE_STRING_TO_INT_MAP.entries.associateBy({ it.value }, { it.key }) } /** * Type of sleep stage. * @suppress */ @Retention(AnnotationRetention.SOURCE) @IntDef( value = [ STAGE_TYPE_UNKNOWN, STAGE_TYPE_AWAKE, STAGE_TYPE_SLEEPING, STAGE_TYPE_OUT_OF_BED, STAGE_TYPE_LIGHT, STAGE_TYPE_DEEP, STAGE_TYPE_REM, ] ) @RestrictTo(RestrictTo.Scope.LIBRARY) annotation class StageTypes }
apache-2.0
2b5d8e8431aa7aa59563de6513764055
32.219298
86
0.623713
4.347876
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/model/scriptTemplateProviderEP.kt
1
3766
package org.jetbrains.kotlin.core.model import org.eclipse.core.resources.IFile import org.eclipse.core.runtime.IProgressMonitor import org.eclipse.core.runtime.SubMonitor import org.jetbrains.kotlin.core.log.KotlinLogger import org.jetbrains.kotlin.script.KotlinScriptDefinition import org.jetbrains.kotlin.script.KotlinScriptDefinitionFromAnnotatedTemplate //import org.jetbrains.kotlin.script.ScriptTemplatesProvider //import org.jetbrains.kotlin.script.makeScriptDefsFromTemplatesProviders import java.io.File import java.net.URLClassLoader const val SCRIPT_TEMPLATE_PROVIDER_EP_ID = "org.jetbrains.kotlin.core.scriptTemplateProvider" const val SCRIPT_TEMPLATE_PROVIDER_EP_EX_ID = "org.jetbrains.kotlin.core.scriptTemplateProviderEx" fun loadAndCreateDefinitionsByTemplateProviders( eclipseFile: IFile, monitor: IProgressMonitor ): Pair<List<KotlinScriptDefinition>, List<String>> { //val scriptTemplateProviders = loadExecutableEP<ScriptTemplatesProvider>(SCRIPT_TEMPLATE_PROVIDER_EP_ID).mapNotNull { it.createProvider() } //val definitionsFromProviders = makeScriptDefsFromTemplatesProviders(scriptTemplateProviders) { provider, e -> // KotlinLogger.logError( // "Extension (scriptTemplateProvider) with template ${provider.templateClassNames.joinToString()} " + // "could not be initialized", e) //} val scriptTemplateProvidersEx = loadExecutableEP<ScriptTemplateProviderEx>(SCRIPT_TEMPLATE_PROVIDER_EP_EX_ID).mapNotNull { it.createProvider() } val definitionsFromProvidersEx = makeScriptDefsFromEclipseTemplatesProviders(eclipseFile, scriptTemplateProvidersEx, monitor) val onlyProvidersEx = definitionsFromProvidersEx.map { it.first } val providersClasspath = definitionsFromProvidersEx.flatMap { it.second } return Pair(/*definitionsFromProviders + */onlyProvidersEx, providersClasspath) } interface ScriptTemplateProviderEx { val templateClassName: String fun isApplicable(file: IFile): Boolean = true fun getTemplateClasspath(environment: Map<String, Any?>?, monitor: IProgressMonitor): Iterable<String> fun getEnvironment(file: IFile): Map<String, Any?>? } fun makeScriptDefsFromEclipseTemplatesProviders( eclipseFile: IFile, providers: Iterable<ScriptTemplateProviderEx>, monitor: IProgressMonitor ): List<Pair<KotlinScriptDefinition, Iterable<String>>> { return providers .filter { it.isApplicable(eclipseFile) } .map { provider: ScriptTemplateProviderEx -> try { val subMonitor = SubMonitor.convert(monitor) val templateClasspath = provider.getTemplateClasspath(provider.getEnvironment(eclipseFile), subMonitor) if (subMonitor.isCanceled) return@map null val loader = URLClassLoader( templateClasspath.map { File(it).toURI().toURL() }.toTypedArray(), ScriptTemplateProviderEx::class.java.classLoader ) val cl = loader.loadClass(provider.templateClassName) Pair(KotlinScriptDefinitionFromAnnotatedTemplate(cl.kotlin, provider.getEnvironment(eclipseFile), templateClasspath.map{File(it)}.toList()), templateClasspath) } catch (ex: Exception) { KotlinLogger.logError( "Extension (EclipseScriptTemplateProvider) ${provider::class.java.name} with templates ${provider.templateClassName} " + "could not be initialized", ex) null } } .filterNotNull() }
apache-2.0
617d1d4235b475c600f076dd363dd64a
49.905405
179
0.695698
5.089189
false
false
false
false
veyndan/reddit-client
app/src/main/java/com/veyndan/paper/reddit/ui/recyclerview/itemdecoration/TreeInsetItemDecoration.kt
2
1482
package com.veyndan.paper.reddit.ui.recyclerview.itemdecoration import android.content.Context import android.graphics.Rect import android.support.annotation.DimenRes import android.support.annotation.Px import android.support.v7.widget.RecyclerView import android.view.View import com.hannesdorfmann.adapterdelegates3.ListDelegationAdapter import com.veyndan.paper.reddit.util.Node class TreeInsetItemDecoration(context: Context, @DimenRes childInsetMultiplierRes: Int) : RecyclerView.ItemDecoration() { @Px private val childInsetMultiplier: Int = context.resources.getDimensionPixelOffset(childInsetMultiplierRes) override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { check(parent.adapter is ListDelegationAdapter<*>) { "RecyclerView's Adapter must implement ListDelegationAdapter<List<Node<?>>> in order for TreeInsetItemDecoration to be used as a decoration" } val listDelegationAdapter: ListDelegationAdapter<List<Node<*>>> = parent.adapter as ListDelegationAdapter<List<Node<*>>> val position: Int = parent.getChildAdapterPosition(view) val nodes: List<Node<*>> = listDelegationAdapter.items val inset: Int = if (position == RecyclerView.NO_POSITION) 0 else { val depth: Int = nodes[position].depth depth * childInsetMultiplier } outRect.set(inset, 0, 0, 0) } }
mit
ad42381d4941ad019d3e4ea984fa4082
45.3125
202
0.72942
4.689873
false
false
false
false
nurkiewicz/ts.class
src/main/kotlin/com/nurkiewicz/tsclass/codegen/Bytecode.kt
1
4400
package com.nurkiewicz.tsclass.codegen import com.nurkiewicz.tsclass.parser.ast.Method import org.objectweb.asm.Label sealed class Bytecode { data class NoArg(val code: Int) : Bytecode() { override fun toString(): String = OPCODE_NAMES[code] } data class Jump(val code: Int, val label: Label) : Bytecode() { override fun toString(): String = OPCODE_NAMES[code] + " " + label } data class LabelPlace(val label: Label) : Bytecode() { override fun toString(): String = label.toString() } data class IntArg(val code: Int, val arg: Int) : Bytecode() { override fun toString(): String = OPCODE_NAMES[code] + " " + arg } data class DoubleArg(val code: Int, val arg: Double) : Bytecode() { override fun toString(): String = OPCODE_NAMES[code] + " " + arg } data class Call(val code: Int, val owner: String, val method: Method, val isInterface: Boolean) : Bytecode() { override fun toString(): String = "${OPCODE_NAMES[code]} $owner.${method.name}(${method.parameters})" } companion object { val OPCODE_NAMES = listOf("nop", "aconst_null", "iconst_m1", "iconst_0", "iconst_1", "iconst_2", "iconst_3", "iconst_4", "iconst_5", "lconst_0", "lconst_1", "fconst_0", "fconst_1", "fconst_2", "dconst_0", "dconst_1", "bipush", "sipush", "ldc", "ldc_w", "ldc2_w", "iload", "lload", "fload", "dload", "aload", "iload_0", "iload_1", "iload_2", "iload_3", "lload_0", "lload_1", "lload_2", "lload_3", "fload_0", "fload_1", "fload_2", "fload_3", "dload_0", "dload_1", "dload_2", "dload_3", "aload_0", "aload_1", "aload_2", "aload_3", "iaload", "laload", "faload", "daload", "aaload", "baload", "caload", "saload", "istore", "lstore", "fstore", "dstore", "astore", "istore_0", "istore_1", "istore_2", "istore_3", "lstore_0", "lstore_1", "lstore_2", "lstore_3", "fstore_0", "fstore_1", "fstore_2", "fstore_3", "dstore_0", "dstore_1", "dstore_2", "dstore_3", "astore_0", "astore_1", "astore_2", "astore_3", "iastore", "lastore", "fastore", "dastore", "aastore", "bastore", "castore", "sastore", "pop", "pop2", "dup", "dup_x1", "dup_x2", "dup2", "dup2_x1", "dup2_x2", "swap", "iadd", "ladd", "fadd", "dadd", "isub", "lsub", "fsub", "dsub", "imul", "lmul", "fmul", "dmul", "idiv", "ldiv", "fdiv", "ddiv", "irem", "lrem", "frem", "drem", "ineg", "lneg", "fneg", "dneg", "ishl", "lshl", "ishr", "lshr", "iushr", "lushr", "iand", "land", "ior", "lor", "ixor", "lxor", "iinc", "i2l", "i2f", "i2d", "l2i", "l2f", "l2d", "f2i", "f2l", "f2d", "d2i", "d2l", "d2f", "i2b", "i2c", "i2s", "lcmp", "fcmpl", "fcmpg", "dcmpl", "dcmpg", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "if_icmpeq", "if_icmpne", "if_icmplt", "if_icmpge", "if_icmpgt", "if_icmple", "if_acmpeq", "if_acmpne", "goto", "jsr", "ret", "tableswitch", "lookupswitch", "ireturn", "lreturn", "freturn", "dreturn", "areturn", "return", "getstatic", "putstatic", "getfield", "putfield", "invokevirtual", "invokespecial", "invokestatic", "invokeinterface", "<UNKNOWN>", "new", "newarray", "anewarray", "arraylength", "athrow", "checkcast", "instanceof", "monitorenter", "monitorexit", "wide", "multianewarray", "ifnull", "ifnonnull", "goto_w", "jsr_w", "breakpoint", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "<UNKNOWN>", "impdep1", "impdep2") } }
apache-2.0
45dbf6dafab338ad5976f9c35a2291a2
64.671642
133
0.520909
3.174603
false
false
false
false
ligee/kotlin-jupyter
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/KotlinKernelHost.kt
1
2321
package org.jetbrains.kotlinx.jupyter.api import org.jetbrains.kotlinx.jupyter.api.libraries.CodeExecution import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition /** * Interface representing kernel engine, the core facility for compiling and executing code snippets */ interface KotlinKernelHost { /** * Try to display the given value. It is only displayed if it's an instance of [Renderable] * or may be converted to it */ fun display(value: Any) /** * Updates display data with given [id] with the new [value] */ fun updateDisplay(value: Any, id: String? = null) /** * Schedules execution of the given [execution] after the completing of execution of the current cell */ fun scheduleExecution(execution: ExecutionCallback<*>) fun scheduleExecution(execution: Code) = scheduleExecution(CodeExecution(execution).toExecutionCallback()) /** * Executes code immediately. Note that it may lead to breaking the kernel state in some cases */ fun execute(code: Code): FieldValue fun addLibrary(library: LibraryDefinition) = addLibraries(listOf(library)) /** * Adds new libraries via their definition. Fully interchangeable with `%use` approach */ fun addLibraries(libraries: Collection<LibraryDefinition>) /** * Says whether this [typeName] should be loaded as integration based on loaded libraries. * `null` means that loaded libraries don't care about this [typeName]. */ fun acceptsIntegrationTypeName(typeName: String): Boolean? /** * Loads Kotlin standard artifacts (org.jetbrains.kotlin:kotlin-$name:$version) * * @param artifacts Names of the artifacts substituted to the above line * @param version Version of the artifacts to load. Current Kotlin version will be used by default */ fun loadKotlinArtifacts(artifacts: Collection<String>, version: String? = null) /** * Loads Kotlin standard library extensions for a current JDK * * @param version Version of the artifact to load. Current Kotlin version will be used by default */ fun loadStdlibJdkExtensions(version: String? = null) /** * Declares global variables for notebook */ fun declare(variables: Iterable<VariableDeclaration>) }
apache-2.0
68e99802dd59b255968868bea9f6dc66
34.707692
110
0.707454
4.815353
false
false
false
false
SecUSo/privacy-friendly-qr-scanner
app/src/main/java/com/secuso/privacyfriendlycodescanner/qrscanner/ui/helpers/GeneratorKeyboardListener.kt
1
2680
package com.secuso.privacyfriendlycodescanner.qrscanner.ui.helpers import android.os.Build import android.transition.TransitionManager import android.util.DisplayMetrics import android.view.ViewTreeObserver import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import kotlin.math.roundToInt /** * This is an OnGlobalLayoutListener for generator activities. It detects if the on screen keyboard * is open or closed based on layout changes and updates the layout accordingly. If the keyboard is * open the generate button gets moved to the right and shrinks. If the keyboard is hidden the * generate button gets centered and expands. */ class GeneratorKeyboardListener( private val rootView: ConstraintLayout, private val generateButton: ExtendedFloatingActionButton, private val generateButtonResourceId: Int, private val displayDensityDpi: Int ) : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val heightChange = rootView.rootView.height - rootView.height if (heightChange > convertDpToPixel(200, displayDensityDpi)) { //keyboard is open if (generateButton.isExtended) { val buttonRightSet = ConstraintSet() buttonRightSet.clone(rootView) buttonRightSet.clear(generateButtonResourceId, ConstraintSet.START) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { TransitionManager.beginDelayedTransition(rootView) } buttonRightSet.applyTo(rootView) generateButton.shrink() } } else { //keyboard is hidden if (!generateButton.isExtended) { val buttonBaseSet = ConstraintSet() buttonBaseSet.clone(rootView) buttonBaseSet.connect( generateButtonResourceId, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 16 ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { TransitionManager.beginDelayedTransition(rootView) } buttonBaseSet.applyTo(rootView) generateButton.extend() } } } private fun convertDpToPixel(dp: Int, displayDensityDpi: Int): Int { return (dp.toFloat() * (displayDensityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)).roundToInt() } }
gpl-3.0
523958c3f1f820537b7d88250d2db78c
40.246154
107
0.66306
5.414141
false
false
false
false