content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// "Replace with 'emptySequence()' call" "true" // WITH_RUNTIME fun foo(a: String?): Sequence<String> { val w = a ?: return null<caret> return sequenceOf(w) }
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/wrapWithCollectionLiteral/returnEmptySequence.kt
3475234418
package com.alexstyl.specialdates.facebook import java.net.URI object FacebookImagePath { private const val SIZE = 700 private const val IMG_URL = "https://graph.facebook.com/%s/picture?width=$SIZE&height=$SIZE" fun forUid(uid: Long): URI { return URI.create(String.format(IMG_URL, uid)) } }
memento/src/main/java/com/alexstyl/specialdates/facebook/FacebookImagePath.kt
1955233314
package com.intellij.ide.starter.profiler enum class ProfilerType(val kind: String) { YOURKIT("YOURKIT"), ASYNC("ASYNC"), NONE("NONE"); }
tools/intellij.ide.starter/src/com/intellij/ide/starter/profiler/ProfilerType.kt
2697038501
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.replaceWith import com.intellij.codeInsight.hint.HintManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.base.fe10.analysis.getAnnotationValue import org.jetbrains.kotlin.base.fe10.analysis.getArrayValue import org.jetbrains.kotlin.base.fe10.analysis.getStringValue import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInliner.CallableUsageReplacementStrategy import org.jetbrains.kotlin.idea.codeInliner.ClassUsageReplacementStrategy import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy import org.jetbrains.kotlin.idea.core.OptionalParametersHelper import org.jetbrains.kotlin.idea.intentions.isInvokeOperator import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.idea.util.application.isDispatchThread import org.jetbrains.kotlin.idea.util.replaceOrCreateTypeArgumentList import org.jetbrains.kotlin.ir.expressions.typeParametersCount import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.isCallee import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.constants.StringValue import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.* //TODO: different replacements for property accessors abstract class DeprecatedSymbolUsageFixBase( element: KtReferenceExpression, val replaceWith: ReplaceWithData ) : KotlinQuickFixAction<KtReferenceExpression>(element) { internal val isAvailable: Boolean init { assert(!isDispatchThread()) { "${javaClass.name} should not be created on EDT" } isAvailable = buildUsageReplacementStrategy( element, replaceWith, recheckAnnotation = true, reformat = false )?.let { it.createReplacer(element) != null } == true } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && isAvailable final override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expression = element ?: return val strategy = buildUsageReplacementStrategy( expression, replaceWith, recheckAnnotation = false, reformat = true, editor = editor ) ?: return invoke(strategy, project, editor) } protected abstract operator fun invoke(replacementStrategy: UsageReplacementStrategy, project: Project, editor: Editor?) companion object { fun fetchReplaceWithPattern( descriptor: DeclarationDescriptor, project: Project, contextElement: KtReferenceExpression?, replaceInWholeProject: Boolean ): ReplaceWithData? { val annotation = descriptor.annotations.findAnnotation(StandardNames.FqNames.deprecated) ?: return null val replaceWithValue = annotation.getAnnotationValue(Deprecated::replaceWith) ?: return null val pattern = replaceWithValue.getStringValue(ReplaceWith::expression)?.takeIf { it.isNotEmpty() } ?: return null val imports = replaceWithValue.getArrayValue(ReplaceWith::imports)?.mapAll { (it as? StringValue)?.value } ?: return null // should not be available for descriptors with optional parameters if we cannot fetch default values for them (currently for library with no sources) if (descriptor is CallableDescriptor && descriptor.valueParameters.any { it.hasDefaultValue() && OptionalParametersHelper.defaultParameterValue(it, project) == null } ) return null return if (replaceInWholeProject) { ReplaceWithData(pattern, imports, true) } else { ReplaceWithData(pattern.applyContextElement(contextElement, descriptor), imports, false) } } private fun String.applyContextElement( element: KtReferenceExpression?, descriptor: DeclarationDescriptor ): String { if (element == null) return this val psiFactory = KtPsiFactory(element) val expressionFromPattern = psiFactory.createExpressionIfPossible(this) ?: return this val classLiteral = when (expressionFromPattern) { is KtClassLiteralExpression -> expressionFromPattern is KtDotQualifiedExpression -> expressionFromPattern.receiverExpression as? KtClassLiteralExpression else -> null } if (classLiteral != null) { val receiver = classLiteral.receiverExpression ?: return this val typeParameterText = (descriptor as? CallableDescriptor)?.typeParameters?.firstOrNull()?.name?.asString() ?: return this if (receiver.text != typeParameterText) return this val typeReference = (element.parent as? KtCallExpression)?.typeArguments?.firstOrNull()?.typeReference ?: return this val type = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] if (type != null && KotlinBuiltIns.isArray(type)) { receiver.replace(typeReference) } else { receiver.replace(psiFactory.createExpression(typeReference.text.takeWhile { it != '<' })) } return expressionFromPattern.text } if (expressionFromPattern !is KtCallExpression) return this val methodFromPattern = expressionFromPattern.referenceExpression()?.let { name -> KotlinShortNamesCache(element.project).getMethodsByName( name.text, element.resolveScope ).firstOrNull() } val patternTypeArgumentList = expressionFromPattern.typeArgumentList val patternTypeArgumentCount = methodFromPattern?.typeParameterList?.typeParameters?.size ?: patternTypeArgumentList?.arguments?.size ?: return this val typeArgumentList = (element.parent as? KtCallExpression)?.typeArgumentList ?: (element.parent as? KtUserType)?.typeArgumentList val descriptorTypeParameterCount = (descriptor as? CallableDescriptor)?.typeParametersCount ?: (descriptor as? ClassDescriptor)?.declaredTypeParameters?.size return if (patternTypeArgumentCount == descriptorTypeParameterCount || patternTypeArgumentCount == typeArgumentList?.arguments?.size ) { if (typeArgumentList != null) expressionFromPattern.replaceOrCreateTypeArgumentList(typeArgumentList.copy() as KtTypeArgumentList) else patternTypeArgumentList?.delete() expressionFromPattern.text } else this } data class Data( val referenceExpression: KtReferenceExpression, val replaceWith: ReplaceWithData, val descriptor: DeclarationDescriptor ) fun extractDataFromDiagnostic(deprecatedDiagnostic: Diagnostic, replaceInWholeProject: Boolean): Data? { val referenceExpression = when (val psiElement = deprecatedDiagnostic.psiElement) { is KtArrayAccessExpression -> psiElement is KtSimpleNameExpression -> psiElement is KtConstructorCalleeExpression -> psiElement.constructorReferenceExpression else -> null } ?: return null val descriptor = when (deprecatedDiagnostic.factory) { Errors.DEPRECATION -> DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION).a Errors.DEPRECATION_ERROR -> DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION_ERROR).a Errors.TYPEALIAS_EXPANSION_DEPRECATION -> DiagnosticFactory.cast(deprecatedDiagnostic, Errors.TYPEALIAS_EXPANSION_DEPRECATION).b Errors.TYPEALIAS_EXPANSION_DEPRECATION_ERROR -> DiagnosticFactory.cast(deprecatedDiagnostic, Errors.TYPEALIAS_EXPANSION_DEPRECATION_ERROR).b else -> throw IllegalStateException("Bad QuickFixRegistrar configuration") } val replacement = fetchReplaceWithPattern(descriptor, referenceExpression.project, referenceExpression, replaceInWholeProject) ?: return null return Data(referenceExpression, replacement, descriptor) } private fun buildUsageReplacementStrategy( element: KtReferenceExpression, replaceWith: ReplaceWithData, recheckAnnotation: Boolean, reformat: Boolean, editor: Editor? = null ): UsageReplacementStrategy? { val resolutionFacade = element.getResolutionFacade() val bindingContext = resolutionFacade.analyze(element, BodyResolveMode.PARTIAL) val resolvedCall = element.getResolvedCall(bindingContext) var target = resolvedCall?.resultingDescriptor?.takeIf { it.isInvokeOperator } ?: element.mainReference.resolveToDescriptors(bindingContext).singleOrNull() ?: return null var replacePatternFromSymbol = fetchReplaceWithPattern(target, resolutionFacade.project, element, replaceWith.replaceInWholeProject) if (replacePatternFromSymbol == null && target is ConstructorDescriptor) { target = target.containingDeclaration replacePatternFromSymbol = fetchReplaceWithPattern(target, resolutionFacade.project, element, replaceWith.replaceInWholeProject) } // check that ReplaceWith hasn't changed if (recheckAnnotation && replacePatternFromSymbol != replaceWith) return null when (target) { is CallableDescriptor -> { if (resolvedCall == null) return null if (!resolvedCall.isReallySuccess()) return null val replacement = ReplaceWithAnnotationAnalyzer.analyzeCallableReplacement( replaceWith, target, resolutionFacade, reformat ) ?: return null return CallableUsageReplacementStrategy(replacement, inlineSetter = false) } is ClassifierDescriptorWithTypeParameters -> { val replacementType = ReplaceWithAnnotationAnalyzer.analyzeClassifierReplacement(replaceWith, target, resolutionFacade) return when { replacementType != null -> { if (editor != null) { val typeAlias = element .getStrictParentOfType<KtUserType>() ?.getStrictParentOfType<KtTypeReference>() ?.getStrictParentOfType<KtTypeAlias>() if (typeAlias != null) { val usedConstructorWithOwnReplaceWith = usedConstructorsWithOwnReplaceWith( element.project, target, typeAlias, element, replaceWith.replaceInWholeProject ) if (usedConstructorWithOwnReplaceWith != null) { val constructorStr = DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render( usedConstructorWithOwnReplaceWith ) HintManager.getInstance().showErrorHint( editor, KotlinBundle.message( "there.is.own.replacewith.on.0.that.is.used.through.this.alias.please.replace.usages.first", constructorStr ) ) return null } } } //TODO: check that it's really resolved and is not an object otherwise it can be expression as well ClassUsageReplacementStrategy(replacementType, null, element.project) } target is ClassDescriptor -> { val constructor = target.unsubstitutedPrimaryConstructor ?: return null val replacementExpression = ReplaceWithAnnotationAnalyzer.analyzeCallableReplacement( replaceWith, constructor, resolutionFacade, reformat ) ?: return null ClassUsageReplacementStrategy(null, replacementExpression, element.project) } else -> null } } else -> return null } } private fun usedConstructorsWithOwnReplaceWith( project: Project, classifier: ClassifierDescriptorWithTypeParameters, typeAlias: PsiElement, contextElement: KtReferenceExpression, replaceInWholeProject: Boolean ): ConstructorDescriptor? { val specialReplaceWithForConstructor = classifier.constructors.filter { fetchReplaceWithPattern(it, project, contextElement, replaceInWholeProject) != null }.toSet() if (specialReplaceWithForConstructor.isEmpty()) { return null } val searchAliasConstructorUsagesScope = GlobalSearchScope.allScope(project).restrictToKotlinSources() ReferencesSearch.search(typeAlias, searchAliasConstructorUsagesScope).find { reference -> val element = reference.element if (element is KtSimpleNameExpression && element.isCallee()) { val aliasConstructors = element.resolveMainReferenceToDescriptors().filterIsInstance<TypeAliasConstructorDescriptor>() for (referenceConstructor in aliasConstructors) { if (referenceConstructor.underlyingConstructorDescriptor in specialReplaceWithForConstructor) { return referenceConstructor.underlyingConstructorDescriptor } } } false } return null } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFixBase.kt
3139406872
// RUNTIME package test import bar.r import bar.foo3 fun main() { val fooLocal = 3 r { foo<caret> } } // ORDER: foo6 // ORDER: foo2 // ORDER: foo3 // ORDER: foo4 // ORDER: fooLocal // ORDER: foo5 // ORDER: foo1
plugins/kotlin/completion/tests/testData/weighers/basic/DslMemberCalls.kt
4001997458
package com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.ctld import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testLvmCapability import io.github.kerubistan.kroki.size.GB internal class CtldIscsiShareTest : OperationalStepVerifications() { override val step = CtldIscsiShare( host = testHost, allocation = VirtualStorageLvmAllocation( vgName = testLvmCapability.volumeGroupName, capabilityId = testLvmCapability.id, hostId = testHost.id, path = "/dev/blah/${testDisk.id}", actualSize = 1.GB ), vstorage = testDisk ) }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/iscsi/ctld/CtldIscsiShareTest.kt
3420565153
package com.github.kerubistan.kerub.planner.steps.storage.lvm.pool.create import com.github.kerubistan.kerub.data.config.HostConfigurationDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.config.LvmPoolConfiguration import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LogicalVolume import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmLv import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmThinLv import com.github.kerubistan.kerub.utils.junix.storagemanager.lvm.LvmVg import io.github.kerubistan.kroki.numbers.compareTo import io.github.kerubistan.kroki.numbers.times class CreateLvmPoolExecutor( private val hostCommandExecutor: HostCommandExecutor, private val hostCfgDao: HostConfigurationDao ) : AbstractStepExecutor<CreateLvmPool, LogicalVolume>() { override fun prepare(step: CreateLvmPool) = hostCommandExecutor.execute(step.host) { LvmVg.list(session = it, vgName = step.vgName).single().let { val expectedFreeSpace = step.size * 1.01 check(it.freeSize >= expectedFreeSpace) { "volume group ${step.vgName} on host ${step.host.address} is expected to have at least " + "$expectedFreeSpace but only have ${it.freeSize}" } } } override fun perform(step: CreateLvmPool) = hostCommandExecutor.execute(step.host) { LvmThinLv.createPool(it, step.vgName, step.name, step.size, step.size / 100.toBigInteger()) LvmLv.list(it, step.vgName, step.name).single() } override fun update(step: CreateLvmPool, updates: LogicalVolume) { hostCfgDao.update(step.host.id, retrieve = { hostCfgDao[it] ?: HostConfiguration(id = step.host.id) }, change = { hostCfg -> hostCfg.copy( storageConfiguration = hostCfg.storageConfiguration + LvmPoolConfiguration( vgName = step.vgName, size = updates.size, poolName = step.name ) ) } ) } }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/pool/create/CreateLvmPoolExecutor.kt
1415064852
// 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.findUsages import com.intellij.find.findUsages.FindUsagesManager import com.intellij.find.findUsages.FindUsagesOptions import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.light.LightMemberReference import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.usageView.UsageInfo import com.intellij.util.Query import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull fun KtDeclaration.processAllExactUsages( options: FindUsagesOptions, processor: (UsageInfo) -> Unit ) { fun elementsToCheckReferenceAgainst(reference: PsiReference): List<PsiElement> { if (reference is KtReference) return listOf(this) return SmartList<PsiElement>().also { list -> list += this list += toLightElements() if (this is KtConstructor<*>) { list.addIfNotNull(getContainingClassOrObject().toLightClass()) } } } FindUsagesManager(project).getFindUsagesHandler(this, true)?.processElementUsages( this, { usageInfo -> val reference = usageInfo.reference ?: return@processElementUsages true if (reference is LightMemberReference || elementsToCheckReferenceAgainst(reference).any { reference.isReferenceTo(it) }) { processor(usageInfo) } true }, options ) } fun KtDeclaration.processAllUsages( options: FindUsagesOptions, processor: (UsageInfo) -> Unit ) { val findUsagesHandler = KotlinFindUsagesHandlerFactory(project).createFindUsagesHandler(this, true) findUsagesHandler.processElementUsages( this, { processor(it) true }, options ) } object ReferencesSearchScopeHelper { fun search(declaration: KtDeclaration, defaultScope: SearchScope? = null): Query<PsiReference> { val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(declaration) return when { enclosingElement != null -> ReferencesSearch.search(declaration, LocalSearchScope(enclosingElement)) defaultScope != null -> ReferencesSearch.search(declaration, defaultScope) else -> ReferencesSearch.search(declaration) } } }
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/findUsageUtils.kt
1797927408
package com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.tgtd import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.model.Host import org.apache.sshd.client.session.ClientSession import java.io.InputStream // because it is a nightmare to mock function literals class HostCommandExecutorStub(private val session: ClientSession) : HostCommandExecutor { override fun readRemoteFile(host: Host, path: String): InputStream { TODO() } override fun <T> execute(host: Host, closure: (ClientSession) -> T): T { return closure(session) } override fun <T> dataConnection(host: Host, action: (ClientSession) -> T): T { return action(session) } }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/iscsi/tgtd/HostCommandExecutorStub.kt
1468807108
// "Replace usages of 'oldFun(Int): Unit' in whole project" "true" import pack.oldFun fun foo() { <caret>oldFun(0) oldFun(2) } fun bar() { oldFun(3) }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/wholeProject/function.before.Main.kt
2419375061
interface I interface Z<T> open class A<T : I, U : I, V>
plugins/kotlin/idea/tests/testData/refactoring/pullUp/j2k/fromClassToClassWithGenerics.kt
431834932
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.lang.properties.psi.impl.PropertyImpl import com.intellij.lang.properties.psi.impl.PropertyKeyImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.IncorrectOperationException import com.intellij.util.PsiNavigateUtil import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.util.PsiUtil /** * Highlights key in `registry.properties` without matching `key.description` entry + corresponding quickfix. */ class RegistryPropertiesAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (element !is PropertyKeyImpl) return val file = holder.currentAnnotationSession.file if (!isRegistryPropertiesFile(file)) { return } val propertyName = element.text if (isImplicitUsageKey(propertyName)) { return } val groupName = propertyName.substringBefore('.').toLowerCase() @Suppress("HardCodedStringLiteral") if (PLUGIN_GROUP_NAMES.contains(groupName) || propertyName.startsWith("editor.config.")) { holder.newAnnotation(HighlightSeverity.ERROR, DevKitBundle.message("registry.properties.annotator.plugin.keys.use.ep")) .withFix(ShowEPDeclarationIntention(propertyName)).create() } val propertiesFile = file as PropertiesFile val descriptionProperty = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX) if (descriptionProperty == null) { holder.newAnnotation(HighlightSeverity.WARNING, DevKitBundle.message("registry.properties.annotator.key.no.description.key", propertyName)) .withFix(AddDescriptionKeyIntention(propertyName)).create() } } private class ShowEPDeclarationIntention(private val propertyName: String) : IntentionAction { override fun startInWriteAction(): Boolean = false override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.show.ep.family.name") override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = true override fun getText(): String = DevKitBundle.message("registry.properties.annotator.show.ep.name", propertyName) override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val propertiesFile = file as PropertiesFile val defaultValue = propertiesFile.findPropertyByKey(propertyName)!!.value val description = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX)?.value @NonNls var restartRequiredText = "" if (propertiesFile.findPropertyByKey(propertyName + RESTART_REQUIRED_SUFFIX) != null) { restartRequiredText = "restartRequired=\"true\"" } val epText = """ <registryKey key="${propertyName}" defaultValue="${defaultValue}" ${restartRequiredText} description="${description}"/> """.trimIndent() Messages.showMultilineInputDialog(project, DevKitBundle.message("registry.properties.annotator.show.ep.message"), DevKitBundle.message("registry.properties.annotator.show.ep.title"), epText, null, null) } } private class AddDescriptionKeyIntention(private val myPropertyName: String) : IntentionAction { @Nls override fun getText(): String = DevKitBundle.message("registry.properties.annotator.add.description.text", myPropertyName) @Nls override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.add.description.family.name") override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean = true @Suppress("HardCodedStringLiteral") @Throws(IncorrectOperationException::class) override fun invoke(project: Project, editor: Editor, file: PsiFile) { val propertiesFile = file as PropertiesFile val originalProperty = propertiesFile.findPropertyByKey(myPropertyName) as PropertyImpl? val descriptionProperty = propertiesFile.addPropertyAfter(myPropertyName + DESCRIPTION_SUFFIX, "Description", originalProperty) val valueNode = (descriptionProperty.psiElement as PropertyImpl).valueNode!! PsiNavigateUtil.navigate(valueNode.psi) } override fun startInWriteAction(): Boolean = true } companion object { @NonNls private val PLUGIN_GROUP_NAMES = setOf( "appcode", "cidr", "clion", "cvs", "git", "github", "svn", "hg4idea", "tfs", "dart", "markdown", "java", "javac", "uast", "junit4", "dsm", "js", "javascript", "typescript", "nodejs", "eslint", "jest", "ruby", "rubymine", "groovy", "grails", "python", "php", "kotlin" ) @NonNls private const val REGISTRY_PROPERTIES_FILENAME = "registry.properties" @NonNls const val DESCRIPTION_SUFFIX = ".description" @NonNls const val RESTART_REQUIRED_SUFFIX = ".restartRequired" @JvmStatic fun isImplicitUsageKey(keyName: String): Boolean = StringUtil.endsWith(keyName, DESCRIPTION_SUFFIX) || StringUtil.endsWith(keyName, RESTART_REQUIRED_SUFFIX) @JvmStatic fun isRegistryPropertiesFile(psiFile: PsiFile): Boolean = PsiUtil.isIdeaProject(psiFile.project) && psiFile.name == REGISTRY_PROPERTIES_FILENAME } }
plugins/devkit/devkit-core/src/inspections/RegistryPropertiesAnnotator.kt
400920538
val foo: <warning descr="SSR">Int?</warning> = 1 var bar: Int = 1
plugins/kotlin/idea/tests/testData/structuralsearch/typeReference/standaloneNullable.kt
2644117308
val s = <selection>10</selection>.toString()
plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/introduceToFile.kt
1829643784
val foo: <selection><caret>Int?</selection> = 1
plugins/kotlin/idea/tests/testData/wordSelection/DefiningVariable/2.kt
2963967639
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.ui import android.content.Context import android.graphics.* import android.graphics.Bitmap.Config.ARGB_8888 import android.graphics.Paint.ANTI_ALIAS_FLAG import android.graphics.Paint.SUBPIXEL_TEXT_FLAG import android.graphics.PorterDuff.Mode.CLEAR import android.graphics.drawable.Drawable import android.support.annotation.ColorInt import android.text.TextPaint import android.util.AttributeSet import android.view.Gravity import com.sinyuk.fanfou.R import com.sinyuk.fanfou.util.px2dp /** * Created by sinyuk on 2018/1/25. * <p> * A view group that draws a badge drawable on top of it's contents. * <p/> */ class BadgedImageView(context: Context, attrs: AttributeSet) : SquareImageView(context, attrs) { var drawBadge = false private val badge: Drawable private var badgeBoundsSet = false private val badgeGravity: Int private val badgePadding: Int init { badge = GifBadge(context) val a = context.obtainStyledAttributes(attrs, R.styleable.BadgedImageView, 0, 0) badgeGravity = a.getInt(R.styleable.BadgedImageView_badgeGravity, Gravity.END or Gravity .BOTTOM) badgePadding = a.getDimensionPixelSize(R.styleable.BadgedImageView_badgePadding, px2dp(context, 8f)) a.recycle() } fun setBadgeColor(@ColorInt color: Int) { badge.setColorFilter(color, PorterDuff.Mode.SRC_IN) } val badgeBounds: Rect get() { if (!badgeBoundsSet) { layoutBadge() } return badge.bounds } override fun draw(canvas: Canvas) { super.draw(canvas) if (drawBadge) { if (!badgeBoundsSet) { layoutBadge() } badge.draw(canvas) } } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) layoutBadge() } private fun layoutBadge() { val badgeBounds = badge.bounds Gravity.apply(badgeGravity, badge.intrinsicWidth, badge.intrinsicHeight, Rect(0, 0, width, height), badgePadding, badgePadding, badgeBounds) badge.bounds = badgeBounds badgeBoundsSet = true } /** * A drawable for indicating that an image is animated */ private class GifBadge internal constructor(context: Context) : Drawable() { private val paint = Paint() init { if (bitmap == null) { val dm = context.resources.displayMetrics val density = dm.density val scaledDensity = dm.scaledDensity val textPaint = TextPaint(ANTI_ALIAS_FLAG or SUBPIXEL_TEXT_FLAG) textPaint.typeface = Typeface.create(TYPEFACE, TYPEFACE_STYLE) textPaint.textSize = TEXT_SIZE * scaledDensity val padding = PADDING * density val textBounds = Rect() textPaint.getTextBounds(GIF, 0, GIF.length, textBounds) val height = padding + textBounds.height() + padding val width = padding + textBounds.width() + padding bitmap = Bitmap.createBitmap(width.toInt(), height.toInt(), ARGB_8888).apply { setHasAlpha(true) } Canvas(bitmap).apply { val backgroundPaint = Paint(ANTI_ALIAS_FLAG) backgroundPaint.color = BACKGROUND_COLOR val cornerRadius = CORNER_RADIUS * density drawRoundRect(0f, 0f, width, height, cornerRadius, cornerRadius, backgroundPaint) // punch out the word 'GIF', leaving transparency textPaint.xfermode = PorterDuffXfermode(CLEAR) drawText(GIF, padding, height - padding, textPaint) } } } override fun getIntrinsicWidth() = bitmap?.width ?: 0 override fun getIntrinsicHeight() = bitmap?.height ?: 0 override fun draw(canvas: Canvas) { canvas.drawBitmap(bitmap, bounds.left.toFloat(), bounds.top.toFloat(), paint) } override fun setAlpha(alpha: Int) { paint.alpha = alpha } override fun setColorFilter(cf: ColorFilter?) { paint.colorFilter = cf } override fun getOpacity() = PixelFormat.TRANSLUCENT companion object { private const val GIF = "GIF" private const val TEXT_SIZE = 11 // sp private const val PADDING = 4 // dp private const val CORNER_RADIUS = 4 // dp private const val BACKGROUND_COLOR = Color.WHITE private const val TYPEFACE = "sans-serif-black" private const val TYPEFACE_STYLE = Typeface.NORMAL private var bitmap: Bitmap? = null } } }
presentation/src/main/java/com/sinyuk/fanfou/ui/BadgedImageView.kt
1839185059
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.domain.repo import android.annotation.SuppressLint import android.arch.lifecycle.MutableLiveData import android.content.SharedPreferences import com.sinyuk.fanfou.domain.ACCESS_SECRET import com.sinyuk.fanfou.domain.ACCESS_TOKEN import com.sinyuk.fanfou.domain.DO.Authorization import com.sinyuk.fanfou.domain.DO.Resource import com.sinyuk.fanfou.domain.TYPE_GLOBAL import com.sinyuk.fanfou.domain.util.XauthUtils import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import java.io.IOException import javax.inject.Named /** * Created by sinyuk on 2017/12/6. * */ class SignInTask constructor(private val account: String, private val password: String, private val client: OkHttpClient, @Named(TYPE_GLOBAL) private val preferences: SharedPreferences) : Runnable { val liveData: MutableLiveData<Resource<Authorization>> = MutableLiveData() @SuppressLint("CommitPrefEdits") override fun run() { try { val url: HttpUrl = XauthUtils.newInstance(account, password).url() val request = Request.Builder().url(url).build() val response: Response = client.newCall(request).execute() if (response.isSuccessful && response.body() != null) { val text = response.body()!!.string() val querySpilt = text.split("&") val tokenAttr = querySpilt[0].split("=".toRegex()) val secretAttr = querySpilt[1].split("=".toRegex()) val token = tokenAttr[1] val secret = secretAttr[1] preferences.edit().apply { putString(ACCESS_SECRET, secret) putString(ACCESS_TOKEN, token) }.apply() liveData.postValue(Resource.success(Authorization(token, secret))) } else { liveData.postValue(Resource.error(response.message(), null)) } } catch (e: IOException) { liveData.postValue(Resource.error(e.message, null)) } } }
domain/src/main/java/com/sinyuk/fanfou/domain/repo/SignInTask.kt
2044338006
package com.cognifide.gradle.aem.common.instance.service.workflow enum class WorkflowType(val ids: List<String>) { DAM_ASSET(listOf( "update_asset_create", "update_asset_create_without_DM", "update_asset_mod", "update_asset_mod_reupload", "update_asset_mod_without_DM", "update_asset_mod_without_DM_reupload", "dam_xmp_writeback" )); companion object { fun of(type: String) = values().find { it.name.equals(type, ignoreCase = true) } fun ids(type: String) = ids(listOf(type)) fun ids(types: Iterable<String>) = types.flatMap { of(it)?.ids ?: listOf(it) } } }
src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/workflow/WorkflowType.kt
795917439
package bj.vinylbrowser.label import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import bj.vinylbrowser.R import bj.vinylbrowser.common.BaseController import bj.vinylbrowser.customviews.MyRecyclerView import bj.vinylbrowser.main.MainActivity import bj.vinylbrowser.main.MainComponent import bj.vinylbrowser.model.common.Label import bj.vinylbrowser.model.labelrelease.LabelRelease import bj.vinylbrowser.release.ReleaseController import bj.vinylbrowser.utils.analytics.AnalyticsTracker import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import kotlinx.android.synthetic.main.controller_single_list.view.* import javax.inject.Inject /** * Created by Josh Laird on 29/05/2017. */ class LabelController(val title: String, val id: String) : BaseController(), LabelContract.View { @Inject lateinit var presenter: LabelPresenter @Inject lateinit var tracker: AnalyticsTracker @Inject lateinit var epxController: LabelEpxController lateinit var recyclerView: MyRecyclerView lateinit var toolbar: Toolbar constructor(args: Bundle) : this(args.getString("title"), args.getString("id")) override fun setupComponent(mainComponent: MainComponent) { mainComponent .labelComponentBuilder() .labelActivityModule(LabelModule(this)) .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = inflater.inflate(R.layout.controller_recyclerview, container, false) setupComponent((activity as MainActivity).mainComponent) recyclerView = view.recyclerView setupToolbar(view.toolbar, "") setupRecyclerView(recyclerView, epxController, title) presenter.fetchReleaseDetails(id) return view } override fun onAttach(view: View) { super.onAttach(view) if (view.recyclerView.adapter == null) setupRecyclerView(view.recyclerView, epxController, title) } private fun setupRecyclerView(recyclerView: MyRecyclerView?, controller: LabelEpxController, title: String?) { recyclerView?.layoutManager = LinearLayoutManager(applicationContext) recyclerView?.adapter = controller.adapter controller.setTitle(title) controller.requestModelBuild() } override fun openLink(url: String?) { tracker.send(applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.clicked), url, "1") val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) activity?.startActivity(intent) } override fun retry() { tracker.send(applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.clicked), "retry", "1") presenter.fetchReleaseDetails(args.getString("id")) } override fun displayRelease(id: String, title: String) { tracker.send(applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.label_activity), applicationContext?.getString(R.string.clicked), "labelRelease", "1") router.pushController(RouterTransaction.with(ReleaseController(title, id)) .popChangeHandler(FadeChangeHandler()) .pushChangeHandler(FadeChangeHandler()) .tag("ReleaseController")) } override fun onRestoreViewState(view: View, savedViewState: Bundle) { super.onRestoreViewState(view, savedViewState) epxController.setLabel(savedViewState.getParcelable<Label>("label")) epxController.setLabelReleases(savedViewState.getParcelableArrayList("labelReleases")) } override fun onSaveViewState(view: View, outState: Bundle) { outState.putParcelable("label", epxController.label) outState.putParcelableArrayList("labelReleases", epxController.labelReleases as ArrayList<LabelRelease>) super.onSaveViewState(view, outState) } }
app/src/main/java/bj/vinylbrowser/label/LabelController.kt
1298671950
package hu.juzraai.ted.xml.model.tedexport.links import hu.juzraai.ted.xml.model.meta.Compatible import hu.juzraai.ted.xml.model.meta.TedXmlSchemaVersion.R208 import hu.juzraai.ted.xml.model.meta.TedXmlSchemaVersion.R209 import org.simpleframework.xml.Attribute import org.simpleframework.xml.Namespace import org.simpleframework.xml.Root @Root data class Link( @field:Attribute(name = "type") @field:Namespace(prefix = "xlink", reference = "http://www.w3.org/1999/xlink") @field:Compatible(R208, R209) var type: String = "", @field:Attribute(name = "href") @field:Namespace(prefix = "xlink", reference = "http://www.w3.org/1999/xlink") @field:Compatible(R208, R209) var href: String = "", @field:Attribute(name = "title", required = false) @field:Namespace(prefix = "xlink", reference = "http://www.w3.org/1999/xlink") @field:Compatible(R208, R209) var title: String = "" )
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/links/Link.kt
521330506
package org.maxur.mserv.frame.runner import org.maxur.mserv.frame.LocatorConfig import org.maxur.mserv.frame.LocatorImpl import org.maxur.mserv.frame.kotlin.Locator import java.util.concurrent.atomic.AtomicInteger /** * The Service Locator Builder. * * @author Maxim Yunusov * @version 1.0 * @since <pre>26.08.2017</pre> */ abstract class LocatorBuilder() { companion object { private var nameCount = AtomicInteger() } protected val name get() = "locator ${nameCount.andIncrement}" /** * List of project service packages for service locator lookup. */ var packages: Set<String> = setOf() /** * Build service locator. */ fun build(init: LocatorConfig.() -> Unit): Locator = try { val locator = make() locator.configure { bind(org.maxur.mserv.frame.kotlin.Locator(locator)) bind(org.maxur.mserv.frame.java.Locator(locator)) } locator.registerAsSingleton() configure(locator) { init() } org.maxur.mserv.frame.kotlin.Locator(locator) } catch (e: Exception) { Locator.current.onConfigurationError(e) } protected abstract fun make(): LocatorImpl protected abstract fun configure(locator: LocatorImpl, function: LocatorConfig.() -> Unit): LocatorConfig }
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/runner/LocatorBuilder.kt
737126602
package com.sksamuel.kotest.property.shrinking import io.kotest.assertions.throwables.shouldThrowAny import io.kotest.core.spec.style.FunSpec import io.kotest.extensions.system.captureStandardOut import io.kotest.inspectors.forAtLeastOne import io.kotest.matchers.collections.shouldHaveAtMostSize import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.kotest.property.Arb import io.kotest.property.PropTestConfig import io.kotest.property.PropertyTesting import io.kotest.property.ShrinkingMode import io.kotest.property.arbitrary.ListShrinker import io.kotest.property.arbitrary.constant import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.list import io.kotest.property.checkAll import io.kotest.property.internal.doShrinking import io.kotest.property.rtree class ListShrinkerTest : FunSpec() { init { val state = PropertyTesting.shouldPrintShrinkSteps beforeSpec { PropertyTesting.shouldPrintShrinkSteps = false } afterSpec { PropertyTesting.shouldPrintShrinkSteps = state } test("ListShrinker should include bisected input") { checkAll(Arb.list(Arb.int(0..1000))) { list -> if (list.size > 1) { val candidates = ListShrinker<Int>(0..100).shrink(list) candidates.forAtLeastOne { list.take(list.size / 2) shouldBe it } } } } test("ListShrinker should include input minus head") { checkAll(Arb.list(Arb.int(0..1000))) { list -> if (list.size > 1) { val candidates = ListShrinker<Int>(0..100).shrink(list) candidates.forAtLeastOne { list.drop(1) shouldBe it } } } } test("ListShrinker should include input minus tail") { checkAll(Arb.list(Arb.int(0..1000))) { list -> if (list.size > 1) { val candidates = ListShrinker<Int>(0..100).shrink(list) candidates.forAtLeastOne { list.dropLast(1) shouldBe it } } } } test("ListShrinker should shrink to expected value") { checkAll(Arb.list(Arb.int(0..1000))) { list -> if (list.isNotEmpty()) { val shrinks = ListShrinker<Int>(0..100).rtree(list) val shrunk = doShrinking(shrinks, ShrinkingMode.Unbounded) { it shouldHaveSize 0 } shrunk.shrink shouldHaveSize 1 } } val input = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val shrinks = ListShrinker<Int>(0..100).rtree(input) val shrunk = doShrinking(shrinks, ShrinkingMode.Unbounded) { it shouldHaveAtMostSize 2 } shrunk.shrink shouldHaveSize 3 } test("ListShrinker should observe range") { checkAll(Arb.list(Arb.constant(0), range = 4..100)) { list -> if (list.isNotEmpty()) { val shrinks = ListShrinker<Int>(4..100).rtree(list) val shrunk = doShrinking(shrinks, ShrinkingMode.Unbounded) { it shouldHaveSize 0 } shrunk.shrink shouldHaveSize 4 } } } test("ListShrinker in action") { val stdout = captureStandardOut { PropertyTesting.shouldPrintShrinkSteps = true shouldThrowAny { checkAll(PropTestConfig(seed = 123132), Arb.list(Arb.int(0..100))) { list -> list.shouldHaveAtMostSize(3) } } } println(stdout) stdout.shouldContain("Shrink result (after 24 shrinks) => [1, 100, 96, 29") } } }
kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/shrinking/ListShrinkerTest.kt
2238109417
package com.dariopellegrini.spike.response import com.android.volley.VolleyError /** * Created by dariopellegrini on 25/07/17. */ open class SpikeErrorResponse<T>(statusCode: Int, headers: Map<String, String>?, results: String?, volleyError: VolleyError?): SpikeResponse(statusCode, headers, results) { val volleyError = volleyError var computedResult: T? = null val error: SpikeError get() { when(statusCode) { -1001 -> return SpikeError.noConnection 400 -> return SpikeError.badRequest 401 -> return SpikeError.unauthorized 402 -> return SpikeError.paymentRequired 403 -> return SpikeError.forbidden 404 -> return SpikeError.notFound 405 -> return SpikeError.methodNotAllowed 406 -> return SpikeError.notAcceptable 407 -> return SpikeError.proxyAuthenticationRequired 408 -> return SpikeError.requestTimeout 409 -> return SpikeError.conflict 410 -> return SpikeError.gone 411 -> return SpikeError.lengthRequired 412 -> return SpikeError.preconditionFailed 413 -> return SpikeError.requestEntityTooLarge 414 -> return SpikeError.requestURITooLong 415 -> return SpikeError.unsupportedMediaType 416 -> return SpikeError.requestedRangeNotSatisfiable 417 -> return SpikeError.requestedRangeNotSatisfiable 418 -> return SpikeError.enhanceYourCalm 421 -> return SpikeError.misdirectedRequest 422 -> return SpikeError.unprocessableEntity 423 -> return SpikeError.locked 424 -> return SpikeError.failedDependency 426 -> return SpikeError.upgradeRequired 428 -> return SpikeError.preconditionRequired 429 -> return SpikeError.tooManyRequests 431 -> return SpikeError.requestHeaderFieldsTooLarge 451 -> return SpikeError.unavailableForLegalReasons 500 -> return SpikeError.internalServerError 501 -> return SpikeError.notImplemented 502 -> return SpikeError.badGateway 503 -> return SpikeError.serviceUnavailable 504 -> return SpikeError.gatewayTimeout 505 -> return SpikeError.HTTPVersionNotSupported 506 -> return SpikeError.bandwidthLimitExceeded else -> return SpikeError.unknownError } } }
spike/src/main/java/com/dariopellegrini/spike/response/SpikeErrorResponse.kt
827432605
package io.kotest.core.test /** * Test naming strategies to adjust test name case. * * @property AsIs For: should("Happen SOMETHING") yields: should Happen SOMETHING * @property Sentence For: should("Happen SOMETHING") yields: Should happen SOMETHING * @property InitialLowercase For: should("Happen SOMETHING") yields: should happen SOMETHING * @property Lowercase For: should("Happen SOMETHING") yields: should happen something */ enum class TestNameCase { AsIs, Sentence, InitialLowercase, Lowercase }
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/test/TestNameCase.kt
1541881441
package de.treichels.hott.voice import de.treichels.hott.util.get import java.util.* enum class CountryCode(val code: Int) { GLOBAL(0), US(1), KR(2), CN(3), JP(4); override fun toString(): String = ResourceBundle.getBundle(javaClass.name)[name] companion object { @JvmStatic fun forCode(countryCode: Int): CountryCode = values().find { it.code == countryCode } ?: GLOBAL } }
HoTT-Voice/src/main/kotlin/de/treichels/hott/voice/CountryCode.kt
4095337083
/* Bogo Sort Bogo Sort is the most inefficient way of sorting an algorithm. The way Bogo Sort works is like throwing a deck of cards in the air and picking them back up and checking to see if it's organized. Array of ints [ 3, 1, 2 ] Step 1. Starts at the start of the array and will grab a random index from the array to switch with. randomIndex = RANDOM NUMBER Step 2. Once random index is obtained, it will then switch the current index value with the random index value Example: randomIndex = 2, currentIndex = 0 [ 3, 1, 2 ] ---> [ 2, 1, 3 ] Step 3. Check if array is sorted. [ 2, 1, 3 ] <---- Is not sorted so go onto the next index and repeat steps 1 & 2. Stop when sorted - You could be done in the next step or the next million steps :') */ package com.exam.kotlin.codingproject import kotlin.random.Random class BogoSort { companion object{ private val randomValues = List(10) { Random.nextInt(0, 100) } private fun isSorted(arr: IntArray): Boolean { for (i in 0 until arr.size - 1) { if (arr[i] > arr[i + 1]) { return false } } return true } fun bogoSort(numbersToSort: IntArray) : IntArray { while (!isSorted(numbersToSort)) { for (i in numbersToSort.indices) { val randomIndex = randomValues[numbersToSort.size] val holder = numbersToSort[i] numbersToSort[i] = numbersToSort[randomIndex] numbersToSort[randomIndex] = holder } } return numbersToSort } } }
sort/bogo_sort/kotlin/bogo_sort.kt
3681803537
/** * BreadWallet * * Created by Pablo Budelli <[email protected]> on 10/17/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.settings import android.net.Uri import com.breadwallet.R import com.breadwallet.tools.util.Link import com.breadwallet.ui.ViewEffect import com.breadwallet.ui.navigation.NavigationEffect import com.breadwallet.ui.navigation.NavigationTarget import com.breadwallet.util.CurrencyCode import dev.zacsweers.redacted.annotations.Redacted object SettingsScreen { const val CONFIRM_EXPORT_TRANSACTIONS_DIALOG = "confirm_export" data class M( val section: SettingsSection, @Redacted val items: List<SettingsItem> = listOf(), val isLoading: Boolean = false ) { companion object { fun createDefault(section: SettingsSection) = M(section) } } sealed class E { data class OnLinkScanned(val link: Link) : E() data class OnOptionClicked(val option: SettingsOption) : E() data class OnOptionsLoaded(@Redacted val options: List<SettingsItem>) : E() object OnBackClicked : E() object OnCloseClicked : E() object OnAuthenticated : E() data class ShowPhrase(@Redacted val phrase: List<String>) : E() data class SetApiServer(val host: String) : E() data class SetPlatformDebugUrl(val url: String) : E() data class SetPlatformBundle(val bundle: String) : E() data class SetTokenBundle(val bundle: String) : E() object OnWalletsUpdated : E() object ShowHiddenOptions : E() object OnCloseHiddenMenu : E() data class OnATMMapClicked(val url: String, val mapJson: String) : E() object OnExportTransactionsConfirmed : E() data class OnTransactionsExportFileGenerated(val uri: Uri) : E() } sealed class F { object SendAtmFinderRequest : F() object SendLogs : F() object ViewLogs : F(), NavigationEffect { override val navigationTarget = NavigationTarget.LogcatViewer } object ViewMetadata : F(), NavigationEffect { override val navigationTarget = NavigationTarget.MetadataViewer } object ShowApiServerDialog : F(), ViewEffect object ShowPlatformDebugUrlDialog : F(), ViewEffect object ShowPlatformBundleDialog : F(), ViewEffect object ShowTokenBundleDialog : F(), ViewEffect object ResetDefaultCurrencies : F() object WipeNoPrompt : F() object GetPaperKey : F() object EnableAllWallets : F() object ClearBlockchainData : F() object ToggleRateAppPrompt : F() object RefreshTokens : F() object DetailedLogging : F() object CopyPaperKey : F() object ToggleTezos : F() data class SetApiServer(val host: String) : F() data class SetPlatformDebugUrl(val url: String) : F() data class SetPlatformBundle(val bundle: String) : F() data class SetTokenBundle(val bundle: String) : F() data class LoadOptions(val section: SettingsSection) : F() data class GoToSection(val section: SettingsSection) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Menu(section) } object GoBack : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Back } object GoToSupport : F(), NavigationEffect { override val navigationTarget = NavigationTarget.SupportPage("") } object GoToQrScan : F(), NavigationEffect { override val navigationTarget = NavigationTarget.QRScanner } object GoToBrdRewards : F(), NavigationEffect { override val navigationTarget = NavigationTarget.BrdRewards } object GoToGooglePlay : F(), NavigationEffect { override val navigationTarget = NavigationTarget.ReviewBrd } object GoToAbout : F(), NavigationEffect { override val navigationTarget = NavigationTarget.About } object GoToDisplayCurrency : F(), NavigationEffect { override val navigationTarget = NavigationTarget.DisplayCurrency } object GoToNotificationsSettings : F(), NavigationEffect { override val navigationTarget = NavigationTarget.NotificationsSettings } object GoToShareData : F(), NavigationEffect { override val navigationTarget = NavigationTarget.ShareDataSettings } object GoToImportWallet : F(), NavigationEffect { override val navigationTarget = NavigationTarget.ImportWallet() } data class GoToSyncBlockchain( val currencyCode: CurrencyCode ) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.SyncBlockchain(currencyCode) } object GoToNodeSelector : F(), NavigationEffect { override val navigationTarget = NavigationTarget.BitcoinNodeSelector } object GoToEnableSegWit : F(), NavigationEffect { override val navigationTarget = NavigationTarget.EnableSegWit } object GoToLegacyAddress : F(), NavigationEffect { override val navigationTarget = NavigationTarget.LegacyAddress } object GoToFingerprintAuth : F(), NavigationEffect { override val navigationTarget = NavigationTarget.FingerprintSettings } object GoToUpdatePin : F(), NavigationEffect { override val navigationTarget = NavigationTarget.SetPin() } object GoToWipeWallet : F(), NavigationEffect { override val navigationTarget = NavigationTarget.WipeWallet } object GoToOnboarding : F(), NavigationEffect { override val navigationTarget = NavigationTarget.OnBoarding } object GoToNativeApiExplorer : F(), NavigationEffect { override val navigationTarget = NavigationTarget.NativeApiExplorer } object GoToHomeScreen : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Home } object GoToAuthentication : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Authentication() } data class GoToPaperKey( @Redacted val phrase: List<String> ) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.PaperKey(phrase, null) } data class GoToFastSync( val currencyCode: CurrencyCode ) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.FastSync(currencyCode) } data class GoToLink(val link: Link) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.DeepLink( link = link, authenticated = true ) } data class GoToATMMap(val url: String, val mapJson: String) : F(), NavigationEffect { override val navigationTarget = NavigationTarget.ATMMap(url, mapJson) } object RelaunchHomeScreen : F(), NavigationEffect { override val navigationTarget = NavigationTarget.Home } object ShowConfirmExportTransactions : F(), NavigationEffect { override val navigationTarget = NavigationTarget.AlertDialog( titleResId = R.string.ExportConfirmation_title, messageResId = R.string.ExportConfirmation_message, positiveButtonResId = R.string.ExportConfirmation_continue, negativeButtonResId = R.string.ExportConfirmation_cancel, dialogId = CONFIRM_EXPORT_TRANSACTIONS_DIALOG ) } object GenerateTransactionsExportFile: F() data class ExportTransactions(val uri: Uri) : F(), ViewEffect } }
app/src/main/java/com/breadwallet/ui/settings/SettingsScreen.kt
3895429001
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game import com.charlatano.settings.MAX_ENTITIES import com.charlatano.game.entity.Entity import com.charlatano.game.entity.EntityType import com.charlatano.game.entity.Player import com.charlatano.game.entity.bone import com.charlatano.utils.Angle import com.charlatano.utils.collections.CacheableList import com.charlatano.utils.collections.ListContainer import com.charlatano.utils.readCached import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap import it.unimi.dsi.fastutil.longs.Long2ObjectMap import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap import it.unimi.dsi.fastutil.objects.Object2ObjectMap import java.util.* var me: Player = 0 var clientState: ClientState = 0 typealias EntityContainer = ListContainer<EntityContext> typealias EntityList = Object2ObjectArrayMap<EntityType, CacheableList<EntityContext>> private val cachedResults = Int2ObjectArrayMap<EntityContainer>(EntityType.size) val entitiesValues = arrayOfNulls<CacheableList<EntityContext>>(MAX_ENTITIES) var entitiesValuesCounter = 0 val entities: Object2ObjectMap<EntityType, CacheableList<EntityContext>> = EntityList(EntityType.size).apply { for (type in EntityType.cachedValues) { val cacheableList = CacheableList<EntityContext>(MAX_ENTITIES) put(type, cacheableList) entitiesValues[entitiesValuesCounter++] = cacheableList } } fun entityByType(type: EntityType): EntityContext? = entities[type]?.firstOrNull() internal inline fun forEntities(types: Array<EntityType> = EntityType.cachedValues, crossinline body: (EntityContext) -> Unit) { val hash = Arrays.hashCode(types) val container = cachedResults.get(hash) ?: EntityContainer(EntityType.size) if (container.empty()) { for (type in types) if (type != EntityType.NULL) { val cacheableList = entities[type]!! container.addList(cacheableList) cachedResults.put(hash, container) } } container.forEach(body) } val entityToBones: Long2ObjectMap<Angle> = Long2ObjectOpenHashMap() fun Entity.bones(boneID: Int) = readCached(entityToBones) { x = bone(0xC, boneID) y = bone(0x1C, boneID) z = bone(0x2C, boneID) }
src/main/kotlin/com/charlatano/game/Entities.kt
4267106397
package com.jakewharton.diffuse import com.jakewharton.diffuse.io.Input class ApiMapping private constructor(private val typeMappings: Map<TypeDescriptor, TypeMapping>) { override fun equals(other: Any?) = other is ApiMapping && typeMappings == other.typeMappings override fun hashCode() = typeMappings.hashCode() override fun toString() = typeMappings.toString() fun isEmpty() = typeMappings.isEmpty() val types get() = typeMappings.size val methods get() = typeMappings.values.sumBy { it.methods.size } val fields get() = typeMappings.values.sumBy { it.fields.size } /** * Given a [TypeDescriptor] which is typically obfuscated, return a new [TypeDescriptor] for the * original name or return [type] if not included in the mapping. */ operator fun get(type: TypeDescriptor): TypeDescriptor { return typeMappings[type.componentDescriptor] ?.typeDescriptor ?.asArray(type.arrayArity) ?: type } /** * Given a [Member] which is typically obfuscated, return a new [Member] with the types and * name mapped back to their original values or return [member] if the declaring type is not * included in the mapping. */ operator fun get(member: Member) = when (member) { is Field -> this[member] is Method -> this[member] } /** * Given a [Field] which is typically obfuscated, return a new [Field] with the types and * name mapped back to their original values or return [field] if the declaring type is not * included in the mapping. */ operator fun get(field: Field): Field { val declaringType = field.declaringType.componentDescriptor val declaringTypeMapping = typeMappings[declaringType] ?: return field val newDeclaringType = declaringTypeMapping.typeDescriptor .asArray(field.declaringType.arrayArity) val newType = this[field.type] val newName = declaringTypeMapping[field.name] ?: field.name return Field(newDeclaringType, newName, newType) } /** * Given a [Method] which is typically obfuscated, return a new [Method] with the types and * name mapped back to their original values or return [method] if the declaring type is not * included in the mapping. */ operator fun get(method: Method): Method { val declaringType = method.declaringType.componentDescriptor val declaringTypeMapping = typeMappings[declaringType] ?: return method val newDeclaringType = declaringTypeMapping.typeDescriptor .asArray(method.declaringType.arrayArity) val newReturnType = this[method.returnType] val newParameters = method.parameterTypes.map(::get) val signature = MethodSignature(newReturnType, method.name, newParameters) val newName = declaringTypeMapping[signature] ?: method.name return Method(newDeclaringType, newName, newParameters, newReturnType) } companion object { @JvmField val EMPTY = ApiMapping(emptyMap()) @JvmStatic @JvmName("parse") fun Input.toApiMapping(): ApiMapping { val typeMappings = mutableMapOf<TypeDescriptor, TypeMapping>() var fromDescriptor: TypeDescriptor? = null var toDescriptor: TypeDescriptor? = null var fields: MutableMap<String, String>? = null var methods: MutableMap<MethodSignature, String>? = null toUtf8().split('\n').forEachIndexed { index, line -> if (line.startsWith('#') || line.isBlank()) { return@forEachIndexed } if (line.startsWith(' ')) { val result = memberLine.matchEntire(line) ?: throw IllegalArgumentException( "Unable to parse line ${index + 1} as member mapping: $line") val (_, returnType, fromName, parameters, toName) = result.groupValues if (parameters != "") { val returnDescriptor = humanNameToDescriptor(returnType) val parameterDescriptors = parameters .substring(1, parameters.lastIndex) // Remove leading '(' and trailing ')'. .takeUnless(String::isEmpty) // Do not process parameter-less methods. ?.split(',') ?.map(::humanNameToDescriptor) ?: emptyList() val lookupSignature = MethodSignature(returnDescriptor, toName, parameterDescriptors) methods!![lookupSignature] = fromName } else { fields!![toName] = fromName } } else { if (fromDescriptor != null) { typeMappings[toDescriptor!!] = TypeMapping(fromDescriptor!!, fields!!, methods!!) } val result = typeLine.matchEntire(line) ?: throw IllegalArgumentException( "Unable to parse line ${index + 1} as type mapping: $line") val (_, fromType, toType) = result.groupValues fromDescriptor = humanNameToDescriptor(fromType) toDescriptor = humanNameToDescriptor(toType) fields = mutableMapOf() methods = mutableMapOf() } } if (fromDescriptor != null) { typeMappings[toDescriptor!!] = TypeMapping(fromDescriptor!!, fields!!, methods!!) } return ApiMapping(typeMappings) } private val typeLine = Regex("(.+?) -> (.+?):") private val memberLine = Regex("\\s+(?:\\d+:\\d+:)?(.+?) (.+?)(\\(.*?\\))?(?::\\d+:\\d+)? -> (.+)") private fun humanNameToDescriptor(name: String): TypeDescriptor { val type = name.trimEnd('[', ']') val descriptor = when (type) { "void" -> "V" "boolean" -> "Z" "byte" -> "B" "char" -> "C" "double" -> "D" "float" -> "F" "int" -> "I" "long" -> "J" "short" -> "S" else -> "L${type.replace('.', '/')};" } val arrayArity = (name.length - type.length) / 2 return TypeDescriptor(descriptor).asArray(arrayArity) } } } private data class MethodSignature( val returnType: TypeDescriptor, val name: String, val parameterTypes: List<TypeDescriptor> ) private data class TypeMapping( val typeDescriptor: TypeDescriptor, val fields: Map<String, String>, val methods: Map<MethodSignature, String> ) { operator fun get(field: String) = fields[field] operator fun get(method: MethodSignature) = methods[method] }
diffuse/src/main/kotlin/com/jakewharton/diffuse/ApiMapping.kt
2101897859
package com.squareup.sqldelight.integration import co.touchlab.sqliter.DatabaseFileContext.deleteDatabase import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.drivers.native.NativeSqliteDriver import kotlin.native.concurrent.Future import kotlin.native.concurrent.TransferMode import kotlin.native.concurrent.Worker import kotlin.native.concurrent.freeze actual fun createSqlDatabase(): SqlDriver { val name = "testdb" deleteDatabase(name) return NativeSqliteDriver(QueryWrapper.Schema, name) } actual class MPWorker actual constructor() { val worker = Worker.start() actual fun <T> runBackground(backJob: () -> T): MPFuture<T> { return MPFuture( worker.execute(TransferMode.SAFE, { backJob.freeze() }) { it() } ) } actual fun requestTermination() { worker.requestTermination().result } } actual class MPFuture<T>(private val future: Future<T>) { actual fun consume(): T = future.result }
sqldelight-gradle-plugin/src/test/integration-multiplatform/src/iosMain/kotlin/com/squareup/sqldelight/integration/ios.kt
2192050179
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.marsphotos.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
app/src/main/java/com/example/marsphotos/ui/theme/Shape.kt
139173193
package com.leaguechampions.features.champions.presentation.champions import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import com.leaguechampions.features.champions.R import com.leaguechampions.features.champions.databinding.ActivityChampionsBinding import dagger.android.support.DaggerAppCompatActivity class ChampionsActivity : DaggerAppCompatActivity() { private lateinit var navController: NavController private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityChampionsBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) // supportActionBar?.setTitle(R.string.app_name) navController = findNavController(R.id.activity_champions_navHostFragment) appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
features/champions/src/main/java/com/leaguechampions/features/champions/presentation/champions/ChampionsActivity.kt
3451939058
package chat.rocket.android.chatroom.ui import android.content.Context import android.view.Menu import android.view.MenuItem import android.widget.EditText import androidx.appcompat.widget.SearchView import androidx.core.content.res.ResourcesCompat import chat.rocket.android.R import chat.rocket.android.util.extension.onQueryTextListener internal fun ChatRoomFragment.setupMenu(menu: Menu) { setupSearchMessageMenuItem(menu, requireContext()) } private fun ChatRoomFragment.setupSearchMessageMenuItem(menu: Menu, context: Context) { val searchItem = menu.add( Menu.NONE, Menu.NONE, Menu.NONE, R.string.title_search_message ).setActionView(SearchView(context)) .setIcon(R.drawable.ic_chatroom_toolbar_magnifier_20dp) .setShowAsActionFlags( MenuItem.SHOW_AS_ACTION_IF_ROOM or MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW ) .setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?): Boolean { dismissEmojiKeyboard() return true } override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { dismissEmojiKeyboard() return true } }) (searchItem.actionView as? SearchView)?.let { // TODO: Check why we need to stylize the search text programmatically instead of by defining it in the styles.xml (ChatRoom.SearchView) it.maxWidth = Integer.MAX_VALUE stylizeSearchView(it, context) setupSearchViewTextListener(it) if (it.isIconified) { isSearchTermQueried = false } } } private fun stylizeSearchView(searchView: SearchView, context: Context) { val searchText = searchView.findViewById<EditText>(androidx.appcompat.R.id.search_src_text) searchText.setTextColor(ResourcesCompat.getColor(context.resources, R.color.color_white, null)) searchText.setHintTextColor( ResourcesCompat.getColor(context.resources, R.color.color_white, null) ) } private fun ChatRoomFragment.setupSearchViewTextListener(searchView: SearchView) { searchView.onQueryTextListener { // TODO: We use isSearchTermQueried to avoid querying when the search view is expanded but the user doesn't start typing. Check for a native solution. if (it.isEmpty() && isSearchTermQueried) { presenter.loadMessages(chatRoomId, chatRoomType, clearDataSet = true) } else if (it.isNotEmpty()) { presenter.searchMessages(chatRoomId, it) isSearchTermQueried = true } } }
app/src/main/java/chat/rocket/android/chatroom/ui/Menu.kt
1153045917
package org.gradle.kotlin.dsl.accessors import org.gradle.internal.classpath.ClassPath import org.gradle.internal.classpath.DefaultClassPath import org.gradle.kotlin.dsl.fixtures.TestWithTempFiles import org.gradle.kotlin.dsl.fixtures.classEntriesFor import org.gradle.kotlin.dsl.support.bytecode.InternalName import org.gradle.kotlin.dsl.support.bytecode.beginClass import org.gradle.kotlin.dsl.support.bytecode.endClass import org.gradle.kotlin.dsl.support.bytecode.publicDefaultConstructor import org.gradle.kotlin.dsl.support.zipTo import org.objectweb.asm.Opcodes.ACC_ABSTRACT import org.objectweb.asm.Opcodes.ACC_INTERFACE import org.objectweb.asm.Opcodes.ACC_PRIVATE import org.objectweb.asm.Opcodes.ACC_PUBLIC import java.io.File import kotlin.reflect.KClass open class TestWithClassPath : TestWithTempFiles() { protected fun jarClassPathWith(vararg classes: KClass<*>): ClassPath = jarClassPathWith("cp.jar", *classes) protected fun jarClassPathWith(path: String, vararg classes: KClass<*>): ClassPath = classPathOf( file(path).also { jar -> zipTo(jar, classEntriesFor(classes)) } ) protected fun classPathWith(vararg classes: KClass<*>): ClassPath = classPathOf( newFolder().also { rootDir -> for ((path, bytes) in classEntriesFor(classes)) { File(rootDir, path).apply { parentFile.mkdirs() writeBytes(bytes) } } } ) } internal fun TestWithTempFiles.classPathWithPublicType(name: String) = classPathWithType(name, ACC_PUBLIC) internal fun TestWithTempFiles.classPathWithPrivateType(name: String) = classPathWithType(name, ACC_PRIVATE) internal fun TestWithTempFiles.classPathWithType(name: String, vararg modifiers: Int): ClassPath = classPathOf( newFolder().also { rootDir -> writeClassFileTo(rootDir, name, *modifiers) } ) internal fun TestWithTempFiles.classPathWith(builder: ClassPathBuilderScope.() -> Unit): ClassPath = classPathOf(newFolder().also { builder(ClassPathBuilderScope(it)) }) internal class ClassPathBuilderScope(val outputDir: File) internal fun ClassPathBuilderScope.publicClass(name: String) { writeClassFileTo(outputDir, name, ACC_PUBLIC) } internal fun ClassPathBuilderScope.publicInterface(name: String, vararg interfaces: String) { val internalName = InternalName.from(name) writeClassFileTo( outputDir, internalName, beginClass( ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, internalName, interfaces = interfaces.takeIf { it.isNotEmpty() }?.map(InternalName.Companion::from) ).endClass() ) } internal fun classPathOf(vararg files: File) = DefaultClassPath.of(files.asList()) private fun writeClassFileTo(rootDir: File, name: String, vararg modifiers: Int) { val internalName = InternalName.from(name) val classBytes = classBytesOf(modifiers.fold(0, Int::plus), internalName) writeClassFileTo(rootDir, internalName, classBytes) } private fun writeClassFileTo(rootDir: File, className: InternalName, classBytes: ByteArray) { File(rootDir, "$className.class").apply { parentFile.mkdirs() writeBytes(classBytes) } } internal fun classBytesOf(modifiers: Int, internalName: InternalName): ByteArray = beginClass(modifiers, internalName).run { publicDefaultConstructor() endClass() }
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/accessors/TestWithClassPath.kt
4191143445
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.resolver import org.gradle.api.artifacts.transform.InputArtifact import org.gradle.api.artifacts.transform.TransformAction import org.gradle.api.artifacts.transform.TransformOutputs import org.gradle.api.artifacts.transform.TransformParameters import org.gradle.api.file.FileSystemLocation import org.gradle.api.provider.Provider import org.gradle.api.tasks.IgnoreEmptyDirectories import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.kotlin.dsl.support.unzipTo import org.gradle.work.DisableCachingByDefault import java.io.File /** * This dependency transform is responsible for extracting the sources from * a downloaded ZIP of the Gradle sources, and will return the list of main sources * subdirectories for all subprojects. */ @DisableCachingByDefault(because = "Only filters the input artifact") abstract class FindGradleSources : TransformAction<TransformParameters.None> { @get:IgnoreEmptyDirectories @get:PathSensitive(PathSensitivity.RELATIVE) @get:InputArtifact abstract val input: Provider<FileSystemLocation> override fun transform(outputs: TransformOutputs) { registerSourceDirectories(outputs) } private fun registerSourceDirectories(outputs: TransformOutputs) { unzippedSubProjectsDir()?.let { subDirsOf(it).flatMap { subProject -> subDirsOf(File(subProject, "src/main")) }.forEach { outputs.dir(it) } } } private fun unzippedSubProjectsDir(): File? = unzippedDistroDir()?.let { File(it, "subprojects") } private fun unzippedDistroDir(): File? = input.get().asFile.listFiles().singleOrNull() } @DisableCachingByDefault(because = "Not worth caching") abstract class UnzipDistribution : TransformAction<TransformParameters.None> { @get:PathSensitive(PathSensitivity.NONE) @get:InputArtifact abstract val input: Provider<FileSystemLocation> override fun transform(outputs: TransformOutputs) { unzipTo(outputs.dir("unzipped-distribution"), input.get().asFile) } }
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/resolver/FindGradleSources.kt
810708395
/* * 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.common.truth.StringSubject import com.google.common.truth.Truth.assertThat import com.squareup.javapoet.JavaFile import com.squareup.javapoet.TypeSpec import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class DataTypeDescriptorDaggerProviderTest { @Test fun provideContentsInto_defaultDtdContainingClassName() { val provider = DataTypeDescriptorDaggerProvider("MyDataClass") assertThat(provider) .generatesMethod( """ | @Provides | @Singleton | @IntoSet | public static DataTypeDescriptor provideMyDataClassDataTypeDescriptor() { | return MyDataClass_GeneratedKt.MY_DATA_CLASS_GENERATED_DTD; | } """.trimMargin() ) } @Test fun provideContentsInto_customDtdContainingClassName() { val provider = DataTypeDescriptorDaggerProvider( elementName = "MyDataClass", dtdContainingClassName = "MyDtds" ) assertThat(provider) .generatesMethod( """ | @Provides | @Singleton | @IntoSet | public static DataTypeDescriptor provideMyDataClassDataTypeDescriptor() { | return MyDtds.MY_DATA_CLASS_GENERATED_DTD; | } """.trimMargin() ) } private fun assertThat(provider: DataTypeDescriptorDaggerProvider): StringSubject { val typeSpec = TypeSpec.classBuilder("MyClass").apply { provider.provideContentsInto(this) }.build() val contents = JavaFile.builder("com.google", typeSpec).build().toString().trim() return assertThat(contents) } private fun StringSubject.generatesMethod(method: String) { isEqualTo( """ |package com.google; | |import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor; |import dagger.Provides; |import dagger.multibindings.IntoSet; |import javax.inject.Singleton; | |class MyClass { |$method |} """.trimMargin() ) } }
javatests/com/google/android/libraries/pcc/chronicle/codegen/backend/DataTypeDescriptorDaggerProviderTest.kt
2529914272
package yt.javi.nftweets.infrastructure.repositories.inmemory import yt.javi.nfltweets.domain.model.team.Team import yt.javi.nftweets.domain.model.Conference import yt.javi.nftweets.domain.model.Division import yt.javi.nftweets.domain.model.team.TeamRepository class TeamInMemoryRepository(private val teams: List<Team>): TeamRepository { override fun findTeams(conference: Conference?, division: Division?): List<Team> = teams.filter { conference == null || it.conference == conference } .filter { division == null || it.division == division } override fun findTeam(name: String): Team = teams.first { it.name == name } }
app/src/main/java/yt/javi/nftweets/infrastructure/repositories/inmemory/TeamInMemoryRepository.kt
2153861801
package com.tlz.fragmentbuilder /** * * Created by Tomlezen. * Date: 2017/7/25. * Time: 17:13. */ object FbConst { const val KEY_FRAGMENT_MANAGER_TAG = "key_fb_fragment_manager_tag" const val KEY_FB_REQUEST_CODE = "key_fb_request_code" }
lib/src/main/java/com/tlz/fragmentbuilder/FbConst.kt
2329451588
package com.github.ajalt.clikt.parameters.types import com.github.ajalt.clikt.core.Context import com.github.ajalt.clikt.parameters.arguments.ProcessedArgument import com.github.ajalt.clikt.parameters.options.OptionWithValues private inline fun <T : Comparable<T>> checkRange( it: T, min: T?, max: T?, clamp: Boolean, context: Context, fail: (String) -> Unit, ): T { require(min == null || max == null || min < max) { "min must be less than max" } if (clamp) { if (min != null && it < min) return min if (max != null && it > max) return max } else if (min != null && it < min || max != null && it > max) { fail(when { min == null -> context.localization.rangeExceededMax(it.toString(), max.toString()) max == null -> context.localization.rangeExceededMin(it.toString(), min.toString()) else -> context.localization.rangeExceededBoth(it.toString(), min.toString(), max.toString()) }) } return it } // Arguments /** * Restrict the argument values to fit into a range. * * By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be * silently clamped to fit in the range. * * This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each * individual value. * * ### Example: * * ``` * argument().int().restrictTo(max=10, clamp=true).default(10) * ``` */ fun <T : Comparable<T>> ProcessedArgument<T, T>.restrictTo(min: T? = null, max: T? = null, clamp: Boolean = false) : ProcessedArgument<T, T> { return copy( { checkRange(transformValue(it), min, max, clamp, context) { m -> fail(m) } }, transformAll, transformValidator ) } /** * Restrict the argument values to fit into a range. * * By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be * silently clamped to fit in the range. * * This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each * individual value. * * ### Example: * * ``` * argument().int().restrictTo(1..10, clamp=true).default(10) * ``` */ fun <T : Comparable<T>> ProcessedArgument<T, T>.restrictTo( range: ClosedRange<T>, clamp: Boolean = false, ): ProcessedArgument<T, T> { return restrictTo(range.start, range.endInclusive, clamp) } // Options /** * Restrict the option values to fit into a range. * * By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be * silently clamped to fit in the range. * * This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each * individual value. * * ### Example: * * ``` * option().int().restrictTo(max=10, clamp=true).default(10) * ``` */ fun <T : Comparable<T>> OptionWithValues<T?, T, T>.restrictTo( min: T? = null, max: T? = null, clamp: Boolean = false, ): OptionWithValues<T?, T, T> { return copy( { checkRange(transformValue(it), min, max, clamp, context) { m -> fail(m) } }, transformEach, transformAll, transformValidator ) } /** * Restrict the option values to fit into a range. * * By default, conversion fails if the value is outside the range, but if [clamp] is true, the value will be * silently clamped to fit in the range. * * This must be called before transforms like `pair`, `default`, or `multiple`, since it checks each * individual value. * * ### Example: * * ``` * option().int().restrictTo(1..10, clamp=true).default(10) * ``` */ fun <T : Comparable<T>> OptionWithValues<T?, T, T>.restrictTo( range: ClosedRange<T>, clamp: Boolean = false, ): OptionWithValues<T?, T, T> { return restrictTo(range.start, range.endInclusive, clamp) }
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/parameters/types/range.kt
3731409055
package io.ldavin.beltbraces.internal.transformation import com.googlecode.catchexception.CatchException.catchException import com.nhaarman.mockito_kotlin.given import io.ldavin.beltbraces.caughtException import io.ldavin.beltbraces.exception.NoAssertionFoundException import io.ldavin.beltbraces.internal.TestFixtures.analysis import io.ldavin.beltbraces.internal.TestFixtures.constructor import io.ldavin.beltbraces.internal.TestFixtures.emptyAnalysis import io.ldavin.beltbraces.internal.TestFixtures.property import io.ldavin.beltbraces.internal.transformation.ExceptionWriter.Companion.DOES_NOT_OVERRIDE_EQUALS import io.ldavin.beltbraces.internal.transformation.ExceptionWriter.Companion.LOOKS_LIKE_DATA_CLASS import io.ldavin.beltbraces.internal.transformation.ExceptionWriter.Companion.OBJECT_EQUALITY_ASSERTION import io.ldavin.beltbraces.internal.transformation.ExceptionWriter.Companion.PROPERTY_ASSERTIONS_FALLBACK import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner.StrictStubs::class) class ExceptionWriterTest { @Mock internal lateinit var propertyWriter: PropertyWriter @Mock internal lateinit var constructorWriter: ConstructorWriter @InjectMocks internal lateinit var writer: ExceptionWriter @Test fun `transformToMessage throws an exception if no properties are found`() { // GIVEN val analysis = emptyAnalysis() // WHEN catchException { writer.transformToMessage(analysis) } // THEN assertThat(caughtException()).isExactlyInstanceOf(NoAssertionFoundException::class.java) } @Test fun `transformToMessage a property-only analysis`() { // GIVEN val property1 = property(name = "1") val property2 = property(name = "2") val analysis = analysis(listOf(property1, property2), overrideEquals = false, isKotlinDataClass = false) given(propertyWriter.transform(property1)).willReturn("assertion1") given(propertyWriter.transform(property2)).willReturn("assertion2") // WHEN val result = writer.transformToMessage(analysis) // THEN val expectedMessage = """ $DOES_NOT_OVERRIDE_EQUALS assertion1 assertion2""".trimIndent() assertThat(result).isEqualTo(expectedMessage) } @Test fun `transformToMessage a kotlin data-class`() { // GIVEN val property1 = property(name = "1") val property2 = property(name = "2") val constructor = constructor() val analysis = analysis( listOf(property1, property2), preferredConstructor = constructor, overrideEquals = true, isKotlinDataClass = true ) given(propertyWriter.transform(property1)).willReturn("assertion1") given(propertyWriter.transform(property2)).willReturn("assertion2") given(constructorWriter.transform(constructor)).willReturn("object equality") // WHEN val result = writer.transformToMessage(analysis) // THEN val expectedMessage = """ $LOOKS_LIKE_DATA_CLASS $OBJECT_EQUALITY_ASSERTION object equality $PROPERTY_ASSERTIONS_FALLBACK assertion1 assertion2""".trimIndent() assertThat(result).isEqualTo(expectedMessage) } }
src/test/kotlin/io/ldavin/beltbraces/internal/transformation/ExceptionWriterTest.kt
3929937663
package com.zj.example.kotlin.shengshiyuan.helloworld /** * Created by zhengjiong * date: 2017/11/26 20:16 */ /** * companion object, ไผด็”Ÿๅฏน่ฑก(้š็€็ฑป็š„ๅญ˜ๅœจ่€Œๅญ˜ๅœจ),ไธ€ไธช็ฑปไธญๆœ€ๅคšๅช่ƒฝๅฎšไน‰ไธ€ไธชไผด็”Ÿๅฏน่ฑก * * javaไธญ็š„้™ๆ€ๆ–นๆณ•, ไป–ๅนถไธๅฑžไบŽไป–ๆ‰€ๅœจ็š„็ฑป, ่€Œๆ˜ฏๅฑžไบŽไป–ๆ‰€ๅœจ็š„็ฑป็š„classๅฏน่ฑก * ๅœจkotlinไธญ, ไธŽjavaไธๅŒ็š„ๆ˜ฏ, ็ฑปๆ˜ฏๆฒกๆœ‰staticๆ–นๆณ•็š„. * ๅœจๅคงๅคšๆ•ฐๆƒ…ๅ†ตไธ‹, kotlinๆŽจ่็š„ๅšๆณ•ๆ˜ฏไฝฟ็”จๅŒ…็บงๅˆซ็š„ๅ‡ฝๆ•ฐๆฅไฝœไธบ้™ๆ€ๆ–นๆณ•, * kotlinไผšๅฐ†ๅŒ…็บงๅˆซ็š„ๅ‡ฝๆ•ฐๅฝ“ๅš้™ๆ€ๆ–นๆณ•ๆฅ็œ‹ๅพ…. * * ๆณจๆ„:่™ฝ็„ถไผด็”Ÿๅฏน่ฑก็š„ๆˆๅ‘˜็œ‹่ตทๆฅๅƒๆ˜ฏjavaไธญ็š„้™ๆ€ๆˆๅ‘˜,ไฝ†ๆ˜ฏๅœจ่ฟ่กŒๆœŸ,ไป–ไปฌไพๆ—งๆ˜ฏ็œŸๅฎžๅฏน่ฑก็š„ๅฎžไพ‹ๆˆๅ‘˜. * ๅœจJVMไธŠ, ๅฏไปฅๅฐ†ไผด็”Ÿๅฏน่ฑก็š„ๆˆๅ‘˜็œŸๆญฃ็”Ÿๆˆไธบ็ฑป็š„้™ๆ€ๆ–นๆณ•ไธŽๅฑžๆ€ง, ่ฟ™ๆ˜ฏ้€š่ฟ‡@JvmStaticๆณจ่งฃๆฅๅฎž็Žฐ็š„. * ไผด็”Ÿๅฏน่ฑกๅœจ็ผ–่ฏ‘ๅŽไผš็”Ÿๆˆไธ€ไธช้™ๆ€ๅ†…้ƒจ็ฑป */ fun main(args: Array<String>) { var a1 = HelloKotlin15.MyTest.MyObject.a HelloKotlin15.MyTest.MyObject.method()//ๅฏไปฅ็œ็•ฅMyObject,็›ดๆŽฅไธญ็ฑปๅ่ฐƒ็”จ, ็œ‹ไธ‹้ข //็œ็•ฅMyObject,็›ดๆŽฅ่ฐƒ็”จ var a2 = HelloKotlin15.MyTest.a//็ฑปไผผไบŽ้™ๆ€ๅฑžๆ€ง HelloKotlin15.MyTest.method()//็ฑปไผผไบŽ้™ๆ€ๆ–นๆณ•, kotlinไธญๆฒกๆœ‰้™ๆ€ๆ–นๆณ• //้ป˜่ฎคๅๅญ—:Companion var a4 = HelloKotlin16.MyTest.Companion.a HelloKotlin16.MyTest.Companion.method() //็œ็•ฅๅๅญ—,็›ดๆŽฅ่ฐƒ็”จ var a5 = HelloKotlin16.MyTest.a /** * ๆณจๆ„: * HelloKotlin16.MyTest.method(),่ฟ™ไธชไผš่ฐƒ็”จMyTestไธญCompanionๅฏน่ฑก็š„methodๆ–นๆณ•. * HelloKotlin17.MyTest.method(),่ฟ™ไธชไผš็›ดๆŽฅ่ฐƒ็”จMyTest็š„methodๆ–นๆณ•.ๅ› ไธบmethodๅŠ ไบ†@JvmStatic,ๅฐฑไผšๅœจ็ผ–่ฏ‘็š„ๆ—ถๅ€™็”Ÿๆˆไธบ้™ๆ€ๆ–นๆณ• * ไธค่€…ๅœจๅบ•ๅฑ‚่ฐƒ็”จๆ˜ฏๅญ˜ๅœจๆ˜Žๆ˜พ็š„ๅทฎๅˆซ็š„,ไฝ†ๆ˜ฏๅœจไฝฟ็”จ็š„ๆ—ถๅ€™ๆ˜ฏๅฏŸ่ง‰ไธๅˆฐ็š„! */ HelloKotlin16.MyTest.method() HelloKotlin17.MyTest.method() //่ฟ”ๅ›žHelloKotlin15.MyTest.MyObject่ฟ™ไธชๅฏน่ฑกๅœจ่ฟ่กŒๆœŸๅฏนๅบ”็š„java class //่พ“ๅ‡บ:class com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin15$MyTest$MyObject //ๆ˜ฏไธ€ไธชๅ†…้ƒจ็ฑป, ๆ‰€ไปฅๅœจๆœ€ๅŽ็ผ–่ฏ‘ๆˆๅญ—่Š‚็ ็š„ๆ—ถๅ€™, ่ฟ™ไธชไผด็”Ÿๅฏน่ฑกไผš็ผ–่ฏ‘ๆˆไธ€ไธชๅ†…้ƒจ็ฑป println(HelloKotlin15.MyTest.MyObject.javaClass) } class HelloKotlin15 { class MyTest { //่ฟ™ไธชMyObjectๅฏไปฅ็œ็•ฅๆމ //ๅฆ‚ๆžœไธๆไพ›ไผด็”Ÿๅฏน่ฑก็š„ๅๅญ—, ็ผ–่ฏ‘ๅ™จ่ฎฒไผšๆไพ›ไธ€ไธช้ป˜่ฎคๆ˜ฏ็š„ๅๅญ—:Companion companion object MyObject { var a: Int = 100 fun method() { println("method invoked!") } } } } /** * ๅ็ผ–่ฏ‘ๆญฅ้ชค: * ็งปๅŠจๅˆฐ็›ฎๅฝ•:ZJ_KotlinStudy\out\production\classes>ไธ‹, ็„ถๅŽjavap com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest * javapๅ็ผ–่ฏ‘ๅŽ: * public final class com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest { * public static final com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest$Companion Companion;//ๅ˜้‡ๅฃฐๆ˜Ž, ้™ๆ€ๆˆๅ‘˜ๅ˜้‡ * public com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest();//ๆž„้€ ๆ–นๆณ• * static {};//้™ๆ€ไปฃ็ ๅ— * public static final int access$getA$cp(); * public static final void access$setA$cp(int); * } * * ไธŠ้ข็ผ–่ฏ‘ๅŽๅนถๆฒกๆœ‰็œ‹ๅˆฐๆœ‰methodๆ–นๆณ•ๅ’Œaๅฑžๆ€ง! ๅฐ่ฏไบ†่ฟ™ๅฅ่ฏ: * ่™ฝ็„ถไผด็”Ÿๅฏน่ฑก็š„ๆˆๅ‘˜็œ‹่ตทๆฅๅƒๆ˜ฏjavaไธญ็š„้™ๆ€ๆˆๅ‘˜,ไฝ†ๆ˜ฏๅœจ่ฟ่กŒๆœŸ,ไป–ไปฌไพๆ—งๆ˜ฏ็œŸๅฎžๅฏน่ฑก็š„ๅฎžไพ‹ๆˆๅ‘˜. * aๅ’ŒmethodๅนถไธไผšๆˆไธบMyTest็š„้™ๆ€ๆˆๅ‘˜! */ class HelloKotlin16 { class MyTest { /** * ่ฟ™ไธชMyObjectๅฏไปฅ็œ็•ฅๆމ,ๅฐฑไผšไฝฟ็”จ้ป˜่ฎค็š„ๅๅญ—:Companion * ๅ็ผ–่ฏ‘ๅพ—็Ÿฅ่ฏฅๅฏน่ฑก็š„็ฑปๅž‹ๆ˜ฏ: * static final com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest$Companion,ๆ˜ฏไธ€ไธช้™ๆ€ๆˆๅ‘˜ๅ˜้‡ */ companion object { var a: Int = 100 fun method() { println("method invoked!") } } } } class HelloKotlin17 { /** * ๅ็ผ–่ฏ‘ๆญฅ้ชค: * ็งปๅŠจๅˆฐ็›ฎๅฝ•:ZJ_KotlinStudy\out\production\classes>ไธ‹, ็„ถๅŽjavap com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest * javapๅ็ผ–่ฏ‘ๅŽ: * * public final class com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin17$MyTest { * public static final com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin17$MyTest$Companion Companion; * public com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin17$MyTest(); * static {}; * public static int a; //ๅŠ ไบ†@JvmFieldๆณจ่งฃๅŽ, aๅฑžๆ€งๅ˜ไธบ้™ๆ€ๆˆๅ‘˜ๅ˜้‡ * public static final void method(); //ๅŠ ไบ†@JvmStaticๆณจ่งฃๅŽ, methodๆ–นๆณ•ๅ˜ไธบ็œŸๆญฃ็š„้™ๆ€ๆ–นๆณ• } */ class MyTest { /** * ่ฟ™ไธชMyObjectๅฏไปฅ็œ็•ฅๆމ,ๅฐฑไผšไฝฟ็”จ้ป˜่ฎค็š„ๅๅญ—:Companion * ๅ็ผ–่ฏ‘ๅพ—็Ÿฅ่ฏฅๅฏน่ฑก็š„็ฑปๅž‹ๆ˜ฏ: * static final com.zj.example.kotlin.shengshiyuan.helloworld.HelloKotlin16$MyTest$Companion,ๆ˜ฏไธ€ไธช้™ๆ€ๆˆๅ‘˜ๅ˜้‡ */ companion object { @JvmField var a: Int = 100 @JvmStatic fun method() { println("method invoked!") } } } }
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/15.HelloKotlin-companion_object(ไผด็”Ÿๅฏน่ฑก).kt
184446349
// // Calendar Notifications Plus // Copyright (C) 2017 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.calendarmonitor import android.content.Context import android.content.Intent import com.github.quarck.calnotify.calendar.EventAlertRecord import com.github.quarck.calnotify.calendar.MonitorEventAlertEntry import com.github.quarck.calnotify.monitorstorage.MonitorStorage interface CalendarMonitorInterface { fun onSystemTimeChange(context: Context) fun onAlarmBroadcast(context: Context, intent: Intent) fun onPeriodicRescanBroadcast(context: Context, intent: Intent) fun onAppResumed(context: Context, monitorSettingsChanged: Boolean) fun onProviderReminderBroadcast(context: Context, intent: Intent) fun onEventEditedByUs(context: Context, eventId: Long) fun onRescanFromService(context: Context) fun getAlertsAt(context: Context, time: Long): List<MonitorEventAlertEntry> fun getAlertsForAlertRange(context: Context, scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry> fun setAlertWasHandled(context: Context, ev: EventAlertRecord, createdByUs: Boolean) fun getAlertWasHandled(context: Context, ev: EventAlertRecord): Boolean fun getAlertWasHandled(db: MonitorStorage, ev: EventAlertRecord): Boolean fun launchRescanService( context: Context, delayed: Int = 0, reloadCalendar: Boolean = false, rescanMonitor: Boolean = true, userActionUntil: Long = 0 ) }
app/src/main/java/com/github/quarck/calnotify/calendarmonitor/CalendarMonitorInterface.kt
2156582830
package org.rust.cargo.runconfig import com.intellij.execution.filters.RegexpFilter import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile /** * Detects messages about panics and adds source code links to them. */ class RustPanicFilter( project: Project, cargoProjectDir: VirtualFile ) : RegexpFileLinkFilter( project, cargoProjectDir, "^\\s*thread '.+' panicked at '.+', ${RegexpFilter.FILE_PATH_MACROS}:${RegexpFilter.LINE_MACROS}$") { }
src/main/kotlin/org/rust/cargo/runconfig/RustPanicFilter.kt
111382221
package net.perfectdreams.loritta.cinnamon.discord.utils.config import kotlinx.serialization.Serializable @Serializable data class FalatronConfig( val url: String, val key: String )
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/config/FalatronConfig.kt
3648596796
/* * Copyright 2018 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.sample interface Planet { val name: String val sector: String }
samples/sample-kotlin/src/main/java/io/michaelrocks/lightsaber/sample/Planet.kt
337522897
interface OrientationHelper { enum class Orientation { LANDSCAPE, PORTRAIT } fun requestOrientation(orientation: Orientation?): Boolean var orientation: Orientation? }
core/src/ru/hyst329/openfool/OrientationHelper.kt
3254085942
package com.blankj.subutil.pkg import android.os.Environment import com.blankj.utilcode.util.Utils /** * ``` * author: Blankj * blog : http://blankj.com * time : 2017/05/10 * desc : config about constants * ``` */ object Config { val FILE_SEP = System.getProperty("file.separator") val LINE_SEP = System.getProperty("line.separator") const val TEST_PKG = "com.blankj.testinstall" private val CACHE_PATH: String val TEST_APK_PATH: String init { val cacheDir = Utils.getApp().externalCacheDir CACHE_PATH = if (cacheDir != null) { cacheDir.absolutePath } else { Environment.getExternalStorageDirectory().absolutePath } + FILE_SEP TEST_APK_PATH = CACHE_PATH + "test_install.apk" } }
feature/subutil/pkg/src/main/java/com/blankj/subutil/pkg/Config.kt
403489088
package io.kotest.core.extensions import io.kotest.core.test.TestCase import io.kotest.core.spec.Spec import kotlin.reflect.KClass /** * Reusable spec extension that allows intercepting specs before they are executed. * The callback is invoked for each [Spec] that has been * submitted for executed. */ interface SpecExtension : Extension { /** * Intercepts execution of a [Spec]. * * Implementations must invoke the process callback if they * wish this spec to be executed. If they want to skip * the tests in this spec they can elect not to invoke * the callback. * * Once the process function returns, the execution of this * [Spec] and all it's nested [TestCase]s are guaranteed * to have been completed. * * @param process callback function required to continue spec processing */ suspend fun intercept(spec: KClass<out Spec>, process: suspend () -> Unit) }
kotest-core/src/commonMain/kotlin/io/kotest/core/extensions/SpecExtension.kt
4003020378
/* * Copyright (C) 2016 skydoves * * 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.skydoves.waterdays.persistence.sqlite import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import com.skydoves.waterdays.models.Capacity import timber.log.Timber import java.util.ArrayList /** * Created by skydoves on 2016-10-15. * Updated by skydoves on 2017-08-17. * Copyright (c) 2017 skydoves rights reserved. */ class SqliteManager(context: Context, name: String, factory: SQLiteDatabase.CursorFactory?, version: Int) : SQLiteOpenHelper(context, name, factory, version) { override fun onCreate(db: SQLiteDatabase) { val CREATE_TABLE_RECORD = "CREATE TABLE " + TABLE_RECORD + "(pk_recordid integer primary key autoincrement, recorddate " + "DATETIME DEFAULT (datetime('now','localtime')), amount varchar(4));" db.execSQL(CREATE_TABLE_RECORD) val CREATE_TABLE_ALARM = "CREATE TABLE " + TABLE_ALARM + "(requestcode integer primary key, daylist varchar(20), " + "starttime varchar(20), endtime varchar(20), interval integer);" db.execSQL(CREATE_TABLE_ALARM) val CREATE_TABLE_CAPACITY = "CREATE TABLE $TABLE_CAPACITY(capacity integer primary key)" db.execSQL(CREATE_TABLE_CAPACITY) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS $TABLE_RECORD") db.execSQL("DROP TABLE IF EXISTS $TABLE_ALARM") db.execSQL("DROP TABLE IF EXISTS $TABLE_CAPACITY") onCreate(db) } fun addCapacity(capacity: Capacity) { val query_addCapacity = "Insert Into " + TABLE_CAPACITY + " (capacity) Values(" + capacity.amount + ");" writableDatabase.execSQL(query_addCapacity) Timber.d("SUCCESS Capacity Inserted : %s", capacity.amount) } fun deleteCapacity(capacity: Capacity) { val query_deleteCapacity = "Delete from " + TABLE_CAPACITY + " Where capacity = " + capacity.amount + "" writableDatabase.execSQL(query_deleteCapacity) Timber.d("SUCCESS Capacity Deleted : %s", capacity.amount) } val capacityList: List<Capacity> get() { val capacities = ArrayList<Capacity>() val cursor = readableDatabase.rawQuery("select *from $TABLE_CAPACITY order by capacity asc", null) if (cursor != null && cursor.count > 0 && cursor.moveToFirst()) { do { val capacity = Capacity(cursor.getInt(0)) capacities.add(capacity) } while (cursor.moveToNext()) } return capacities } fun addRecord(amount: String) { val query_addRecord = "Insert Into $TABLE_RECORD (amount) Values('$amount');" writableDatabase.execSQL(query_addRecord) Timber.d("SUCCESS Record Inserted : %s", amount) } fun deleteRecord(index: Int) { val query_addRecord = "Delete from $TABLE_RECORD Where pk_recordid = '$index'" writableDatabase.execSQL(query_addRecord) Timber.d("SUCCESS Record Deleted : %s", index) } fun updateRecordAmount(index: Int, amount: Int) { val query_updateAmount = "Update $TABLE_RECORD set amount = '$amount' Where pk_recordid = '$index'" writableDatabase.execSQL(query_updateAmount) Timber.d("SUCCESS Record Updated : %s", amount) } fun getDayDrinkAmount(datetime: String): Int { var TotalAmount = 0 val cursor = readableDatabase.rawQuery("select * from " + TABLE_RECORD + " where recorddate >= datetime(date('" + datetime + "','localtime')) " + "and recorddate < datetime(date('" + datetime + "', 'localtime', '+1 day'))", null) if (cursor != null && cursor.count > 0 && cursor.moveToFirst()) { do { TotalAmount += cursor.getInt(2) } while (cursor.moveToNext()) } return TotalAmount } fun addAlarm(requestcode: Int, daylist: String, starttime: String, endtime: String, interval: Int) { val query_addRecord = "Insert Into $TABLE_ALARM Values($requestcode,'$daylist','$starttime','$endtime', $interval);" writableDatabase.execSQL(query_addRecord) Timber.d("SUCCESS Alarm Inserted : %s", requestcode) } fun deleteAlarm(requestcode: Int) { val query_addRecord = "Delete from $TABLE_ALARM Where requestcode = '$requestcode'" writableDatabase.execSQL(query_addRecord) Timber.d("SUCCESS Alarm Deleted : %s", requestcode) } @Synchronized override fun close() { super.close() } companion object { const val DATABASE_VERSION = 1 const val DATABASE_NAME = "waterdays.db" private const val TABLE_RECORD = "RecordList" private const val TABLE_ALARM = "AlarmList" private const val TABLE_CAPACITY = "capacityList" } }
app/src/main/java/com/skydoves/waterdays/persistence/sqlite/SqliteManager.kt
437677725
package de.maxvogler.learningspaces.services import com.google.android.gms.maps.model.LatLng import com.squareup.okhttp.OkHttpClient import com.squareup.okhttp.Request import com.squareup.otto.Produce import com.squareup.otto.Subscribe import de.maxvogler.learningspaces.events.RequestLocationsEvent import de.maxvogler.learningspaces.events.UpdateLocationsEvent import de.maxvogler.learningspaces.exceptions.NetworkException import de.maxvogler.learningspaces.helpers.* import de.maxvogler.learningspaces.models.FreeSeatMeasurement import de.maxvogler.learningspaces.models.Location import de.maxvogler.learningspaces.models.OpeningHourPair import de.maxvogler.learningspaces.services.filters.GroupKitBibSuedFilter import org.jetbrains.anko.async import org.jetbrains.anko.uiThread import org.joda.time.LocalTime import org.joda.time.format.DateTimeFormat import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.parser.JSONParser import org.json.simple.parser.ParseException import java.io.IOException import java.util.* /** * A network service, querying the KIT library location data. */ public open class LocationService : BusBasedService() { private val http = OkHttpClient() private val filters = listOf(GroupKitBibSuedFilter()) // TODO: Initialize mLastResults with static data to show something while live data is loaded protected var lastResults: Map<String, Location> = emptyMap() private val URL = "http://services.bibliothek.kit.edu/leitsystem/getdata.php?callback=jQuery1102036302255163900554_1417122682722&location%5B0%5D=LSG%2CLST%2CLSW%2CLSN%2CLBS%2CFBC%2CLAF%2CFBW%2CFBP%2CFBI%2CFBM%2CFBA%2CBIB-N%2CFBH%2CFBD%2CTheaBib&values%5B0%5D=seatestimate%2Cmanualcount&after%5B0%5D=-10800seconds&before%5B0%5D=now&limit%5B0%5D=-17&location%5B1%5D=LSG%2CLST%2CLSW%2CLSN%2CLBS%2CFBC%2CLAF%2CFBW%2CFBP%2CFBI%2CFBM%2CFBA%2CBIB-N%2CFBH%2CFBD%2CTheaBib&values%5B1%5D=location&after%5B1%5D=&before%5B1%5D=now&limit%5B1%5D=1&refresh=&_=1417122682724" private val DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") @Subscribe public open fun onRequestLocations(e: RequestLocationsEvent) { requestLocationsAsync(); } public open fun requestLocationsAsync() { async { val locations = getLocations() uiThread { bus.post(UpdateLocationsEvent(locations)) } } } @Throws(NetworkException::class) public open fun getLocations(): Map<String, Location> { val request = Request.Builder().url(URL).build() val jsonp = try { http.newCall(request).execute().body().string() } catch (e: IOException) { throw NetworkException(e) } val json = jsonp.substringAfter('(').substringBeforeLast(')') return getLocations(json) } @Throws(NetworkException::class) public open fun getLocations(json: String): Map<String, Location> { var locations: MutableMap<String, Location> = HashMap() val parser = JSONParser() try { parseRecursively(locations, parser.parse(json)) } catch (e: ParseException) { throw NetworkException(e) } filters.forEach { locations = it.apply(locations) } lastResults = locations return locations } @Produce public fun getLastResults(): UpdateLocationsEvent { return UpdateLocationsEvent(lastResults) } private fun parseRecursively(locations: MutableMap<String, Location>, root: Any) { if (root is JSONObject) { if (root.containsKeys("location_name", "free_seats")) { parseFreeSeatMeasurement(locations, root) } else if (root.containsKeys("name", "long_name")) { parseLocation(locations, root) } else { root.values().forEach { parseRecursively(locations, it!!) } } } else if (root is JSONArray) { root.forEach { parseRecursively(locations, it!!) } } } private fun parseLocation(locations: MutableMap<String, Location>, node: JSONObject) { val name = node.string("name")!! val location = locations.getOrPut(name, { Location(name) }) val coordinates = node.string("geo_coordinates") location.name = node.string("long_name") location.building = node.string("building") location.room = node.string("room") location.level = node.string("level") location.superLocationString = node.string("super_location") location.totalSeats = node.int("available_seats") ?: 0 location.openingHours.addAll(parseOpeningHourPairs(node)) if (coordinates != null) location.coordinates = parseLatLng(coordinates) } private fun parseOpeningHourPairs(json: JSONObject): List<OpeningHourPair> { val hoursArray = json.obj("opening_hours")?.array("weekly_opening_hours")!! return hoursArray.flatMap { val (open, close) = (it as JSONArray) .map { it as JSONObject } .map { DATE_TIME_FORMAT.parseLocalDateTime(it.string("date")) } val openWeekday = open.toWeekday() val closeWeekday = close.toWeekday() (openWeekday..closeWeekday).map { weekday -> if(openWeekday == weekday && closeWeekday == weekday) { OpeningHourPair(weekday, open.toLocalTime(), close.toLocalTime()) } else { val openTime = if (openWeekday < weekday) LocalTime.MIDNIGHT else open.toLocalTime() val closeTime = if(closeWeekday > weekday) LocalTime(23, 59, 59) else close.toLocalTime() OpeningHourPair(weekday, openTime, closeTime) } } } } private fun parseFreeSeatMeasurement(locations: MutableMap<String, Location>, json: JSONObject) { val name = json.string("location_name")!! val freeSeats = json.int("free_seats") val date = DATE_TIME_FORMAT.parseLocalDateTime(json.obj("timestamp")?.string("date")) val location = locations.getOrPut(name, { Location(name) }) if (freeSeats != null) location.measurements.add(FreeSeatMeasurement(date, freeSeats)) } private fun parseLatLng(geoCoordinates: String): LatLng { val (lat, lng) = geoCoordinates.split(";").map { it.toDouble() } return LatLng(lat, lng) } }
app/src/main/java/de/maxvogler/learningspaces/services/LocationService.kt
4109983342
package mil.nga.giat.mage.geopackage.media import android.app.Application import android.webkit.MimeTypeMap import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import mil.nga.geopackage.GeoPackageCache import mil.nga.geopackage.GeoPackageFactory import mil.nga.geopackage.extension.related.RelatedTablesExtension import java.io.File import javax.inject.Inject enum class GeoPackageMediaType { IMAGE, VIDEO, AUDIO, OTHER; companion object { fun fromContentType(contentType: String): GeoPackageMediaType { return when { contentType.contains("image/") -> IMAGE contentType.contains("video/") -> VIDEO contentType.contains("audio/") -> AUDIO else -> OTHER } } } } data class GeoPackageMedia(val path: String, val type: GeoPackageMediaType) @HiltViewModel open class GeoPackageMediaViewModel @Inject constructor( val application: Application ) : ViewModel() { private var file: File? = null private val geoPackageCache = GeoPackageCache(GeoPackageFactory.getManager(application)) private val _geoPackageMedia = MutableLiveData<GeoPackageMedia>() val geoPackageMedia: LiveData<GeoPackageMedia> = _geoPackageMedia override fun onCleared() { super.onCleared() file?.delete() file = null } fun setMedia(geoPackageName: String, mediaTable: String, mediaId: Long) { viewModelScope.launch(Dispatchers.IO) { getMedia(geoPackageName, mediaTable, mediaId)?.let { media -> _geoPackageMedia.postValue(media) } } } private fun getMedia( geoPackageName: String, mediaTable: String, mediaId: Long ): GeoPackageMedia? { val geoPackage = geoPackageCache.getOrOpen(geoPackageName) val relatedTablesExtension = RelatedTablesExtension(geoPackage) val mediaDao = relatedTablesExtension.getMediaDao(mediaTable) val mediaRow = mediaDao.getRow(mediaDao.queryForIdRow(mediaId)) return mediaRow.columns.getColumnIndex("content_type", false)?.let { index -> val contentType = mediaRow.getValue(index).toString() val path = saveMedia(geoPackageName, mediaTable, mediaId, mediaRow.data, contentType) GeoPackageMedia(path, GeoPackageMediaType.fromContentType(contentType)) } } private fun saveMedia( geoPackageName: String, mediaTable: String, mediaId: Long, data: ByteArray, contentType: String ): String { val directory = File(application.cacheDir, "geopackage").apply { mkdirs() } val tempFile = File.createTempFile( "${geoPackageName}_${mediaTable}_${mediaId}", ".${MimeTypeMap.getSingleton().getExtensionFromMimeType(contentType)}", directory ) tempFile.writeBytes(data) file = tempFile return tempFile.absolutePath } }
mage/src/main/java/mil/nga/giat/mage/geopackage/media/GeoPackageMediaViewModel.kt
1644606472
package mil.nga.giat.mage.network.gson.observation import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import mil.nga.giat.mage.network.gson.nextLongOrNull import mil.nga.giat.mage.network.gson.nextStringOrNull import mil.nga.giat.mage.sdk.datastore.observation.Attachment class AttachmentTypeAdapter: TypeAdapter<Attachment>() { override fun write(out: JsonWriter, value: Attachment) { throw UnsupportedOperationException() } override fun read(reader: JsonReader): Attachment { val attachment = Attachment() attachment.isDirty = false if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return attachment } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "id" -> attachment.remoteId = reader.nextString() "action" -> attachment.action = reader.nextStringOrNull() "observationFormId" -> attachment.observationFormId = reader.nextString() "fieldName" -> attachment.fieldName = reader.nextString() "contentType" -> attachment.contentType = reader.nextStringOrNull() "size" -> attachment.size = reader.nextLongOrNull() "name" -> attachment.name = reader.nextStringOrNull() "url" -> attachment.url = reader.nextStringOrNull() "localPath" -> attachment.localPath = reader.nextStringOrNull() "relativePath" -> attachment.remotePath = reader.nextStringOrNull() else -> reader.skipValue() } } reader.endObject() return attachment } }
mage/src/main/java/mil/nga/giat/mage/network/gson/observation/AttachmentTypeAdapter.kt
1676741706
package com.sampsonjoliver.firestarter.views.gallery import android.app.Activity import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.sampsonjoliver.firestarter.FirebaseActivity import com.sampsonjoliver.firestarter.R import com.sampsonjoliver.firestarter.models.Message import com.sampsonjoliver.firestarter.views.GridSpacingItemDecoration import kotlinx.android.synthetic.main.activity_gallery.* import kotlinx.android.synthetic.main.item_photo_thumbnail.view.* import java.util.* class GalleryActivity : FirebaseActivity() { companion object { val EXTRA_TITLE = "EXTRA_TITLE" val EXTRA_MESSAGES = "EXTRA_MESSAGES" } val messages by lazy { intent.getParcelableArrayListExtra<Message>(EXTRA_MESSAGES) } val title by lazy { intent.getStringExtra(EXTRA_TITLE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_gallery) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = title val spacingPx = 5 val manager = GridLayoutManager(this, 4) recycler.addItemDecoration(GridSpacingItemDecoration(4, spacingPx, true)) recycler?.layoutManager = manager recycler?.adapter = PhotoAdapter(messages) } inner class PhotoAdapter(val messages: List<Message>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { holder?.itemView?.drawee?.setImageURI(messages[position].contentThumbUri) holder?.itemView?.setOnClickListener { GalleryItemFragment.newInstance(ArrayList(messages), position).show(fragmentManager, "") } } override fun getItemCount(): Int = messages.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(parent?.context)?.inflate(R.layout.item_photo_thumbnail, parent, false) return PhotoThumbnailHolder(view) } } inner class PhotoThumbnailHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { } }
app/src/main/java/com/sampsonjoliver/firestarter/views/gallery/GalleryActivity.kt
499763470
package org.fossasia.susi.ai.rest.responses.susi import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Created by meeera on 30/6/17. */ class UserSetting { /** * Gets session * * @return the session */ @SerializedName("session") @Expose val session: Session? = null /** * Gets settings * * @return the settings */ @SerializedName("settings") @Expose val settings: Settings? = null }
app/src/main/java/org/fossasia/susi/ai/rest/responses/susi/UserSetting.kt
1590644193
package com.baulsupp.okurl.test private fun runMain(s: String) { com.baulsupp.okurl.main(s.split(" ").toTypedArray()) } fun main() { runMain("-i -r https://httpbin.org/brotli") }
src/test/kotlin/com/baulsupp/okurl/test/TestMain.kt
795520450
package permissions.dispatcher.processor.impl.kotlin import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FunSpec class WriteSettingsHelper : SensitivePermissionInterface { private val PERMISSION_UTILS = ClassName("permissions.dispatcher", "PermissionUtils") private val SETTINGS = ClassName("android.provider", "Settings") private val INTENT = ClassName("android.content", "Intent") private val URI = ClassName("android.net", "Uri") override fun addHasSelfPermissionsCondition(builder: FunSpec.Builder, activity: String, permissionField: String) { builder.beginControlFlow("if (%T.hasSelfPermissions(%N, *%N) || %T.System.canWrite(%N))", PERMISSION_UTILS, activity, permissionField, SETTINGS, activity) } override fun addRequestPermissionsStatement(builder: FunSpec.Builder, targetParam: String, activityVar: String, requestCodeField: String) { builder.addStatement("val intent = %T(%T.ACTION_MANAGE_WRITE_SETTINGS, %T.parse(\"package:\" + %N!!.getPackageName()))", INTENT, SETTINGS, URI, activityVar) builder.addStatement("%N.startActivityForResult(intent, %N)", targetParam, requestCodeField) } }
processor/src/main/kotlin/permissions/dispatcher/processor/impl/kotlin/WriteSettingsHelper.kt
3849574621
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.mountables import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.core.width import com.facebook.litho.dp import com.facebook.litho.kotlin.widget.Text class SimpleImageViewWithAccessibilityExampleComponent : KComponent() { override fun ComponentScope.render(): Component { return Column(style = Style.padding(all = 20.dp)) { child( SimpleImageViewWithAccessibility( style = Style.width(100.dp).height(100.dp).margin(all = 50.dp))) child( Text( "Litho logo with a11y features rendered using a Mountable Component", textSize = 16f.dp)) } } }
sample/src/main/java/com/facebook/samples/litho/kotlin/mountables/SimpleImageViewWithAccessibilityExampleComponent.kt
2568317479
package shark import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.CliktError import com.github.ajalt.clikt.core.Context import com.github.ajalt.clikt.core.UsageError import com.github.ajalt.clikt.output.TermUi import com.github.ajalt.clikt.parameters.groups.OptionGroup import com.github.ajalt.clikt.parameters.groups.cooccurring import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import com.github.ajalt.clikt.parameters.options.versionOption import com.github.ajalt.clikt.parameters.types.file import shark.DumpProcessCommand.Companion.dumpHeap import shark.SharkCliCommand.HeapDumpSource.HprofFileSource import shark.SharkCliCommand.HeapDumpSource.ProcessSource import shark.SharkLog.Logger import java.io.File import java.io.PrintWriter import java.io.StringWriter import java.util.Properties import java.util.concurrent.TimeUnit.SECONDS class SharkCliCommand : CliktCommand( name = "shark-cli", // This ASCII art is a remix of a shark from -David "TAZ" Baltazar- and chick from jgs. help = """ |Version: $versionName | |``` |$S ^`. .=""=. |$S^_ \ \ / _ _ \ |$S\ \ { \ | d b | |$S{ \ / `~~~--__ \ /\ / |$S{ \___----~~' `~~-_/'-=\/=-'\, |$S \ /// a `~. \ \ |$S / /~~~~-, ,__. , /// __,,,,) \ | |$S \/ \/ `~~~; ,---~~-_`/ \ / \/ |$S / / '. .' |$S '._.' _|`~~`|_ |$S /|\ /|\ |``` """.trimMargin() ) { private class ProcessOptions : OptionGroup() { val processName by option( "--process", "-p", help = "Full or partial name of a process, e.g. \"example\" would match \"com.example.app\"" ).required() val device by option( "-d", "--device", metavar = "ID", help = "device/emulator id" ) } private val processOptions by ProcessOptions().cooccurring() private val obfuscationMappingPath by option( "-m", "--obfuscation-mapping", help = "path to obfuscation mapping file" ).file() private val verbose by option( help = "provide additional details as to what shark-cli is doing" ).flag("--no-verbose") private val heapDumpFile by option("--hprof", "-h", help = "path to a .hprof file").file( exists = true, folderOkay = false, readable = true ) init { versionOption(versionName) } class CommandParams( val source: HeapDumpSource, val obfuscationMappingPath: File? ) sealed class HeapDumpSource { class HprofFileSource(val file: File) : HeapDumpSource() class ProcessSource( val processName: String, val deviceId: String? ) : HeapDumpSource() } override fun run() { if (verbose) { setupVerboseLogger() } if (processOptions != null && heapDumpFile != null) { throw UsageError("Option --process cannot be used with --hprof") } else if (processOptions != null) { context.sharkCliParams = CommandParams( source = ProcessSource(processOptions!!.processName, processOptions!!.device), obfuscationMappingPath = obfuscationMappingPath ) } else if (heapDumpFile != null) { context.sharkCliParams = CommandParams( source = HprofFileSource(heapDumpFile!!), obfuscationMappingPath = obfuscationMappingPath ) } else { throw UsageError("Must provide one of --process, --hprof") } } private fun setupVerboseLogger() { class CLILogger : Logger { override fun d(message: String) { echo(message) } override fun d( throwable: Throwable, message: String ) { d("$message\n${getStackTraceString(throwable)}") } private fun getStackTraceString(throwable: Throwable): String { val stringWriter = StringWriter() val printWriter = PrintWriter(stringWriter, false) throwable.printStackTrace(printWriter) printWriter.flush() return stringWriter.toString() } } SharkLog.logger = CLILogger() } companion object { /** Zero width space */ private const val S = '\u200b' var Context.sharkCliParams: CommandParams get() { var ctx: Context? = this while (ctx != null) { if (ctx.obj is CommandParams) return ctx.obj as CommandParams ctx = ctx.parent } throw IllegalStateException("CommandParams not found in Context.obj") } set(value) { obj = value } fun CliktCommand.retrieveHeapDumpFile(params: CommandParams): File { return when (val source = params.source) { is HprofFileSource -> source.file is ProcessSource -> dumpHeap(source.processName, source.deviceId) } } fun CliktCommand.echoNewline() { echo("") } /** * Copy of [CliktCommand.echo] to make it publicly visible and therefore accessible * from [CliktCommand] extension functions */ fun CliktCommand.echo( message: Any?, trailingNewline: Boolean = true, err: Boolean = false, lineSeparator: String = context.console.lineSeparator ) { TermUi.echo(message, trailingNewline, err, context.console, lineSeparator) } fun runCommand( directory: File, vararg arguments: String ): String { val process = ProcessBuilder(*arguments) .directory(directory) .start() .also { it.waitFor(10, SECONDS) } // See https://github.com/square/leakcanary/issues/1711 // On Windows, the process doesn't always exit; calling to readText() makes it finish, so // we're reading the output before checking for the exit value val output = process.inputStream.bufferedReader().readText() if (process.exitValue() != 0) { val command = arguments.joinToString(" ") val errorOutput = process.errorStream.bufferedReader() .readText() throw CliktError( "Failed command: '$command', error output:\n---\n$errorOutput---" ) } return output } private val versionName = run { val properties = Properties() properties.load( SharkCliCommand::class.java.getResourceAsStream("/version.properties") ?: throw IllegalStateException("version.properties missing") ) properties.getProperty("version_name") ?: throw IllegalStateException( "version_name property missing" ) } } }
shark-cli/src/main/java/shark/SharkCliCommand.kt
2494563494
package net.dinkla.raytracer.lights import net.dinkla.raytracer.colors.Color import net.dinkla.raytracer.hits.Shade import net.dinkla.raytracer.materials.IMaterial import net.dinkla.raytracer.math.Normal import net.dinkla.raytracer.math.Point3D import net.dinkla.raytracer.math.Ray import net.dinkla.raytracer.math.Vector3D import net.dinkla.raytracer.worlds.World import java.util.* class AreaLight : Light(), ILightSource { var `object`: ILightSource? = null // Emissive Material TODO: Warum nicht Emissive? var material: IMaterial? = null var numSamples: Int = 0 inner class Sample { var samplePoint: Point3D? = null var lightNormal: Normal? = null var wi: Vector3D? = null val nDotD: Double get() = (-lightNormal!!) dot (wi!!) } init { numSamples = 4 } fun L(world: World, sr: Shade, sample: Sample): Color { return if (sample.nDotD > 0) { sr.material?.getLe(sr) ?: world.backgroundColor } else { Color.BLACK } } fun inShadow(world: World, ray: Ray, sr: Shade, sample: Sample): Boolean { val d = sample.samplePoint!!.minus(ray.origin).dot(ray.direction) return world.inShadow(ray, sr, d) } fun G(sr: Shade, sample: Sample): Double { val nDotD = sample.nDotD val d2 = sample.samplePoint!!.sqrDistance(sr.hitPoint) return nDotD / d2 } override fun pdf(sr: Shade): Double { return `object`!!.pdf(sr) } fun getSample(sr: Shade): Sample { val sample = Sample() sample.samplePoint = `object`!!.sample() sample.lightNormal = `object`!!.getNormal(sample.samplePoint!!) sample.wi = sample.samplePoint!!.minus(sr.hitPoint).normalize() return sample } fun getSamples(sr: Shade): List<Sample> { val result = ArrayList<Sample>() for (i in 0 until numSamples) { result.add(getSample(sr)) } return result } override fun sample(): Point3D { throw RuntimeException("NLU") } override fun getNormal(p: Point3D): Normal { throw RuntimeException("NLU") } override fun L(world: World, sr: Shade): Color { throw RuntimeException("NLU") } override fun getDirection(sr: Shade): Vector3D { throw RuntimeException("NLU") } override fun inShadow(world: World, ray: Ray, sr: Shade): Boolean { throw RuntimeException("NLU") } }
src/main/kotlin/net/dinkla/raytracer/lights/AreaLight.kt
761351853
/* * Copyright 2016 Jonathan Beaudoin * * 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.xena.cs /** * Created by Jonathan on 7/24/2016. */ enum class Weapons(val id: Int, val skin: Int = -1, val customSkin: Boolean = (skin != -1)) { DESERT_EAGLE(1, CRIMSON_WEB), FIVE_SEVEN(3, MONKEY_BUSINESS), GLOCK(4, FADE), CZ75A(63, CRIMSON_WEB), DUAL_BERRETA(2, URBAN_SHOCK), P2000(32, IMPERIAL_DRAGON), P250(36, ASIIMOV_2), R8_REVOLVER(6, REBOOT), TEC9(30, AVALANCHE), USP_SILENCER(61, KILL_CONFIRMED), AK47(7, FRONTSIDE_MISTY), AUG(8, AKIHABARA_ACCEPT), AWP(9, DRAGON_LORE), FAMAS(10, AFTERIMAGE), M4A1_SILENCER(60, MECHA_INDUSTRIES), M4A4(16, HOWL), SSG08(40, DETOUR), PP_BIZON(26, JUDGEMENT_OF_ANUBIS), P90(19, DEATH_BY_KITTY), UMP45(24, PRIMAL_SABER), G3SG1(11), GALIL(13), M249(14), MAC10(17), XM1014(25), MAG7(27), NEGEV(28), SAWED_OFF(29), ZEUS_X27(31), MP7(33), MP9(34), NOVA(35), SCAR20(38), SG556(39), KNIFE(42), FLASH_GRENADE(43), EXPLOSIVE_GRENADE(44), SMOKE_GRENADE(45), MOLOTOV(46), DECOY_GRENADE(47), INCENDIARY_GRENADE(48), C4(49), KNIFE_T(59, MARBLE_FADE), KNIFE_CT(41, MARBLE_FADE), KNIFE_BAYONET(500), KNIFE_FLIP(505), KNIFE_GUT(506), KNIFE_KARAMBIT(507, MARBLE_FADE), KNIFE_M9_BAYONET(508, MARBLE_FADE), KNIFE_TACTICAL(509), KNIFE_TALCHION(512), KNIFE_BOWIE(514), KNIFE_BUTTERFLY(515), KNIFE_PUSH(516), FISTS(69), MEDISHOT(57), TABLET(72), DIVERSION_DEVICE(82), FIRE_BOMB(81), CHARGE(70), HAMMER(76); companion object { private val cachedValues = values() @JvmStatic fun byID(id: Int) = cachedValues.firstOrNull { it.id == id } } }
src/main/kotlin/org/xena/cs/Weapons.kt
3082223670
package hr.caellian.math.internal /** * You don't need to interact with this class in most cases as it's handled by Matrix * classes automatically. * * This class is based on Apache Math LUDecomposition class but is optimised to work * better with this library as it doesn't calculate data this library doesn't use. * * @since 2.0.0 * @author Caellian */ object Inverse { /** * Java implementation of Doolittle LUP matrix decomposition algorithm. * * @param lu input matrix which will turn into LU data matrix. * @param singularityThreshold singularity threshold. This should be a very low number. * @return Pivot decomposition data. */ @JvmStatic fun doolittleLUP(lu: Array<Array<Double>>, singularityThreshold: Double): Array<Int> { if (lu.size != lu[0].size) { throw IllegalArgumentException("LU decomposition of non-square matrices not supported!") } val n = lu.size // Pivot val p = Array(n) { it } // Iterate over columns for (col in 0 until n) { // Upper matrix construction for (row in 0 until col) { val luRow = lu[row] var sum = luRow[col] for (i in 0 until row) { sum -= luRow[i] * lu[i][col] } luRow[col] = sum } // Lower matrix construction var max = col // Permutation row var largest = 0.0 for (row in col until n) { val luRow = lu[row] var sum = luRow[col] for (i in 0 until col) { sum -= luRow[i] * lu[i][col] } luRow[col] = sum // Maintain best permutation choice if (Math.abs(sum) > largest) { largest = Math.abs(sum) max = row } } // Singularity check if (Math.abs(lu[max][col]) < singularityThreshold) { throw IllegalArgumentException("LUP Decomposition impossible for singular matrices!") } // Pivot if necessary if (max != col) { val luMax = lu[max] val luCol = lu[col] var tmp: Double for (i in 0 until n) { tmp = luMax[i] luMax[i] = luCol[i] luCol[i] = tmp } val temp = p[max] p[max] = p[col] p[col] = temp } // Divide the lower elements by the "winning" diagonal elt. val luDiagonal = lu[col][col] for (row in col + 1 until n) { lu[row][col] /= luDiagonal } } return p } /** * Calculates inverse matrix of input matrix. Unwrapped matrix format is used to * increase performance. * * @param lu input matrix which will turn into LU data matrix. * @param singularityThreshold singularity threshold. This should be a very low number. * @return inverse matrix of given matrix. */ @JvmStatic fun inverseMatrix(lu: Array<Array<Double>>, singularityThreshold: Double): Array<Array<Double>> { // Decomposition pivot val p = doolittleLUP(lu, singularityThreshold) // Size of decomposed matrix val n = lu.size val b = Array(n) { _ -> Array(n) { 0.0 } } for (row in 0 until n) { val bRow = b[row] val pRow = p[row] for (col in 0 until n) { bRow[col] = (if (pRow == col) 1 else 0).toDouble() } } // Solve LY = b for (col in 0 until n) { val bpCol = b[col] for (i in col + 1 until n) { val bpI = b[i] val luICol = lu[i][col] for (j in 0 until n) { bpI[j] -= bpCol[j] * luICol } } } // Solve UX = Y for (col in n - 1 downTo 0) { val bpCol = b[col] val luDiag = lu[col][col] for (j in 0 until n) { bpCol[j] /= luDiag } for (i in 0 until col) { val bpI = b[i] val luICol = lu[i][col] for (j in 0 until n) { bpI[j] -= bpCol[j] * luICol } } } return b } }
src/main/kotlin/hr/caellian/math/internal/Inverse.kt
2319498187
//package org.koin.androidx.workmanager // //import android.content.Context //import androidx.work.ListenableWorker //import androidx.work.WorkerParameters //import com.google.common.util.concurrent.ListenableFuture // ///** // * @author Fabio de Matos // * @since 21/08/2020. // */ //open class MyListenableWorker1(context: Context, val workerParams: WorkerParameters) : // ListenableWorker(context, workerParams) { // override fun startWork(): ListenableFuture<Result> { // TODO("Not yet implemented") // } // //} // // //class MyListenableWorker2( // context: Context, // workerParams: WorkerParameters, // val dummyPayload: DummyPayload //) : // MyListenableWorker1(context, workerParams) { // override fun startWork(): ListenableFuture<Result> { // TODO("Not yet implemented") // } // //} // // //data class DummyPayload(val id: String) // //
koin-projects/koin-androidx-workmanager/src/test/java/org/koin/androidx/workmanager/Classes.kt
3915157527
package views import integration.Profile import photos.Album import photos.Photo //language=HTML fun photo(photo: Photo, album: Album, profile: Profile, redirectUrl: String?) = """ <!DOCTYPE html> <html lang="en"> <head> <title>${+album.title} - ${+photo.description} by ${+profile.name}</title> <meta name="viewport" content="width=device-width"> <meta name="medium" content="image"> <meta property="og:title" content="${+(photo.description ?: album.title)} by ${+profile.name}"> <meta property="og:image" content="${+photo.thumbUrlLarge}"> <link rel="image_src" href="${+photo.thumbUrlLarge}"> <style> html, body { background: black; color: gray; font-family: sans-serif } a { color: white } img { padding: 1em 0; max-height: 90vh; max-width: 95vw; cursor: pointer } </style> </head> <body> <div itemscope itemtype="http://schema.org/Photograph"> <meta itemprop="datePublished" content="${photo.date}"> <a href="${album.url}">${+album.title} by <span itemprop="author">${+profile.name}</span></a> <span itemprop="description">${+photo.description}</span> <div> <img itemprop="image" src="${photo.fullHdUrl}" alt="${+(photo.description ?: album.title)}"> </div> </div> ${redirectUrl / """<script>location.href = '$redirectUrl'</script>""" }} </body> </html> """
src/views/photo.kt
321746095
package com.artfable.telegram.api import com.artfable.telegram.api.request.GetUpdatesRequest import com.artfable.telegram.api.service.TelegramSender import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import org.mockito.ArgumentMatchers.any import org.mockito.BDDMockito.given import org.mockito.Mock import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.junit.jupiter.MockitoExtension import java.lang.reflect.InvocationTargetException import java.util.concurrent.Executor import kotlin.reflect.full.declaredMemberFunctions import kotlin.reflect.jvm.isAccessible /** * @author aveselov * @since 08/08/2020 */ @ExtendWith(MockitoExtension::class) internal class LongPollingTelegramBotTest { @Mock private lateinit var taskExecutor: Executor @Mock private lateinit var telegramSender: TelegramSender @Mock private lateinit var behaviour: Behaviour @Mock private lateinit var behaviour2: Behaviour @Test fun subscribeToUpdates() { val longPollingTelegramBot = createBot() val updates = listOf(Update(1L)) given(telegramSender.executeMethod<List<Update>>(GetUpdatesRequest(timeout = 100))).willReturn(updates) callSubscribeToUpdates(longPollingTelegramBot) verify(behaviour).parse(updates) verify(behaviour2).parse(updates) verify(taskExecutor).execute(any()) } @Test fun subscribeToUpdates_skipFailed() { val longPollingTelegramBot = createBot() val updates = listOf(Update(1L)) given(telegramSender.executeMethod<List<Update>>(GetUpdatesRequest(timeout = 100))).willReturn(updates) given(behaviour.parse(updates)).willThrow(IllegalArgumentException::class.java) callSubscribeToUpdates(longPollingTelegramBot) verify(behaviour2).parse(updates) verify(taskExecutor).execute(any()) } @Test fun subscribeToUpdates_doNotSkipFailed() { val longPollingTelegramBot = createBot(false) val updates = listOf(Update(1L)) given(telegramSender.executeMethod<List<Update>>(GetUpdatesRequest(timeout = 100))).willReturn(updates) given(behaviour.parse(updates)).willThrow(IllegalArgumentException::class.java) assertThrows<IllegalArgumentException> { callSubscribeToUpdates(longPollingTelegramBot) } verify(behaviour2).parse(updates) verify(taskExecutor, never()).execute(any()) } private fun createBot(skipFailed: Boolean? = null): LongPollingTelegramBot { return if (skipFailed == null) { object : LongPollingTelegramBot(taskExecutor, telegramSender, setOf(behaviour, behaviour2), setOf()) {} } else { object : LongPollingTelegramBot(taskExecutor, telegramSender, setOf(behaviour, behaviour2), setOf(), skipFailed) {} } } private fun callSubscribeToUpdates(bot: LongPollingTelegramBot) { try { LongPollingTelegramBot::class.declaredMemberFunctions.asSequence() .filter { it.name == "subscribeToUpdates" } .onEach { it.isAccessible = true } .first() .call(bot, null) } catch (e: InvocationTargetException) { throw e.targetException } } }
src/test/kotlin/com/artfable/telegram/api/LongPollingTelegramBotTest.kt
3330288331
package io.jentz.winter import org.opentest4j.AssertionFailedError inline fun <T> expectValueToChange(from: T, to: T, valueProvider: () -> T, block: () -> Unit) { val a = valueProvider() if (a != from) fail("Expected initial value to be ${formatValue(from)} but was ${formatValue(a)}") block() val b = valueProvider() if (b != to) fail("Expected change from ${formatValue(from)} to ${formatValue(to)} but was ${formatValue(b)}") } internal inline fun <reified S : UnboundService<*>> Component.shouldContainServiceOfType(key: TypeKey<*>) { val service = this[key] ?: fail("Component was expected to contain service with key <$key> but doesn't") if (service !is S) fail("Service with key <$key> was expected to be <${S::class}> but was <${service.javaClass}>.") } internal fun Component.shouldContainService(key: TypeKey<*>) { if (!containsKey(key)) fail("Component was expected to contain service with key <$key> but doesn't") } internal fun Component.shouldNotContainService(key: TypeKey<*>) { if (containsKey(key)) fail("Component wasn't expected to contain service with key <$key> but does.") } fun fail(message: String): Nothing { throw AssertionFailedError(message) } @PublishedApi internal fun formatValue(any: Any?) = when (any) { is String -> "\"$any\"" else -> "<$any>" }
winter/src/test/kotlin/io/jentz/winter/assertions.kt
2095932735
package cz.softdeluxe.jlib import cz.softdeluxe.jlib.entity.getEnumByKod import cz.softdeluxe.jlib.entity.getEnumByText import cz.softdeluxe.jlib.entity.roundHalfUp import org.junit.Assert.assertEquals import org.junit.Test import java.math.BigDecimal /** * User: Petr Balat * Date: 2.4.2014 */ class EntityUtilTest { @Test fun getEnumByKod() { assertEquals(Obor.ADMINISTRATIVA, getEnumByKod<Obor>(1)) assertEquals(Obor.MANAGMENT, getEnumByKod<Obor>(7)) } @Test fun getEnumByText() { assertEquals(Obor.MANAGMENT, getEnumByText<Obor>("Management")) assertEquals(Obor.KULTURA_SPORT, getEnumByText<Obor>("Kultura a sport")) } @Test fun roundHalfUp() { assertEquals(BigDecimal("1"), BigDecimal("1.4999").roundHalfUp()) assertEquals(BigDecimal("2"), BigDecimal("1.50").roundHalfUp()) assertEquals(BigDecimal("1.43"), BigDecimal("1.425").roundHalfUp(2)) assertEquals(BigDecimal("1.50"), BigDecimal("1.504").roundHalfUp(2)) } }
src/test/java/cz/softdeluxe/jlib/EntityUtilTest.kt
3579053530
package org.xmbirds.gallery import android.os.Bundle import io.flutter.app.FlutterActivity import io.flutter.plugins.GeneratedPluginRegistrant class MainActivity(): FlutterActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GeneratedPluginRegistrant.registerWith(this) } }
gallery/android/app/src/main/kotlin/org/xmbirds/gallery/MainActivity.kt
1024881534
package com.krawczyk.maciej.simpleremotecontroller.android.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.krawczyk.maciej.simpleremotecontroller.R import com.krawczyk.maciej.simpleremotecontroller.data.model.Weather import com.krawczyk.maciej.simpleremotecontroller.data.model.WeatherModel import com.krawczyk.maciej.simpleremotecontroller.domain.mappers.WeatherMapper import kotlinx.android.synthetic.main.fragment_adjustable_on_off.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class AdjustableOnOffFragment : BaseFragment() { private val weather = Weather() override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater!!.inflate(R.layout.fragment_adjustable_on_off, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews() } private fun setupViews() { val getSetWeather = weatherService.setWeather getSetWeather.enqueue(getCallback()) btn_set.setOnClickListener({ weather.temperature = et_furnace_when.text.toString().toDouble() weather.humidity = et_airing_when.text.toString().toDouble() val setWeather = weatherService.setTemperatureAndAiring(WeatherMapper.getWeatherModel(weather)) setWeather.enqueue(getCallback()) }) } private fun getCallback(): Callback<WeatherModel> { return object : Callback<WeatherModel> { override fun onResponse(call: Call<WeatherModel>, response: Response<WeatherModel>) { if (response.isSuccessful && response.body() != null) { et_furnace_when.setText(response.body()!!.temperature.toString()) et_airing_when.setText(response.body()!!.humidity.toString()) } } override fun onFailure(call: Call<WeatherModel>, t: Throwable) { Log.d("Weather Response: ", t.message) } } } companion object { fun newInstance(): AdjustableOnOffFragment { return AdjustableOnOffFragment() } } }
app/src/main/java/com/krawczyk/maciej/simpleremotecontroller/android/fragments/AdjustableOnOffFragment.kt
2717760022
package wu.seal.jsontokotlin import com.winterbe.expekt.should import org.junit.Test import org.junit.Before import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass import wu.seal.jsontokotlin.model.classscodestruct.DataClass import wu.seal.jsontokotlin.model.classscodestruct.ListClass import wu.seal.jsontokotlin.model.classscodestruct.Property import wu.seal.jsontokotlin.test.TestConfig import wu.seal.jsontokotlin.utils.classgenerator.ListClassGeneratorByJSONArray class ListClassGeneratorByJSONArrayTest { @Before fun setUp() { TestConfig.setToTestInitState() } @Test fun generateBaseListTypeTest() { ListClassGeneratorByJSONArray("TestList", "[]").generate() .should.be.equal(ListClass("TestList", KotlinClass.ANY)) ListClassGeneratorByJSONArray("TestList", "[1]").generate() .should.be.equal(ListClass("TestList", KotlinClass.INT)) ListClassGeneratorByJSONArray("TestList", "[1.0]").generate() .should.be.equal(ListClass("TestList", KotlinClass.DOUBLE)) ListClassGeneratorByJSONArray("TestList", "[true]").generate() .should.be.equal(ListClass("TestList", KotlinClass.BOOLEAN)) ListClassGeneratorByJSONArray("TestList", "[100000000000000]").generate() .should.be.equal(ListClass("TestList", KotlinClass.LONG)) ListClassGeneratorByJSONArray("TestList", "[null]").generate() .should.be.equal(ListClass("TestList", KotlinClass.ANY)) } @Test fun generateListClassWithDataClass() { val result = ListClassGeneratorByJSONArray("TestList", "[{p1:1}]").generate() val dataClassProperty = Property(name = "p1",originName = "p1",type = "Int",comment = "1",originJsonValue = "1",typeObject = KotlinClass.INT) val itemClass = DataClass(name = "TestListItem",properties = listOf(dataClassProperty)) result.should.be.equal(ListClass("TestList", itemClass)) } @Test fun generateListClassWithListClass() { val result = ListClassGeneratorByJSONArray("TestList", "[[]]").generate() result.should.be.equal(ListClass("TestList", ListClass("TestListSubList", KotlinClass.ANY))) } }
src/test/kotlin/wu/seal/jsontokotlin/ListClassGeneratorByJSONArrayTest.kt
1613209229
/* * Vision - free remote desktop software built with Kotlin * Copyright (C) 2016 Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.anglur.vision.net import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.channel.socket.DatagramPacket import io.netty.handler.codec.MessageToMessageDecoder import org.anglur.vision.net.packet.incoming import org.anglur.vision.util.extensions.readString class Decoder : MessageToMessageDecoder<DatagramPacket>() { override fun decode(ctx: ChannelHandlerContext, msg: DatagramPacket, out: MutableList<Any>) { val buff = msg.content() if (buff.readableBytes() > 0) { val packetId = buff.readUnsignedByte().toInt() println("Packet $packetId") //If secret has not been set, read the id instead. This should only happen during handshake (packet 0) val pos = buff.readerIndex() val session = Sessions[buff.readLong()] ?: Sessions[buff.readerIndex(pos).readString()] if (!ctx.channel().hasAttr(SESSION) && packetId != 0) { //If the key hasn't been set, than they are trying to fake a packet ctx.channel().close() return } else ctx.channel().attr(SESSION).set(session) incoming[packetId]!!(PacketPayload(buff, ctx, session)) } } fun session(c: Channel): RemoteSession? = c.attr(SESSION).get() override fun channelActive(ctx: ChannelHandlerContext) { session(ctx.channel())?.connect() } override fun channelUnregistered(ctx: ChannelHandlerContext) { session(ctx.channel())?.disconnect() } override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) = TODO() }
src/main/kotlin/org/anglur/vision/net/Decoder.kt
3468015883
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter class RsMatchArmCommaFormatProcessorTest : RsFormatterTestBase() { // https://internals.rust-lang.org/t/syntax-of-block-like-expressions-in-match-arms/5025 fun `test removes commas in match arms with blocks`() = doTextTest(""" fn main() { match x { 1 => 1, 2 => { 2 }, 3 => { 3 } 92 => unsafe { 3 }, 4 => loop {}, 5 => 5, 6 => if true {} else {}, 7 => 7 } } """, """ fn main() { match x { 1 => 1, 2 => { 2 } 3 => { 3 } 92 => unsafe { 3 }, 4 => loop {}, 5 => 5, 6 => if true {} else {}, 7 => 7 } } """) }
src/test/kotlin/org/rust/ide/formatter/RsMatchArmCommaFormatProcessorTest.kt
1136325219
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.completion.PrioritizedLookupElement import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.editor.EditorModificationUtil import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.ty.TyUnknown import org.rust.lang.core.types.type const val KEYWORD_PRIORITY = 10.0 fun createLookupElement(element: RsCompositeElement, scopeName: String): LookupElement { val base = LookupElementBuilder.create(element, scopeName) .withIcon(if (element is RsFile) RsIcons.MODULE else element.getIcon(0)) return when (element) { is RsMod -> if (scopeName == "self" || scopeName == "super") { base.withTailText("::") .withInsertHandler({ ctx, _ -> val offset = ctx.editor.caretModel.offset if (ctx.file.findElementAt(offset)?.parentOfType<RsUseGlobList>() == null) { ctx.addSuffix("::") } }) } else { base } is RsConstant -> base.withTypeText(element.typeReference?.text) is RsFieldDecl -> base.withTypeText(element.typeReference?.text) is RsFunction -> base .withTypeText(element.retType?.typeReference?.text ?: "()") .withTailText(element.valueParameterList?.text?.replace("\\s+".toRegex(), " ") ?: "()") .appendTailText(element.extraTailText, true) .withInsertHandler handler@ { context: InsertionContext, _: LookupElement -> if (context.isInUseBlock) return@handler if (!context.alreadyHasCallParens) { context.document.insertString(context.selectionEndOffset, "()") } EditorModificationUtil.moveCaretRelatively(context.editor, if (element.valueParameters.isEmpty()) 2 else 1) if (!element.valueParameters.isEmpty()) { AutoPopupController.getInstance(element.project)?.autoPopupParameterInfo(context.editor, element) } } is RsStructItem -> base .withTailText(when { element.blockFields != null -> " { ... }" element.tupleFields != null -> element.tupleFields!!.text else -> "" }) is RsEnumVariant -> base .withTypeText(element.parentOfType<RsEnumItem>()?.name ?: "") .withTailText(when { element.blockFields != null -> " { ... }" element.tupleFields != null -> element.tupleFields!!.tupleFieldDeclList .map { it.typeReference.text } .joinToString(prefix = "(", postfix = ")") else -> "" }) .withInsertHandler handler@ { context, _ -> if (context.isInUseBlock) return@handler val (text, shift) = when { element.tupleFields != null -> Pair("()", 1) element.blockFields != null -> Pair(" {}", 2) else -> return@handler } if (!(context.alreadyHasPatternParens || context.alreadyHasCallParens)) { context.document.insertString(context.selectionEndOffset, text) } EditorModificationUtil.moveCaretRelatively(context.editor, shift) } is RsPatBinding -> base .withTypeText(element.type.let { when (it) { is TyUnknown -> "" else -> it.toString() } }) is RsMacroBinding -> base.withTypeText(element.fragmentSpecifier) is RsMacroDefinition -> { val parens = when (element.name) { "vec" -> "[]" else -> "()" } base .withTailText("!") .withInsertHandler { context: InsertionContext, _: LookupElement -> context.document.insertString(context.selectionEndOffset, "!$parens") EditorModificationUtil.moveCaretRelatively(context.editor, 2) } } else -> base } } fun LookupElementBuilder.withPriority(priority: Double): LookupElement = PrioritizedLookupElement.withPriority(this, priority) private val InsertionContext.isInUseBlock: Boolean get() = file.findElementAt(startOffset - 1)!!.parentOfType<RsUseItem>() != null private val InsertionContext.alreadyHasCallParens: Boolean get() { val parent = file.findElementAt(startOffset)!!.parentOfType<RsExpr>() return (parent is RsDotExpr && parent.methodCall != null) || parent?.parent is RsCallExpr } private val InsertionContext.alreadyHasPatternParens: Boolean get() { val pat = file.findElementAt(startOffset)!!.parentOfType<RsPatEnum>() ?: return false return pat.path.textRange.contains(startOffset) } private val RsFunction.extraTailText: String get() = parentOfType<RsImplItem>()?.traitRef?.text?.let { " of $it" } ?: ""
src/main/kotlin/org/rust/lang/core/completion/LookupElements.kt
3617148124
package com.openlattice.hazelcast.serializers.shuttle import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.hazelcast.processors.shuttle.UpdateIntegrationEntryProcessor import org.springframework.stereotype.Component @Component class UpdateIntegrationEntryProcessorStreamSerializer : SelfRegisteringStreamSerializer<UpdateIntegrationEntryProcessor> { override fun getTypeId(): Int { return StreamSerializerTypeIds.UPDATE_INTEGRATION_EP.ordinal } override fun getClazz(): Class<out UpdateIntegrationEntryProcessor> { return UpdateIntegrationEntryProcessor::class.java } override fun write(out: ObjectDataOutput, `object`: UpdateIntegrationEntryProcessor) { IntegrationUpdateStreamSerializer.serialize(out, `object`.update) } override fun read(`in`: ObjectDataInput): UpdateIntegrationEntryProcessor { return UpdateIntegrationEntryProcessor(IntegrationUpdateStreamSerializer.deserialize(`in`)) } }
src/main/kotlin/com/openlattice/hazelcast/serializers/shuttle/UpdateIntegrationEntryProcessorStreamSerializer.kt
2030118426
package com.openlattice.linking import com.hazelcast.projection.Projection class LinkingFeedbackProjection: Projection<Map.Entry<EntityKeyPair, Boolean>, EntityLinkingFeedback> { override fun transform(input: Map.Entry<EntityKeyPair, Boolean>): EntityLinkingFeedback { return EntityLinkingFeedback( input ) } }
src/main/java/com/openlattice/linking/LinkingFeedbackProjection.kt
2053104807
package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.openlattice.hazelcast.StreamSerializerTypeIds import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind import org.springframework.stereotype.Component @Component class EdmPrimitiveTypeKindStreamSerializer : AbstractEnumSerializer<EdmPrimitiveTypeKind>() { companion object { @JvmStatic fun serialize(out: ObjectDataOutput, `object`: EdmPrimitiveTypeKind ) = AbstractEnumSerializer.serialize(out, `object`) @JvmStatic fun deserialize(`in`: ObjectDataInput): EdmPrimitiveTypeKind = deserialize(EdmPrimitiveTypeKind::class.java, `in`) } override fun getTypeId(): Int { return StreamSerializerTypeIds.EDM_PRIMITIVE_TYPE_KIND.ordinal } override fun getClazz(): Class<EdmPrimitiveTypeKind> { return EdmPrimitiveTypeKind::class.java } }
src/main/kotlin/com/openlattice/hazelcast/serializers/EdmPrimitiveTypeKindStreamSerializer.kt
1394222135
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.mapper import android.database.Cursor import com.moez.QKSMS.model.Contact interface CursorToContact : Mapper<Cursor, Contact> { fun getContactsCursor(): Cursor? }
domain/src/main/java/com/moez/QKSMS/mapper/CursorToContact.kt
2237412190
package blog.nanoservices import org.http4k.client.JavaHttpClient import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.then import org.http4k.filter.RequestFilters.ProxyHost import org.http4k.filter.RequestFilters.ProxyProtocolMode.Https import org.http4k.filter.ResponseFilters.ReportRouteLatency import org.http4k.server.SunHttp import org.http4k.server.asServer import java.lang.System.setProperty fun `latency reporting proxy`() = ProxyHost(Https) .then(ReportRouteLatency { req, ms -> println("$req took $ms") }) .then(JavaHttpClient()) .asServer(SunHttp()) .start() fun main() { setProperty("http.proxyHost", "localhost") setProperty("http.proxyPort", "8000") setProperty("http.nonProxyHosts", "localhost") `latency reporting proxy`().use { JavaHttpClient()(Request(GET, "http://github.com/")) } }
src/docs/blog/nanoservices/latency_reporting_proxy.kt
2517273950
package org.abhijitsarkar.touchstone.mockito import org.mockito.Mockito /** * @author Abhijit Sarkar */ fun <T> any(): T { Mockito.any<T>() return uninitialized() } @Suppress("UNCHECKED_CAST") fun <T> uninitialized(): T = null as T
touchstone/src/test/kotlin/mockito/MockitoUtils.kt
2075714708
package cm.aptoide.pt.download.view.outofspace import android.widget.ImageView import android.widget.TextView import cm.aptoide.pt.R import cm.aptoide.pt.networking.image.ImageLoader import cm.aptoide.pt.utils.AptoideUtils import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import com.fa.epoxysample.bundles.models.base.BaseViewHolder import rx.subjects.PublishSubject @EpoxyModelClass(layout = R.layout.out_of_space_installed_app_card) abstract class InstalledAppCardModel : EpoxyModelWithHolder<InstalledAppCardModel.CardHolder>() { @EpoxyAttribute var application: InstalledApp? = null @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var eventSubject: PublishSubject<String>? = null override fun bind(holder: CardHolder) { application?.let { app -> holder.name.text = app.appName ImageLoader.with(holder.itemView.context).load(app.icon, holder.appIcon) holder.appSize.text = AptoideUtils.StringU.formatBytes(app.size, false) handleUninstallClick(holder, app) } } private fun handleUninstallClick(holder: CardHolder, app: InstalledApp) { holder.uninstallButton.setOnClickListener { eventSubject?.onNext(app.packageName) } } class CardHolder : BaseViewHolder() { val appIcon by bind<ImageView>(R.id.app_icon) val name by bind<TextView>(R.id.app_name) val appSize by bind<TextView>(R.id.app_size) val uninstallButton by bind<TextView>(R.id.uninstall_button) } }
app/src/main/java/cm/aptoide/pt/download/view/outofspace/InstalledAppCardModel.kt
884970895
package me.sweetll.tucao.business.showtimes.adapter import android.widget.ImageView import com.chad.library.adapter.base.BaseSectionQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import me.sweetll.tucao.R import me.sweetll.tucao.extension.load import me.sweetll.tucao.model.raw.ShowtimeSection class ShowtimeAdapter(data: MutableList<ShowtimeSection>?): BaseSectionQuickAdapter<ShowtimeSection, BaseViewHolder>(R.layout.item_showtime, R.layout.item_showtime_header, data) { override fun convertHead(helper: BaseViewHolder, showtimeSection: ShowtimeSection) { helper.setText(R.id.text_week, showtimeSection.header) } override fun convert(helper: BaseViewHolder, showtimeSection: ShowtimeSection) { helper.setText(R.id.text_title, showtimeSection.t.title) val thumbImg = helper.getView<ImageView>(R.id.img_thumb) thumbImg.load(mContext, showtimeSection.t.thumb) } }
app/src/main/kotlin/me/sweetll/tucao/business/showtimes/adapter/ShowtimeAdapter.kt
2680476492
package com.aptoide.authentication.mock import com.aptoide.authentication.model.CodeAuth import com.aptoide.authentication.model.OAuth2 import com.aptoide.authentication.service.AuthenticationService import kotlinx.coroutines.delay class MockAuthenticationService : AuthenticationService { override suspend fun sendMagicLink(email: String): CodeAuth { delay(200) return CodeAuth("code", "estado de arte", "agente da pejota", false, CodeAuth.Data("TOKEN", "EMAIL"), "[email protected]") } override suspend fun authenticate(magicToken: String, state: String, agent: String): OAuth2 { delay(200) return OAuth2("OAUTH2", false, OAuth2.Data("accesst0k3nF4k3", 3000, "r3fr3shT0k3nF4k3", "Bearer", null)) } }
aptoide-authentication-core/src/main/kotlin/com/aptoide/authentication/mock/MockAuthenticationService.kt
837134209
/* * Copyright 2016 Juliane Lehmann <[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.lambdasoup.quickfit.ui import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.lambdasoup.quickfit.Constants.FITNESS_API_OPTIONS import com.lambdasoup.quickfit.FitActivityService.Companion.enqueueSyncSession import com.lambdasoup.quickfit.persist.FitApiFailureResolution import com.lambdasoup.quickfit.persist.FitApiFailureResolution.registerAsCurrentForeground import com.lambdasoup.quickfit.persist.FitApiFailureResolution.unregisterAsCurrentForeground import com.lambdasoup.quickfit.persist.FitApiFailureResolver import timber.log.Timber /** * Base class for activities that bind to [FitApiFailureResolution]; which allows to interrupt the * user with Fit Api connection failure resolution while this activity is in the foreground. Can also be started with an * intent with a failure connection result as extra to start the resolution process. */ abstract class FitFailureResolutionActivity : DialogActivity(), FitApiFailureResolver { private var failureResolutionInProgress = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { failureResolutionInProgress = savedInstanceState.getBoolean(KEY_FAILURE_RESOLUTION_IN_PROGRESS) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(KEY_FAILURE_RESOLUTION_IN_PROGRESS, failureResolutionInProgress) } override fun onStart() { super.onStart() registerAsCurrentForeground(this) } override fun onStop() { super.onStop() unregisterAsCurrentForeground(this) } override fun onResume() { super.onResume() // if started from notification (failure occurred while no activity was bound to FitApiFailureResolution) val account: GoogleSignInAccount? = intent.getParcelableExtra(EXTRA_PLAY_API_SIGNIN_ACCOUNT) if (account != null) { requestFitPermissions(account) } } override fun requestFitPermissions(account: GoogleSignInAccount) { if (failureResolutionInProgress) { // nothing to do return } failureResolutionInProgress = true try { GoogleSignIn.requestPermissions( this, REQUEST_FAILURE_RESOLUTION, account, FITNESS_API_OPTIONS ) } catch (e: ActivityNotFoundException) { Timber.e(e, "Exception while starting resolution activity") } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_FAILURE_RESOLUTION) { failureResolutionInProgress = false intent.removeExtra(EXTRA_PLAY_API_SIGNIN_ACCOUNT) if (resultCode == RESULT_OK) { enqueueSyncSession(applicationContext) } } else { super.onActivityResult(requestCode, resultCode, data) } } companion object { const val EXTRA_PLAY_API_SIGNIN_ACCOUNT = "com.lambdasoup.quickfit.play_api_connect_result" private const val REQUEST_FAILURE_RESOLUTION = 0 private const val KEY_FAILURE_RESOLUTION_IN_PROGRESS = "com.lambdasoup.quickfit.failure_resolution_in_progress" } }
app/src/main/java/com/lambdasoup/quickfit/ui/FitFailureResolutionActivity.kt
1272182061
package org.abhijitsarkar.touchstone.execution.junit import org.springframework.beans.BeanUtils import org.springframework.format.annotation.DateTimeFormat import java.io.Serializable import java.time.Instant import java.time.OffsetDateTime import java.time.ZoneOffset import javax.persistence.CollectionTable import javax.persistence.Column import javax.persistence.ElementCollection import javax.persistence.Embeddable import javax.persistence.EmbeddedId import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.JoinColumn import org.junit.platform.launcher.listeners.TestExecutionSummary as JUnitSummary /** * @author Abhijit Sarkar */ @Entity class JUnitExecutionSummary : Serializable { companion object { fun fromJUnit(junit: JUnitSummary): JUnitExecutionSummary { return JUnitExecutionSummary().apply { timeStarted = Instant .ofEpochMilli(junit.timeStarted) .atOffset(ZoneOffset.UTC) timeFinished = Instant .ofEpochMilli(junit.timeFinished) .atOffset(ZoneOffset.UTC) BeanUtils.copyProperties(junit, this) failures = junit.failures .map { TestFailure().also { tf -> tf.testId = it.testIdentifier.uniqueId tf.message = it.exception.message } } } } } @EmbeddedId lateinit var id: TestExecutionId @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) lateinit var timeStarted: OffsetDateTime @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) lateinit var timeFinished: OffsetDateTime var totalFailureCount = 0L var containersFoundCount = 0L var containersStartedCount = 0L var containersSkippedCount = 0L var containersAbortedCount = 0L var containersSucceededCount = 0L var containersFailedCount = 0L var testsFoundCount = 0L var testsStartedCount = 0L var testsSkippedCount = 0L var testsAbortedCount = 0L var testsSucceededCount = 0L var testsFailedCount = 0L @ElementCollection(fetch = FetchType.EAGER) @CollectionTable( name = "TEST_FAILURE", joinColumns = [ JoinColumn(name = "stepExecutionId", referencedColumnName = "stepExecutionId"), JoinColumn(name = "jobExecutionId", referencedColumnName = "jobExecutionId") ] ) var failures: List<TestFailure> = mutableListOf() } @Embeddable data class TestExecutionId( var stepExecutionId: Long, var jobExecutionId: Long ) : Serializable @Embeddable class TestFailure : Serializable { @Column(length = 999) lateinit var testId: String @Column(length = 999) var message: String? = null }
touchstone/src/main/kotlin/execution/junit/JUnitExecutionSummary.kt
2870478713
/* * MIT License * * Copyright (c) 2016 Hossain Khan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package info.hossainkhan.dailynewsheadlines import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import info.hossainkhan.android.core.headlines.HeadlinesContract import info.hossainkhan.android.core.headlines.HeadlinesPresenter import info.hossainkhan.android.core.model.NewsHeadlineItem import info.hossainkhan.android.core.model.NewsCategoryHeadlines import info.hossainkhan.android.core.model.NewsHeadlines import info.hossainkhan.android.core.model.ScreenType import info.hossainkhan.android.core.newsprovider.NewsProviderManager import kotlinx.android.synthetic.main.activity_headlines_nav_and_content.* import kotlinx.android.synthetic.main.headlines_item_viewpager_container.* import kotlinx.android.synthetic.main.headlines_main_content_container.* import kotlinx.android.synthetic.main.nav_header_main.* import timber.log.Timber import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class HeadlinesBrowseActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, HeadlinesContract.View { /** * The [android.support.v4.view.PagerAdapter] that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * [android.support.v13.app.FragmentStatePagerAdapter]. */ private var headlinesPagerAdapter: HeadlinesPagerAdapter? = null private lateinit var headlinesPresenter: HeadlinesPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_headlines_nav_and_content) setSupportActionBar(toolbar) supportActionBar?.title = getString(R.string.choose_source_title) setupNavigationDrawer() // NOTE use DI to inject val context = applicationContext val newsProviderManager = NewsProviderManager(context) headlinesPresenter = HeadlinesPresenter(context, this, newsProviderManager) } private fun setupNavigationDrawer() { val toggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer_layout.addDrawerListener(toggle) toggle.syncState() nav_view.setNavigationItemSelectedListener(this) sidebar_subtitle.text = SimpleDateFormat("EEE, d MMM yyy", Locale.getDefault()).format(Date()) } override fun onStop() { // NOTE - What happens when presenter is attached again. headlinesPresenter.detachView() super.onStop() } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_headlines_browse, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val isConsumed = headlinesPresenter.onMenuItemClicked(item) return if (isConsumed) { true } else { super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.action_add_news_source_feed -> { // Handle the camera action } } drawer_layout.closeDrawer(GravityCompat.START) return true } /** * Setups the navigation bar with all the news sources which can be selected. */ private fun setupNavigationDrawerAdapter(headlines: List<NewsHeadlines>) { nav_drawer_recycler_view.adapter = NewsSourceAdapter(headlines, this::onNewsSourceSelected) } /** * Updates toolbar title with currently selected content */ private fun updateToolbarTitle(title: String) { toolbar.title = title } fun onNewsSourceSelected(selectedRow: NewsCategoryHeadlines) { Timber.d("onNewsSourceSelected() called with: row = [${selectedRow}]") updateToolbarTitle(selectedRow.displayTitle ?: selectedRow.title!!) // Create the adapter that will return a fragment for each of the three // primary sections of the activity. if (headlinesPagerAdapter == null) { // Set up the ViewPager with the sections adapter. headlinesPagerAdapter = HeadlinesPagerAdapter(fragmentManager, selectedRow.newsHeadlines!!) news_headlines_pager_container.adapter = headlinesPagerAdapter } else { headlinesPagerAdapter!!.setData(selectedRow.newsHeadlines!!) news_headlines_pager_container.setCurrentItem(0, true) } if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } } // // HeadlinesContract.View // override fun showHeadlines(headlines: MutableList<NewsHeadlines>) { Timber.d("showHeadlines() called with: categoriesHeadlines = [${headlines}]") setupNavigationDrawerAdapter(headlines) } override fun showHeadlineDetailsUi(newsHeadlineItem: NewsHeadlineItem?) { Timber.d("showHeadlineDetailsUi() called with: newsHeadlineItem = [${newsHeadlineItem}]") // NOTE: Details view on mobile is not supported to keep it minimal. } override fun showAppSettingsScreen() { Timber.d("showAppSettingsScreen() called") Toast.makeText(this, "Feature not implemented yet.", Toast.LENGTH_SHORT).show() } override fun showHeadlineBackdropBackground(imageUrl: String?) { Timber.d("showHeadlineBackdropBackground() called with: imageUrl = [${imageUrl}]") } override fun showDefaultBackground() { Timber.d("showDefaultBackground() called") } override fun toggleLoadingIndicator(active: Boolean) { Timber.d("toggleLoadingIndicator() called with: active = [${active}]") if (active) { news_headlines_loading_indicator.visibility = View.VISIBLE } else { news_headlines_loading_indicator.visibility = View.GONE } } override fun showDataLoadingError() { Timber.d("showDataLoadingError() called") Toast.makeText(this, "Failed to load news.", Toast.LENGTH_LONG).show() } override fun showDataNotAvailable() { Timber.d("showDataNotAvailable() called") } override fun showAddNewsSourceScreen() { Timber.d("showAddNewsSourceScreen() called") Toast.makeText(this, "Feature not implemented yet.", Toast.LENGTH_SHORT).show() } override fun showUiScreen(type: ScreenType) { Timber.d("showUiScreen() called with: type = [${type}]") Toast.makeText(this, "Feature not implemented yet.", Toast.LENGTH_SHORT).show() } }
mobile/src/main/java/info/hossainkhan/dailynewsheadlines/HeadlinesBrowseActivity.kt
1953360570
/* * Copyright (C) 2018, Alashov Berkeli * All rights reserved. */ package tm.alashow.base.util.extensions import android.content.res.Resources import androidx.annotation.StringRes import com.andretietz.retroauth.AuthenticationCanceledException import java.io.IOException import retrofit2.HttpException import tm.alashow.base.R import tm.alashow.base.util.ValidationErrorException import tm.alashow.domain.models.errors.ApiErrorException import tm.alashow.domain.models.errors.EmptyResultException @StringRes fun Throwable?.localizedTitle(): Int = when (this) { is EmptyResultException -> R.string.error_empty_title else -> R.string.error_title } @StringRes fun Throwable?.localizedMessage(): Int = when (this) { is ApiErrorException -> localizeApiError() is EmptyResultException -> R.string.error_empty is HttpException -> { when (code()) { 404 -> R.string.error_notFound 500 -> R.string.error_server 502 -> R.string.error_keyError 503 -> R.string.error_unavailable 403, 401 -> R.string.error_auth else -> R.string.error_unknown } } is AuthenticationCanceledException -> R.string.error_noAuth is AppError -> messageRes is RuntimeException, is IOException -> R.string.error_network is ValidationErrorException -> error.errorRes else -> R.string.error_unknown } fun ApiErrorException.localizeApiError(): Int = when (val errorRes = errorRes) { is Int -> errorRes else -> when (error.id) { "unknown" -> R.string.error_unknown else -> R.string.error_api } } val localizedApiMessages = mapOf( "test" to R.string.error_errorLogOut ) fun String.hasLocalizeApiMessage(): Boolean = localizedApiMessages.containsKey(this) fun String.tryToLocalizeApiMessage(resources: Resources, overrideOnFail: Boolean = true): String = when { localizedApiMessages.containsKey(this) -> resources.getString(localizedApiMessages[this] ?: 0) else -> if (overrideOnFail) resources.getString(R.string.error_unknown) else this } data class ThrowableString(val value: String) : Throwable() data class AppError(val messageRes: Int = R.string.error_unknown) : Throwable()
modules/base-android/src/main/java/tm/alashow/base/util/ThrowableExtensions.kt
1565067958
package cz.vhromada.catalog.gui.game import cz.vhromada.catalog.entity.Game import cz.vhromada.catalog.facade.GameFacade import cz.vhromada.catalog.gui.common.AbstractInfoDialog import cz.vhromada.catalog.gui.common.AbstractOverviewDataPanel import javax.swing.JPanel import javax.swing.JTabbedPane /** * A class represents panel with games' data. * * @author Vladimir Hromada */ class GamesPanel(private val gameFacade: GameFacade) : AbstractOverviewDataPanel<Game>(GamesListDataModel(gameFacade), GamesStatsTableDataModel(gameFacade)) { override fun getInfoDialog(add: Boolean, data: Game?): AbstractInfoDialog<Game> { return if (add) GameInfoDialog() else GameInfoDialog(data!!) } override fun deleteData() { gameFacade.newData() } override fun addData(data: Game) { gameFacade.add(data) } override fun updateData(data: Game) { gameFacade.update(data) } override fun removeData(data: Game) { gameFacade.remove(data) } override fun duplicatesData(data: Game) { gameFacade.duplicate(data) } override fun moveUpData(data: Game) { gameFacade.moveUp(data) } override fun moveDownData(data: Game) { gameFacade.moveDown(data) } override fun getDataPanel(data: Game): JPanel { return GameDataPanel(data) } override fun updateDataOnChange(dataPanel: JTabbedPane, data: Game) { // nothing } }
src/main/kotlin/cz/vhromada/catalog/gui/game/GamesPanel.kt
3425381494
package src.configuration import java.awt.Component import java.awt.LayoutManager import javax.swing.JFrame /** * Created by vicboma on 02/12/16. */ class DisplayImpl internal constructor(override var title: String, override val widht: Int?, override val heigth: Int?, override val visible: Boolean?, override val closeOp: Int?, override val layout: LayoutManager?, override val location: Component?) : Display { companion object { fun create(title: String, widht: Int?, heigth: Int?, visible: Boolean?): Display { return DisplayImpl(title, widht, heigth, visible, JFrame.EXIT_ON_CLOSE, null, null) } } }
14-start-async-menuBar-block-application/src/main/kotlin/components/display/DisplayImpl.kt
2100959178
package io.gitlab.arturbosch.detekt.api import java.io.PrintStream /** * Extension point which describes how findings should be printed on the console. * * Additional [ConsoleReport]'s can be made available through the [java.util.ServiceLoader] pattern. * If the default reporting mechanism should be turned off, exclude the entry 'FindingsReport' * in the 'console-reports' property of a detekt yaml config. */ abstract class ConsoleReport : Extension { /** * Prints the rendered report to the given printer * if anything was rendered at all. */ fun print(printer: PrintStream, detektion: Detektion) { val output = render(detektion) if (!output.isNullOrBlank()) { printer.println(output) } } /** * Converts the given [detektion] into a string representation * to present it to the client. * The implementation specifies which parts of the report are important to the user. */ abstract fun render(detektion: Detektion): String? }
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/ConsoleReport.kt
4156392676
package com.boardgamegeek.entities import com.boardgamegeek.extensions.asColorRgb data class PlayerColorEntity( val description: String, var sortOrder: Int = 0 ) { val rgb = description.asColorRgb() }
app/src/main/java/com/boardgamegeek/entities/PlayerColorEntity.kt
2010417384
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.entity import org.lanternpowered.api.cause.CauseStack import org.lanternpowered.api.cause.withFrame import org.lanternpowered.api.data.Keys import org.lanternpowered.api.event.EventManager import org.lanternpowered.api.item.inventory.Carrier import org.lanternpowered.api.item.inventory.ItemStack import org.lanternpowered.api.item.inventory.emptyItemStackSnapshot import org.lanternpowered.api.item.inventory.fix import org.lanternpowered.api.item.inventory.stack.asSnapshot import org.lanternpowered.api.item.inventory.stack.isNotEmpty import org.lanternpowered.api.item.inventory.stack.isSimilarTo import org.lanternpowered.api.util.duration.max import org.lanternpowered.api.util.math.plus import org.lanternpowered.api.util.math.times import org.lanternpowered.api.util.optional.orNull import org.lanternpowered.api.world.getIntersectingBlockCollisionBoxes import org.lanternpowered.api.world.getIntersectingEntities import org.lanternpowered.server.effect.entity.EntityEffectCollection import org.lanternpowered.server.effect.entity.EntityEffectTypes import org.lanternpowered.server.effect.entity.particle.item.ItemDeathParticleEffect import org.lanternpowered.server.entity.event.CollectEntityEvent import org.lanternpowered.server.event.LanternEventContextKeys import org.lanternpowered.server.event.LanternEventFactory import org.lanternpowered.server.network.entity.EntityProtocolTypes import org.spongepowered.api.entity.Item import org.spongepowered.api.entity.living.Living import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent.Pickup import org.spongepowered.api.util.AABB import org.spongepowered.api.util.Direction import org.spongepowered.math.vector.Vector3d import kotlin.time.Duration import kotlin.time.seconds class LanternItem(creationData: EntityCreationData) : LanternEntity(creationData), Item { companion object { val DEFAULT_EFFECT_COLLECTION = EntityEffectCollection.builder() .add(EntityEffectTypes.DEATH, ItemDeathParticleEffect) .build() val BOUNDING_BOX_EXTENT = AABB(Vector3d(-0.125, 0.0, -0.125), Vector3d(0.125, 0.25, 0.125)) val DROPPED_PICKUP_DELAY = 2.seconds } private var timer = Duration.ZERO init { this.protocolType = EntityProtocolTypes.ITEM this.boundingBoxExtent = BOUNDING_BOX_EXTENT this.effectCollection = DEFAULT_EFFECT_COLLECTION.copy() keyRegistry { register(Keys.ITEM_STACK_SNAPSHOT, emptyItemStackSnapshot()) registerBounded(Keys.PICKUP_DELAY, 0.5.seconds).minimum(Duration.ZERO).coerceInBounds() registerBounded(Keys.DESPAWN_DELAY, 300.seconds).minimum(Duration.ZERO).coerceInBounds() register(Keys.GRAVITATIONAL_ACCELERATION, 0.04) register(Keys.INFINITE_PICKUP_DELAY, false) register(Keys.INFINITE_DESPAWN_DELAY, false) } } override fun update(deltaTime: Duration) { super.update(deltaTime) var pickupDelay = this.require(Keys.PICKUP_DELAY) var despawnDelay = this.require(Keys.DESPAWN_DELAY) val infinitePickupDelay = this.require(Keys.INFINITE_PICKUP_DELAY) val infiniteDespawnDelay = this.require(Keys.INFINITE_DESPAWN_DELAY) val oldPickupDelay = pickupDelay val oldDespawnDelay = despawnDelay if (!infinitePickupDelay) pickupDelay -= deltaTime if (!infiniteDespawnDelay) despawnDelay -= deltaTime this.timer += deltaTime val timer = this.timer if (timer > 1.seconds) { val data = combineItemStacks(pickupDelay, despawnDelay) if (data != null) { pickupDelay = data.pickupDelay despawnDelay = data.despawnDelay // Play the merge effect? this.effectCollection.getCombinedOrEmpty(EntityEffectTypes.MERGE).play(this) } this.timer = Duration.ZERO } if (timer > 0.5.seconds && !infinitePickupDelay && pickupDelay <= Duration.ZERO) this.tryToPickupItems() if (pickupDelay != oldPickupDelay) this.offer(Keys.PICKUP_DELAY, pickupDelay) if (despawnDelay != oldDespawnDelay) this.offer(Keys.DESPAWN_DELAY, despawnDelay) if (despawnDelay <= Duration.ZERO) { CauseStack.withFrame { frame -> frame.pushCause(this) // Throw the expire entity event val event = LanternEventFactory.createExpireEntityEvent( frame.currentCause, this) EventManager.post(event) // Remove the item, also within this context this.remove() } // Play the death effect? this.effectCollection.getCombinedOrEmpty(EntityEffectTypes.DEATH).play(this) } else { this.updatePhysics(deltaTime) } } private fun updatePhysics(deltaTime: Duration) { // Get the current velocity var velocity = this.require(Keys.VELOCITY) // Update the position based on the velocity this.position = this.position + (velocity * deltaTime.inSeconds) // We will check if there is a collision box under the entity var ground = false val thisBox = this.boundingBox.get().offset(0.0, -0.1, 0.0) val boxes: Set<AABB> = this.world.getIntersectingBlockCollisionBoxes(thisBox) for (box in boxes) { val factor = box.center.sub(thisBox.center) if (Direction.getClosest(factor).isUpright) ground = true } if (!ground && this.get(Keys.IS_GRAVITY_AFFECTED).orElse(true)) { val constant = this.get(Keys.GRAVITATIONAL_ACCELERATION).orNull() if (constant != null) { // Apply the gravity factor velocity = velocity.add(0.0, -constant * deltaTime.inSeconds, 0.0) } } velocity = velocity.mul(0.98, 0.98, 0.98) if (ground) velocity = velocity.mul(1.0, -0.5, 1.0) // Offer the velocity back this.offer(Keys.VELOCITY, velocity) } private fun tryToPickupItems() { val entities = this.world.getIntersectingEntities( this.boundingBox.get().expand(2.0, 0.5, 2.0)) { entity -> entity !== this && entity is Carrier } if (entities.isEmpty()) return val stack = this.require(Keys.ITEM_STACK_SNAPSHOT).createStack() if (stack.isEmpty) { this.remove() return } // TODO: Call pre pickup event for (entity in entities) { // Ignore dead entities if (entity is LanternLiving && entity.isDead) continue val inventory = (entity as Carrier).inventory.fix() /* if (inventory is PlayerInventory) { // TODO: Get priority hotbar inventory //inventory = inventory.primary.transform(InventoryTransforms.PRIORITY_HOTBAR) } */ // Copy before consuming val originalStack = stack.copy() val peekResult = inventory.peekOffer(stack) var event: Pickup CauseStack.withFrame { frame -> frame.addContext(LanternEventContextKeys.ORIGINAL_ITEM_STACK, originalStack) if (stack.isNotEmpty) frame.addContext(LanternEventContextKeys.REST_ITEM_STACK, stack) event = LanternEventFactory.createChangeInventoryEventPickup( frame.currentCause, inventory, peekResult.transactions) event.isCancelled = peekResult.transactions.isEmpty() EventManager.post(event) } // Don't continue if the entity was removed during the event if (event.isCancelled && !this.isRemoved) continue event.transactions.stream() .filter { transaction -> transaction.isValid } .forEach { transaction -> transaction.slot.set(transaction.final.createStack()) } val added = originalStack.quantity - stack.quantity if (added != 0 && entity is Living) this.triggerEvent(CollectEntityEvent(entity as Living, added)) if (this.isRemoved) stack.quantity = 0 if (stack.isEmpty) break } if (stack.isNotEmpty) { this.offer(Keys.ITEM_STACK_SNAPSHOT, stack.asSnapshot()) } else { this.remove() } } private inner class CombineData( val pickupDelay: Duration, val despawnDelay: Duration ) private fun combineItemStacks(pickupDelay: Duration, despawnDelay: Duration): CombineData? { // Remove items with no item stack val item = this.require(Keys.ITEM_STACK_SNAPSHOT) if (item.isEmpty) { this.remove() return null } val max = item.type.maxStackQuantity var quantity = item.quantity // Check if the stack is already at it's maximum size if (quantity >= max) return null val frame = CauseStack.pushCauseFrame() frame.pushCause(this) // Search for surrounding items val entities = this.world.getIntersectingEntities( this.boundingBox.get().expand(0.6, 0.0, 0.6)) { entity -> entity !== this && entity is LanternItem } var newPickupDelay = pickupDelay var newDespawnDelay = despawnDelay var newItem: ItemStack? = null for (other in entities) { val otherInfinitePickupDelay = other.require(Keys.INFINITE_PICKUP_DELAY) if (otherInfinitePickupDelay) continue val otherPickupDelay = other.require(Keys.PICKUP_DELAY) val otherItem = other.require(Keys.ITEM_STACK_SNAPSHOT) var otherQuantity = otherItem.quantity // Don't bother stacks that are already filled and // make sure that the stacks can be merged if (otherQuantity >= max || !item.isSimilarTo(otherItem)) continue // Call the merge event val event = LanternEventFactory.createItemMergeWithItemEvent( frame.currentCause, other as Item, this) EventManager.post(event) if (event.isCancelled) continue // Merge the items quantity += otherQuantity if (quantity > max) { otherQuantity = quantity - max quantity = max // Create a new stack and offer it back the entity val newOtherItem = otherItem.createStack() newOtherItem.quantity = otherQuantity // The snapshot can be wrapped other.offer(Keys.ITEM_STACK_SNAPSHOT, newOtherItem.asSnapshot()) } else { // The other entity is completely drained and will be removed other.offer(Keys.ITEM_STACK_SNAPSHOT, emptyItemStackSnapshot()) other.remove() } // The item stack has changed if (newItem == null) newItem = item.createStack() newItem!!.quantity = quantity // When merging items, also merge the pickup and despawn delays newPickupDelay = max(newPickupDelay, otherPickupDelay) newDespawnDelay = max(newDespawnDelay, other.require(Keys.DESPAWN_DELAY)) // The stack is already full, stop here if (quantity == max) break } frame.close() if (newItem != null) { this.offer(Keys.ITEM_STACK_SNAPSHOT, newItem.asSnapshot()) return CombineData(newPickupDelay, newDespawnDelay) } return null } }
src/main/kotlin/org/lanternpowered/server/entity/LanternItem.kt
869772953
package kotlinx.serialization.cbor import kotlinx.serialization.decodeFromByteArray import kotlinx.serialization.encodeToByteArray import kotlin.test.Test import kotlin.test.assertEquals class CborNumberEncodingTest { // 0-23 packs into a single byte @Test fun testEncodingLengthOfTinyNumbers() { val tinyNumbers = listOf(0, 1, 23) for (number in tinyNumbers) { assertEquals( expected = 1, actual = Cbor.encodeToByteArray(number).size, "when encoding value '$number'" ) } } // 24..(2^8-1) packs into 2 bytes @Test fun testEncodingLengthOf8BitNumbers() { val tinyNumbers = listOf(24, 127, 128, 255) for (number in tinyNumbers) { assertEquals( expected = 2, actual = Cbor.encodeToByteArray(number).size, "when encoding value '$number'" ) } } // 2^8..(2^16-1) packs into 3 bytes @Test fun testEncodingLengthOf16BitNumbers() { val tinyNumbers = listOf(256, 32767, 32768, 65535) for (number in tinyNumbers) { assertEquals( expected = 3, actual = Cbor.encodeToByteArray(number).size, "when encoding value '$number'" ) } } // 2^16..(2^32-1) packs into 5 bytes @Test fun testEncodingLengthOf32BitNumbers() { val tinyNumbers = listOf(65536, 2147483647, 2147483648, 4294967295) for (number in tinyNumbers) { assertEquals( expected = 5, actual = Cbor.encodeToByteArray(number).size, "when encoding value '$number'" ) } } // 2^32+ packs into 9 bytes @Test fun testEncodingLengthOfLargeNumbers() { val tinyNumbers = listOf(4294967296, 8589934592) for (number in tinyNumbers) { assertEquals( expected = 9, actual = Cbor.encodeToByteArray(number).size, "when encoding value '$number'" ) } } @Test fun testEncodingLargestPositiveTinyNumber() { assertEquals( expected = byteArrayOf(23).toList(), actual = Cbor.encodeToByteArray(23).toList(), ) } @Test fun testDecodingLargestPositiveTinyNumber() { assertEquals( expected = 23, actual = Cbor.decodeFromByteArray(byteArrayOf(23)), ) } @Test fun testEncodingLargestNegativeTinyNumber() { assertEquals( expected = byteArrayOf(55).toList(), actual = Cbor.encodeToByteArray(-24).toList(), ) } @Test fun testDecodingLargestNegativeTinyNumber() { assertEquals( expected = -24, actual = Cbor.decodeFromByteArray(byteArrayOf(55)), ) } @Test fun testEncodingLargestPositive8BitNumber() { val bytes = listOf(24, 255).map { it.toByte() } assertEquals( expected = bytes, actual = Cbor.encodeToByteArray(255).toList(), ) } @Test fun testDecodingLargestPositive8BitNumber() { val bytes = listOf(24, 255).map { it.toByte() }.toByteArray() assertEquals( expected = 255, actual = Cbor.decodeFromByteArray(bytes), ) } @Test fun testEncodingLargestNegative8BitNumber() { val bytes = listOf(56, 255).map { it.toByte() } assertEquals( expected = bytes, actual = Cbor.encodeToByteArray(-256).toList(), ) } @Test fun testDecodingLargestNegative8BitNumber() { val bytes = listOf(56, 255).map { it.toByte() }.toByteArray() assertEquals( expected = -256, actual = Cbor.decodeFromByteArray(bytes), ) } @Test fun testEncodingLargestPositive16BitNumber() { val bytes = listOf(25, 255, 255).map { it.toByte() } assertEquals( expected = bytes, actual = Cbor.encodeToByteArray(65535).toList(), ) } @Test fun testDecodingLargestPositive16BitNumber() { val bytes = listOf(25, 255, 255).map { it.toByte() }.toByteArray() assertEquals( expected = 65535, actual = Cbor.decodeFromByteArray(bytes), ) } @Test fun testEncodingLargestNegative16BitNumber() { val bytes = listOf(57, 255, 255).map { it.toByte() } assertEquals( expected = bytes, actual = Cbor.encodeToByteArray(-65536).toList(), ) } @Test fun testDecodingLargestNegative16BitNumber() { val bytes = listOf(57, 255, 255).map { it.toByte() }.toByteArray() assertEquals( expected = -65536, actual = Cbor.decodeFromByteArray(bytes), ) } @Test fun testEncodingLargestPositive32BitNumber() { val bytes = listOf(26, 255, 255, 255, 255).map { it.toByte() } assertEquals( expected = bytes, actual = Cbor.encodeToByteArray(4294967295).toList(), ) } @Test fun testDecodingLargestPositive32BitNumber() { val bytes = listOf(26, 255, 255, 255, 255).map { it.toByte() }.toByteArray() assertEquals( expected = 4294967295, actual = Cbor.decodeFromByteArray(bytes), ) } @Test fun testEncodingLargestNegative32BitNumber() { val bytes = listOf(58, 255, 255, 255, 255).map { it.toByte() } assertEquals( expected = bytes, actual = Cbor.encodeToByteArray(-4294967296).toList(), ) } @Test fun testDecodingLargestNegative32BitNumber() { val bytes = listOf(58, 255, 255, 255, 255).map { it.toByte() }.toByteArray() assertEquals( expected = -4294967296, actual = Cbor.decodeFromByteArray(bytes), ) } }
formats/cbor/commonTest/src/kotlinx/serialization/cbor/CborNumberEncodingTest.kt
2207426944
package ch.difty.scipamato.common import org.amshove.kluent.shouldBeInstanceOf import org.junit.jupiter.api.Test internal class PublicPersistenceJooqUtilConfigurationTest { @Test fun dateTimeService() { PublicPersistenceJooqUtilConfiguration().dateTimeService() shouldBeInstanceOf CurrentDateTimeService::class } }
public/public-persistence-jooq/src/test/kotlin/ch/difty/scipamato/common/PublicPersistenceJooqUtilConfigurationTest.kt
2292202270
package me.echeung.moemoekyun.service.auto import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaDescriptionCompat import androidx.media.MediaBrowserServiceCompat import me.echeung.moemoekyun.App import me.echeung.moemoekyun.R import me.echeung.moemoekyun.service.RadioService class AutoMediaBrowserService : MediaBrowserServiceCompat(), ServiceConnection { override fun onCreate() { super.onCreate() if (App.service != null) { setSessionToken() } else { val intent = Intent(applicationContext, RadioService::class.java) applicationContext.bindService(intent, this, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT) } } override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? { return BrowserRoot(MEDIA_ID_ROOT, null) } override fun onLoadChildren(parentId: String, result: Result<List<MediaBrowserCompat.MediaItem>>) { val mediaItems = listOf( createPlayableMediaItem(RadioService.LIBRARY_JPOP, resources.getString(R.string.jpop)), createPlayableMediaItem(RadioService.LIBRARY_KPOP, resources.getString(R.string.kpop)), ) result.sendResult(mediaItems) } override fun onServiceConnected(className: ComponentName, service: IBinder) { val binder = service as RadioService.ServiceBinder val radioService = binder.service App.service = radioService setSessionToken() } override fun onServiceDisconnected(arg0: ComponentName) { } private fun setSessionToken() { val mediaSession = App.service!!.mediaSession sessionToken = mediaSession!!.sessionToken } private fun createPlayableMediaItem(mediaId: String, title: String): MediaBrowserCompat.MediaItem { val builder = MediaDescriptionCompat.Builder() .setMediaId(mediaId) .setTitle(title) return MediaBrowserCompat.MediaItem(builder.build(), MediaBrowserCompat.MediaItem.FLAG_PLAYABLE) } } private const val MEDIA_ID_ROOT = "media_root"
app/src/main/kotlin/me/echeung/moemoekyun/service/auto/AutoMediaBrowserService.kt
2417044205
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.watchnext import android.annotation.SuppressLint import android.app.Application import android.content.Context import androidx.work.Worker import androidx.work.WorkerParameters import com.android.tv.reference.repository.VideoRepositoryFactory import com.android.tv.reference.shared.datamodel.VideoType import timber.log.Timber /** * Worker triggered by WorkManager to add/update/remove video to Watch Next channel. * * <code> * WorkManager.getInstance(context).enqueue(OneTimeWorkRequest.Builder(WatchNextWorker::class.java).build()) * </code> */ class WatchNextWorker(private val context: Context, params: WorkerParameters) : Worker(context, params) { /** * Worker thread to add/update/remove content from Watch Next channel. * Events triggered from player state change events & * playback lifecycle events (onPause) are consumed here. */ @SuppressLint("RestrictedApi") override fun doWork(): Result { // Step 1 : get the video information from the "inputData". val videoId = inputData.getString(WatchNextHelper.VIDEO_ID) val watchPosition = inputData.getLong(WatchNextHelper.CURRENT_POSITION, /* defaultValue= */ 0) val state = inputData.getString(WatchNextHelper.PLAYER_STATE) Timber.v("Work Manager called watch id $videoId , watchTime $watchPosition") // Step 2 : Check for invalid inputData. // If videoId is invalid, abort worker and return. if (videoId.isNullOrEmpty()) { Timber.e("Error.Invalid entry for Watch Next. videoid: $videoId") return Result.failure() } // Check for invalid player state. if ((state != WatchNextHelper.PLAY_STATE_PAUSED) and (state != WatchNextHelper.PLAY_STATE_ENDED) ) { Timber.e("Error.Invalid entry for Watch Next. Player state: $state") return Result.failure() } // Step 3: Get video object from videoId to be added to Watch Next. val video = VideoRepositoryFactory.getVideoRepository(context.applicationContext as Application) .getVideoById(videoId) Timber.v("Retrieved video from repository with id %s, %s", videoId, video) // Step 4 : Handle Watch Next for different types of content. when (video?.videoType) { VideoType.MOVIE -> { Timber.v("Add Movie to Watch Next : id = ${video.id}") WatchNextHelper.handleWatchNextForMovie(video, watchPosition.toInt(), state, context) } VideoType.EPISODE -> { Timber.v("Add Episode to Watch Next : id = ${video.id}") WatchNextHelper.handleWatchNextForEpisode( video, watchPosition.toInt(), state, VideoRepositoryFactory.getVideoRepository( context.applicationContext as Application), context) } VideoType.CLIP -> Timber.w( "NOT recommended to add Clips / Trailers /Short videos to Watch Next " ) else -> Timber.e("Invalid category for Video Type: ${video?.videoType}") } Timber.v("WatchNextWorker finished") return Result.success() } }
step_4_completed/src/main/java/com/android/tv/reference/watchnext/WatchNextWorker.kt
2959649352
/* * Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.core.compress /** * ์••์ถ•/๋ณต์›์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. * @author [email protected] */ interface Compressor { /** * ์ง€์ •๋œ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด์„ ์••์ถ•ํ•ฉ๋‹ˆ๋‹ค. * * @param ์••์ถ•์„ ํ‘ผ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด * @return input ์••์ถ•๋œ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด */ fun compress(input: ByteArray?): ByteArray /** * ์••์ถ•๋œ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด์„ ์••์ถ•์„ ํ’‰๋‹ˆ๋‹ค. * * @param input ์••์ถ•๋œ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด * @return ์••์ถ•์„ ํ‘ผ ๋ฐ”์ดํŠธ ๋ฐฐ์—ด */ fun decompress(input: ByteArray?): ByteArray }
debop4k-core/src/main/kotlin/debop4k/core/compress/Compressor.kt
986473276
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.watchnext import android.content.Context import android.util.Log import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.work.Configuration import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.testing.WorkManagerTestInitHelper import com.android.tv.reference.shared.datamodel.Video import com.android.tv.reference.shared.datamodel.VideoType import com.android.tv.reference.shared.playback.VideoPlaybackState import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class WatchNextPlaybackStateListenerTest { private val context = ApplicationProvider.getApplicationContext() as Context private val watchNextPlaybackStateListener = WatchNextPlaybackStateListener(context) private lateinit var workManager: WorkManager @Before fun setUp() { val config = Configuration.Builder() .setMinimumLoggingLevel(Log.DEBUG) .build() WorkManagerTestInitHelper.initializeTestWorkManager(context, config) workManager = WorkManager.getInstance(context) } @Test fun onChanged_pauseState_enqueuesWorkRequest() { watchNextPlaybackStateListener.onChanged(VideoPlaybackState.Pause(VIDEO, position = 10L)) val workInfos: List<WorkInfo> = workManager.getWorkInfosByTag(WatchNextWorker::class.java.name).get() assertThat(workInfos).hasSize(1) } @Test fun onChanged_endState_enqueuesWorkRequest() { watchNextPlaybackStateListener.onChanged(VideoPlaybackState.End(VIDEO)) val workInfos: List<WorkInfo> = workManager.getWorkInfosByTag(WatchNextWorker::class.java.name).get() assertThat(workInfos).hasSize(1) } @Test fun onChanged_nonPauseOrEndState_doesNotEnqueWork() { watchNextPlaybackStateListener.onChanged(VideoPlaybackState.Load(VIDEO)) val workInfos: List<WorkInfo> = workManager.getWorkInfosByTag(WatchNextWorker::class.java.name).get() assertThat(workInfos).isEmpty() } companion object { private val VIDEO = Video( id = "id", name = "name", description = "description", uri = "https://example.com/id", videoUri = "https://example.com/video/id", thumbnailUri = "https://example.com/thumbnail/id", backgroundImageUri = "https://example.com/background/id", category = "Test", videoType = VideoType.MOVIE, duration = "PT00H10M" // 10 Minutes ) } }
step_4_completed/src/test/java/com/android/tv/reference/watchnext/WatchNextPlaybackStateListenerTest.kt
693379571
package com.asamm.locus.api.sample.mapServer import android.graphics.BitmapFactory import locus.api.android.features.mapProvider.MapTileService import locus.api.android.features.mapProvider.data.MapConfigLayer import locus.api.android.features.mapProvider.data.MapTileRequest import locus.api.android.features.mapProvider.data.MapTileResponse import locus.api.utils.Logger import locus.api.utils.Utils import java.io.ByteArrayOutputStream import java.io.InputStream import java.util.* /** * Service that provide map data to Locus Map application. * * Service is not yet fully working, so consider this as "work in progress". */ class MapProvider : MapTileService() { override val mapConfigs: List<MapConfigLayer> get() = generateMapConfig() override fun getMapTile(request: MapTileRequest): MapTileResponse { return loadMapTile(request) } private fun generateMapConfig(): List<MapConfigLayer> { val maps = ArrayList<MapConfigLayer>() maps.add(generateMapConfiguration(0)) maps.add(generateMapConfiguration(1)) maps.add(generateMapConfiguration(2)) return maps } private fun generateMapConfiguration(zoom: Int): MapConfigLayer { val mapSize = 1 shl zoom + 8 // create empty object and set projection (Spherical Mercator) val mapConfig = MapConfigLayer() mapConfig.projEpsg = 3857 // set name and description mapConfig.name = "OSM MapQuest" mapConfig.description = "Testing map" // define size of tiles mapConfig.tileSizeX = 256 mapConfig.tileSizeY = 256 // define size of map mapConfig.xmax = mapSize.toLong() mapConfig.ymax = mapSize.toLong() // specify zoom level mapConfig.zoom = zoom // add at least two calibration points val maxX = 20037508.343 val maxY = 20037508.343 mapConfig.addCalibrationPoint(0.0, 0.0, maxY, -maxX) mapConfig.addCalibrationPoint(mapSize.toDouble(), 0.0, maxY, maxX) mapConfig.addCalibrationPoint(0.0, mapSize.toDouble(), -maxY, -maxX) mapConfig.addCalibrationPoint(mapSize.toDouble(), mapSize.toDouble(), -maxY, maxX) // return generated map return mapConfig } private fun loadMapTile(request: MapTileRequest): MapTileResponse { val resp = MapTileResponse() // load images val fileName = "tile_" + request.tileX + "_" + request.tileY + "_" + request.tileZoom + ".jpg" val tileData = loadMapTile(fileName) if (tileData == null || tileData.isEmpty()) { resp.resultCode = MapTileResponse.CODE_NOT_EXISTS return resp } // convert to bitmap val img = BitmapFactory.decodeByteArray(tileData, 0, tileData.size) return if (img == null) { resp.resultCode = MapTileResponse.CODE_INTERNAL_ERROR resp } else { resp.resultCode = MapTileResponse.CODE_VALID resp.image = img resp } } private fun loadMapTile(name: String): ByteArray? { var input: InputStream? = null return try { input = assets.open("map_tiles/$name") ByteArrayOutputStream() .apply { input.copyTo(this) } .toByteArray() } catch (e: Exception) { Logger.logE(TAG, "loadMapTile($name), not exists", e) null } finally { Utils.closeStream(input) } } companion object { // tag for logger private const val TAG = "MapProvider" } }
locus-api-android-sample/src/main/java/com/asamm/locus/api/sample/mapServer/MapProvider.kt
3401466999
package ru.nsu.bobrofon.easysshfs import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.NetworkInfo import android.net.wifi.WifiManager import android.os.Handler import android.util.Log import com.topjohnwu.superuser.Shell import ru.nsu.bobrofon.easysshfs.mountpointlist.MountPointsList private const val TAG = "InternetStateChange" private const val AUTO_MOUNT_DELAY_MILLIS: Long = 5000 class InternetStateChangeReceiver( private val handler: Handler ) : BroadcastReceiver() { private val shell: Shell by lazy { EasySSHFSActivity.initNewShell() } override fun onReceive(context: Context, intent: Intent) { if (WifiManager.NETWORK_STATE_CHANGED_ACTION != intent.action) { return } Log.d(TAG, "network state changed") val info = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO) ?: return val mountPointsList = MountPointsList.instance(context) handler.removeCallbacksAndMessages(null) // ignore repeated intents if (info.isConnected) { Log.d(TAG, "network is connected") handler.postDelayed({autoMount(mountPointsList, shell)}, AUTO_MOUNT_DELAY_MILLIS) } else { Log.d(TAG, "unmount everything") handler.post { forceUmount(mountPointsList, shell) } } } private fun autoMount(mountPointsList: MountPointsList, shell: Shell) { Log.d(TAG, "check auto-mount") if (mountPointsList.needAutomount()) { Log.d(TAG, "auto-mount required") mountPointsList.autoMount(shell) } } private fun forceUmount(mountPointsList: MountPointsList, shell: Shell) { Log.d(TAG, "force umount everything") mountPointsList.umount(shell) } }
app/src/main/java/ru/nsu/bobrofon/easysshfs/InternetStateChangeReceiver.kt
4068072215
package org.worshipsongs.adapter import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import org.worshipsongs.CommonConstants import org.worshipsongs.fragment.SongContentPortraitViewFragment import org.worshipsongs.service.PresentationScreenService import java.util.* /** * author : Madasamy * version : 2.1.0 */ class SongContentPortraitViewerPageAdapter(private val fragmentManager: FragmentManager, private val bundle: Bundle, private val presentationScreenService: PresentationScreenService) : FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_SET_USER_VISIBLE_HINT) { private val titles: ArrayList<String>? init { this.titles = bundle.getStringArrayList(CommonConstants.TITLE_LIST_KEY) } override fun getItem(position: Int): Fragment { Log.i(this.javaClass.simpleName, "No of songs" + titles!!.size) val title = titles[position] bundle.putString(CommonConstants.TITLE_KEY, title) val songContentPortraitViewFragment = SongContentPortraitViewFragment.newInstance(bundle) songContentPortraitViewFragment.presentationScreenService = presentationScreenService return songContentPortraitViewFragment } override fun getPageTitle(position: Int): CharSequence? { return "" } override fun getCount(): Int { return titles!!.size } }
app/src/main/java/org/worshipsongs/adapter/SongContentPortraitViewerPageAdapter.kt
3818610168
package io.clappr.player.plugin.control import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.LinearLayout import android.widget.TextView import io.clappr.player.R import io.clappr.player.base.Event import io.clappr.player.base.InternalEvent import io.clappr.player.base.NamedType import io.clappr.player.components.Core import io.clappr.player.components.Playback import io.clappr.player.extensions.asTimeInterval import io.clappr.player.extensions.unlessChromeless import io.clappr.player.plugin.PluginEntry open class TimeIndicatorPlugin(core: Core) : MediaControl.Plugin(core, name) { companion object : NamedType { override val name = "timeIndicator" val entry = PluginEntry.Core( name = name, factory = ::TimeIndicatorPlugin.unlessChromeless() ) } override var panel: Panel = Panel.BOTTOM override var position: Position = Position.LEFT protected val textView by lazy { LayoutInflater.from(applicationContext).inflate(R.layout.time_indicator, null) as TextView } override val view: View? get() = textView private val playbackListenerIds = mutableListOf<String>() init { listenTo(core, InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value, { setupPlaybackListeners() }) updateLiveStatus() } private fun setupPlaybackListeners() { updateLiveStatus() stopPlaybackListeners() core.activePlayback?.let { updateValue(null) playbackListenerIds.add(listenTo(it, Event.DID_LOAD_SOURCE.value) { setupPlaybackListeners() }) playbackListenerIds.add(listenTo(it, Event.DID_UPDATE_POSITION.value) { bundle -> updateValue(bundle) }) playbackListenerIds.add(listenTo(it, Event.DID_COMPLETE.value) { hide() }) } } private fun stopPlaybackListeners() { playbackListenerIds.forEach(::stopListening) playbackListenerIds.clear() } private fun updateLiveStatus() { val isVOD = core.activePlayback?.mediaType == Playback.MediaType.VOD view?.visibility = if (!isVOD || isPlaybackIdle) View.GONE else View.VISIBLE } private fun updateValue(bundle: Bundle?) { (bundle ?: Bundle()).let { val position = it.getDouble("time", 0.0) val duration = core.activePlayback?.duration ?: 0.0 textView.text = "%s / %s".format(position.asTimeInterval(), duration.asTimeInterval()) } updateLiveStatus() } override fun render() { val height = applicationContext.resources?.getDimensionPixelSize(R.dimen.time_indicator_height) ?: 0 val layoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, height) layoutParams.gravity = Gravity.CENTER_VERTICAL textView.layoutParams = layoutParams textView.text = "00:00 / 00:00" } override fun destroy() { stopPlaybackListeners() super.destroy() } }
clappr/src/main/kotlin/io/clappr/player/plugin/control/TimeIndicatorPlugin.kt
1552076621